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): spike hand-drawn lines via Terra Draw, persisted as notes
Clauded890c0aaddd9
diff --git a/apps/client/package.json b/apps/client/package.jsonindex 0775b9b1c2..fbc2e5a2be 100644--- a/apps/client/package.json+++ b/apps/client/package.json@@ -70,7 +70,9 @@"rrule": "2.8.1","svg-pan-zoom": "3.6.2","tabulator-tables": "6.5.2",- "temporal-polyfill": "1.0.3"+ "temporal-polyfill": "1.0.3",+ "terra-draw": "1.32.3",+ "terra-draw-maplibre-gl-adapter": "1.4.1"},"devDependencies": {"@ckeditor/ckeditor5-inspector": "5.0.3",diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 9835093ea1..8a74550a2b 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2851,6 +2851,10 @@"create-child-note-instruction": "Click on the map to create a new note at that location or press Escape to dismiss.","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-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.","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.tsxnew file mode 100644index 0000000000..1abefde448--- /dev/null+++ b/apps/client/src/widgets/collections/geomap/DrawLine.tsx@@ -0,0 +1,63 @@+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/EditToolbar.spec.tsx b/apps/client/src/widgets/collections/geomap/EditToolbar.spec.tsxindex ce1a3d0071..c11f62e981 100644--- a/apps/client/src/widgets/collections/geomap/EditToolbar.spec.tsx+++ b/apps/client/src/widgets/collections/geomap/EditToolbar.spec.tsx@@ -1,7 +1,7 @@/**- * The bar of editing actions over a geo map (see EditToolbar.tsx). What is checked is the one- * button it holds so far: that a press arms the map and a press on an armed one stands it down,- * that the mode is worn as held down, and that a map that may not be edited refuses it.+ * The bar of editing actions over a geo map (see EditToolbar.tsx). What is checked of each button+ * is that a press arms the map and a press on an armed one stands it down, that an armed mode is+ * worn as held down, and that a map that may not be edited refuses them all.*/import { act } from "preact/test-utils";import { describe, expect, it, vi } from "vitest";@@ -11,14 +11,15 @@ 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 } = {}) {+function renderBar({ map = {} as never, isReadOnly = false, placing = false, drawing = false } = {}) {const onTogglePlacement = vi.fn();+ const onToggleDrawing = vi.fn();const onAddGpxTrack = vi.fn();let container: HTMLElement | undefined;act(() => {container = renderInto(<ParentMap.Provider value={map}>- <EditToolbar isReadOnly={isReadOnly} placing={placing} onTogglePlacement={onTogglePlacement} onAddGpxTrack={onAddGpxTrack} />+ <EditToolbar isReadOnly={isReadOnly} placing={placing} onTogglePlacement={onTogglePlacement} drawing={drawing} onToggleDrawing={onToggleDrawing} onAddGpxTrack={onAddGpxTrack} /></ParentMap.Provider>);});@@ -27,11 +28,13 @@ function renderBar({ map = {} as never, isReadOnly = false, placing = false } =const all = () => [ ...container?.querySelectorAll<HTMLButtonElement>(".geo-edit-toolbar button") ?? [] ];return {onTogglePlacement,+ onToggleDrawing,onAddGpxTrack,buttons: all,/** The first button, which is the +. */button: () => all()[0] ?? null,- gpxButton: () => all()[1] ?? null+ drawButton: () => all()[1] ?? null,+ gpxButton: () => all()[2] ?? null};}@@ -57,6 +60,19 @@ 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);++ act(() => drawButton()?.click());+ expect(onToggleDrawing).toHaveBeenCalledTimes(1);++ const armed = renderBar({ drawing: true });+ expect(armed.drawButton()?.classList.contains("active")).toBe(true);+ });+it("offers to bring in a GPX track, and hands the asking to the map view", () => {const { gpxButton, onAddGpxTrack } = renderBar();diff --git a/apps/client/src/widgets/collections/geomap/EditToolbar.tsx b/apps/client/src/widgets/collections/geomap/EditToolbar.tsxindex 2b2a00c817..95b3286fb3 100644--- a/apps/client/src/widgets/collections/geomap/EditToolbar.tsx+++ b/apps/client/src/widgets/collections/geomap/EditToolbar.tsx@@ -15,6 +15,10 @@ 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;/** Asks for a GPX file and brings it onto the map (see `addGpxTrack` in index.tsx). */onAddGpxTrack: () => void;}@@ -36,9 +40,10 @@ 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, onAddGpxTrack }: EditToolbarProps) {+export default function EditToolbar({ isReadOnly, placing, onTogglePlacement, drawing, 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@@ -47,6 +52,10 @@ export default function EditToolbar({ isReadOnly, placing, onTogglePlacement, ontitle: 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).@@ -71,9 +80,17 @@ export default function EditToolbar({ isReadOnly, placing, onTogglePlacement, onthe pointer once armed. A child rather than a class on the button: the boxiconsclass sets the icon font on whatever wears it, and the words beside it are tostay words. */}- <span className="bx bx-pin" aria-hidden="true"></span>+ <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}+ /><buttonref={gpxRef}type="button"diff --git a/apps/client/src/widgets/collections/geomap/LineShape.spec.tsx b/apps/client/src/widgets/collections/geomap/LineShape.spec.tsxnew file mode 100644index 0000000000..89e1256a87--- /dev/null+++ b/apps/client/src/widgets/collections/geomap/LineShape.spec.tsx@@ -0,0 +1,135 @@+/**+ * 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.+ */+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { LineShape, lineShapeSourceId } from "./LineShape";+import { MapStyleLoaded, ParentMap } from "./map";++/**+ * A map as MapLibre behaves, in the one respect that matters here: a source or a layer can only be+ * added to a style that has finished loading, and asking for one before then throws.+ */+function fakeMap() {+ const sources = new Map<string, unknown>();+ const layers = new Map<string, unknown>();+ const listeners = new Map<string, (() => void)[]>();+ let loaded = false;++ return {+ sources,+ layers,++ on(type: string, listener: () => void) {+ listeners.set(type, [ ...(listeners.get(type) ?? []), listener ]);+ },+ off(type: string, listener: () => void) {+ listeners.set(type, (listeners.get(type) ?? []).filter((l) => l !== listener));+ },+ getSource(id: string) {+ return sources.get(id);+ },+ getLayer(id: string) {+ return layers.get(id);+ },+ addSource(id: string, source: unknown) {+ if (!loaded) throw new Error("Style is not done loading");+ sources.set(id, source);+ },+ addLayer(layer: { id: string }) {+ if (!loaded) throw new Error("Style is not done loading");+ layers.set(layer.id, layer);+ },+ removeSource(id: string) {+ sources.delete(id);+ },+ removeLayer(id: string) {+ layers.delete(id);+ },++ /** The style finishing, which is what `style.load` announces. */+ loadStyle() {+ loaded = true;+ for (const listener of listeners.get("style.load") ?? []) {+ listener();+ }+ },+ /** A style switch as the line experiences one: everything wiped, then `style.load` again. */+ switchStyle() {+ sources.clear();+ layers.clear();+ this.loadStyle();+ }+ };+}++const NOTE_ID = "shapeNoteId1";+const COORDINATES: [number, number][] = [ [ 24.13, 45.79 ], [ 24.14, 45.81 ], [ 24.08, 45.89 ] ];++describe("LineShape", () => {+ let container: HTMLElement;+ let map: ReturnType<typeof fakeMap>;++ beforeEach(() => {+ map = fakeMap();+ container = document.createElement("div");+ document.body.appendChild(container);+ });++ afterEach(() => {+ render(null, container);+ container.remove();+ });++ function renderLine({ styleLoaded = true } = {}) {+ act(() => {+ render(+ <ParentMap.Provider value={map as never}>+ <MapStyleLoaded.Provider value={styleLoaded}>+ <LineShape noteId={NOTE_ID} coordinates={COORDINATES} color="purple" />+ </MapStyleLoaded.Provider>+ </ParentMap.Provider>,+ container+ );+ });+ }++ it("draws the line from the note's coordinates, and takes it down when unmounted", () => {+ map.loadStyle();+ renderLine();++ const source = map.sources.get(lineShapeSourceId(NOTE_ID)) as {+ data: { properties: { id: string }; geometry: { 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.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");++ act(() => render(null, container));+ expect(map.sources.size).toBe(0);+ 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 });+ 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);++ // 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);+ });+});diff --git a/apps/client/src/widgets/collections/geomap/LineShape.tsx b/apps/client/src/widgets/collections/geomap/LineShape.tsxnew file mode 100644index 0000000000..1add66c29b--- /dev/null+++ b/apps/client/src/widgets/collections/geomap/LineShape.tsx@@ -0,0 +1,114 @@+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/api.ts b/apps/client/src/widgets/collections/geomap/api.tsindex 107b4409bc..d1cd7bc901 100644--- a/apps/client/src/widgets/collections/geomap/api.ts+++ b/apps/client/src/widgets/collections/geomap/api.ts@@ -7,10 +7,14 @@ 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";/** 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";+export async function moveMarker(noteId: string, latLng: { lat: number; lng: number } | null) {const value = latLng ? [latLng.lat, latLng.lng].join(",") : "";await attributes.setLabel(noteId, LOCATION_ATTRIBUTE, value);@@ -108,3 +112,27 @@ export async function createNewNote(parentNote: FNote, e: GeoMouseEvent) {return note;}++/**+ * Makes a note of a line 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+ * 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][]) {+ const { note } = await note_create.createNote(parentNote.noteId, {+ title: t("relation_map.default_new_note_title"),+ content: "",+ type: "text",+ activate: false,+ isProtected: parentNote.isProtected,+ attributes: [+ { type: "label", name: SHAPE_ATTRIBUTE, value: serializeLine(coordinates) },+ { type: "label", name: "iconClass", value: LINE_NOTE_ICON }+ ]+ });++ return note;+}diff --git a/apps/client/src/widgets/collections/geomap/index.tsx b/apps/client/src/widgets/collections/geomap/index.tsxindex 345c96defe..60b45f085d 100644--- a/apps/client/src/widgets/collections/geomap/index.tsx+++ b/apps/client/src/widgets/collections/geomap/index.tsx@@ -13,17 +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 { createNewNote, importGpxTrack, moveMarker } from "./api";+import { createLineNote, createNewNote, importGpxTrack, moveMarker } from "./api";import Buildings from "./Buildings";import ContextMenus from "./ContextMenus";import DetailPane, { PaneSelection } from "./DetailPane";+import DrawLine from "./DrawLine";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 Tooltips from "./Tooltips";const DEFAULT_COORDINATES: [number, number] = [3.878638227135724, 446.6630455551659];@@ -46,15 +49,19 @@ interface MapData {/*** What the next click on the map is for, where it is for anything at all: a new note is to be created- * there, or the marker of the note named here is to be moved there. `undefined` is a map that is only- * being looked at, which is every map most of the time.+ * there, the marker of the note named here is to be moved there, or a line is being drawn point by+ * point. `undefined` is a map that is only being looked at, which is every map most of the time.*- * The two are one state rather than two because they are alternatives — a click cannot mean both — and- * because the note being moved has nowhere else to be kept where it could not go missing.+ * The three are one state rather than three because they are alternatives — a click cannot mean two+ * of them — and because the note being moved has nowhere else to be kept where it could not go+ * missing. Drawing differs from the other two in taking many clicks rather than one, which is why+ * the map's own click handler leaves it alone (see onClick): the clicks belong to the drawing+ * session (see DrawLine) until it finishes or is stood down.*/type Placement =| { mode: "new" }- | { mode: "move"; noteId: string };+ | { mode: "move"; noteId: string }+ | { mode: "draw" };export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewModeProps<MapData>) {const [ placement, setPlacement ] = useState<Placement>();@@ -98,6 +105,24 @@ 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" });+ }, []);++ /**+ * Makes a note of a finished line 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.+ */+ const finishLine = useCallback(async (coordinates: [number, number][]) => {+ setPlacement(undefined);++ const created = await createLineNote(note, coordinates);+ if (!created) return;++ setNotes((current) => current.some((n) => n.noteId === created.noteId) ? current : [ ...current, created ]);+ setSelection({ noteId: created.noteId, isNew: true });+ }, [ note ]);/*** Creates a note where the click landed and opens the pane on it, title selected, so naming the@@ -153,11 +178,17 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewMtitle: t("geo-map.create-child-note-toast-title"),message: t("geo-map.create-child-note-instruction")}- : {- icon: "move",- title: t("geo-map.move-marker-toast-title"),- message: t("geo-map.move-marker-instruction")- })+ : placement.mode === "move"+ ? {+ icon: "move",+ title: 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")+ })});const globalKeyListener = (e: KeyboardEvent) => {@@ -174,7 +205,9 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM}, [ placement ]);const onClick = useCallback(async (e: GeoMouseEvent) => {- if (!placement) return;+ // A drawing session's clicks are its vertices, one by one — not this handler's to spend,+ // and above all not to disarm on: the session runs until it finishes or is stood down.+ if (!placement || placement.mode === "draw") return;// Leaving placement mode closes the instruction toast via the effect's cleanup. The state is// cleared first either way, so a failure to write the location does not leave the map armed@@ -247,13 +280,16 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewMisReadOnly={isReadOnly}placing={placement?.mode === "new"}onTogglePlacement={toggleNotePlacement}+ drawing={placement?.mode === "draw"}+ onToggleDrawing={toggleLineDrawing}onAddGpxTrack={addGpxTrack}/><Tooltips selectedNoteId={selection?.noteId ?? null} />{/* The preview under the pointer while a click is armed to mean a place — the notebeing moved wearing its own pin, a note to be created wearing the pin it will be- given (see api.ts). */}- {placement && <GhostPin note={placement.mode === "move" ? notes.find((n) => n.noteId === placement.noteId) : undefined} />}+ given (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} />}<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@@ -263,7 +299,8 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewMopen the note themselves — the two would otherwise both answer the same click,raising the quick editor over the pane that had just opened behind it. */}<Markers notes={notes} hideLabels={hideLabels} isDarkTheme={layerData.isDarkTheme ?? false} clustered={clustered} placing={!!placement} opensNotes={false} selectedNoteId={selection?.noteId ?? null} />- {notes.map(note => <NoteGpxTrackWrapper note={note} hideLabels={hideLabels} isDarkTheme={layerData.isDarkTheme ?? false} />)}+ {notes.map(note => <NoteGpxTrackWrapper key={note.noteId} note={note} hideLabels={hideLabels} isDarkTheme={layerData.isDarkTheme ?? false} />)}+ {notes.map(note => <NoteShapeWrapper key={note.noteId} note={note} />)}</Map>}</div>);@@ -381,3 +418,25 @@ 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+ * (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.+ */+function NoteShapeWrapper({ note }: { note: FNote }) {+ const [ shapeValue ] = useNoteLabel(note, SHAPE_ATTRIBUTE);+ const [ color ] = useNoteLabel(note, "color");++ const shape = shapeValue ? parseGeoShape(shapeValue) : null;+ if (!shape) {+ return null;+ }++ return <LineShape+ noteId={note.noteId}+ coordinates={shape.coordinates}+ color={color ?? "blue"}+ />;+}+diff --git a/apps/client/src/widgets/collections/geomap/shapes.spec.ts b/apps/client/src/widgets/collections/geomap/shapes.spec.tsnew file mode 100644index 0000000000..037bb3f318--- /dev/null+++ b/apps/client/src/widgets/collections/geomap/shapes.spec.ts@@ -0,0 +1,50 @@+import { describe, expect, it } from "vitest";++import { parseGeoShape, serializeLine } 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");+ });++ it("round-trips through parseGeoShape", () => {+ const coordinates: [number, number][] = [+ [ 13.404954, 52.520008 ],+ [ 13.412, 52.531 ],+ [ -0.1276, 51.5072 ]+ ];+ expect(parseGeoShape(serializeLine(coordinates))).toEqual({ type: "line", coordinates });+ });+});++describe("parseGeoShape", () => {+ it("reads a line back in GeoJSON lng,lat order", () => {+ expect(parseGeoShape("line:48.858093,2.294694 48.86,2.35")).toEqual({+ type: "line",+ coordinates: [+ [ 2.294694, 48.858093 ],+ [ 2.35, 48.86 ]+ ]+ });+ });++ it("tolerates surrounding and repeated whitespace", () => {+ 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();+ 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.+ expect(parseGeoShape("line:1,2 3")).toBeNull();+ expect(parseGeoShape("line:1,2 x,4")).toBeNull();+ expect(parseGeoShape("line:1,2 3,4,5")).toBeNull();+ });+});diff --git a/apps/client/src/widgets/collections/geomap/shapes.ts b/apps/client/src/widgets/collections/geomap/shapes.tsnew file mode 100644index 0000000000..ac5000ed30--- /dev/null+++ b/apps/client/src/widgets/collections/geomap/shapes.ts@@ -0,0 +1,83 @@+/**+ * 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.+ *+ * 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+ * shape. The trade is a bounded size — a label is no home for a thousand points, which is why the+ * drawing tools are the deliberate, click-a-vertex kind rather than freehand (and why an imported+ * track keeps its own file-note form; see GpxTrack).+ */++/** The label a shape note carries its geometry in. */+export const SHAPE_ATTRIBUTE = "geoShape";++/** How many decimal places a coordinate keeps: six is about a tenth of a metre, which is already+ * more than a hand-placed vertex means. */+const COORDINATE_DECIMALS = 6;++export interface GeoShapeLine {+ type: "line";+ /** `[lng, lat]` pairs — GeoJSON's order, ready for a MapLibre source or a Terra Draw feature. */+ 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;++/**+ * 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.+ */+export function serializeLine(coordinates: [number, number][]): string {+ const points = coordinates+ .map(([ lng, lat ]) => `${round(lat)},${round(lng)}`)+ .join(" ");+ return `line:${points}`;+}++/**+ * 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.+ */+export function parseGeoShape(value: string): GeoShape | null {+ if (!value.startsWith("line:")) {+ return null;+ }++ const coordinates: [number, number][] = [];+ for (const point of value.slice("line:".length).trim().split(/\s+/)) {+ const parts = point.split(",");+ if (parts.length !== 2) {+ return null;+ }++ const lat = Number(parts[0]);+ const lng = Number(parts[1]);+ if (!Number.isFinite(lat) || !Number.isFinite(lng)) {+ return null;+ }++ coordinates.push([ lng, lat ]);+ }++ if (coordinates.length < 2) {+ return null;+ }++ return { type: "line", coordinates };+}++/** A coordinate at the precision the label keeps, without `toFixed`'s trailing zeros. */+function round(coordinate: number): number {+ const factor = 10 ** COORDINATE_DECIMALS;+ return Math.round(coordinate * factor) / factor;+}diff --git a/packages/commons/src/lib/builtin_attributes.ts b/packages/commons/src/lib/builtin_attributes.tsindex e1dc4032e7..fe19a449d3 100644--- a/packages/commons/src/lib/builtin_attributes.ts+++ b/packages/commons/src/lib/builtin_attributes.ts@@ -287,6 +287,9 @@ const BUILTIN_ATTRIBUTES = [{ type: "label", name: "endTime", valueType: "time", hasUserValue: true },{ type: "label", name: "recurrence", valueType: "text", hasUserValue: true },{ type: "label", name: "geolocation", valueType: "text", hasUserValue: true },+ // A shape drawn onto a geo map, held as `kind:` and then a `lat,lng` per vertex — the+ // geolocation format walked along a path (see the client's geomap/shapes.ts).+ { type: "label", name: "geoShape", valueType: "text", hasUserValue: true },// Which note map a note map note draws; anything but `tree` is read as `link`.{ type: "label", name: "mapType", valueType: "select", hasUserValue: true, selectOptions: ["link", "tree"diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 5f95c4d23c..6458e50740 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -357,6 +357,12 @@ importers:temporal-polyfill:specifier: 1.0.3version: 1.0.3+ terra-draw:+ specifier: 1.32.3+ version: 1.32.3+ terra-draw-maplibre-gl-adapter:+ specifier: 1.4.1+ version: 1.4.1([email protected])([email protected])devDependencies:'@ckeditor/ckeditor5-inspector':specifier: 5.0.3@@ -2243,8 +2249,8 @@ packages:resolution: {integrity: sha512-pjoBpru1KdEtcExBnuHAP1cAc/5faoedw0hzJkL3o4/IJp7HNF1+fbrdxT3gMYRX2oJfvnA/WXeCTVQpYYxyJA==}engines: {node: '>=22.12.0'}- '@electron/node-gyp@https://codeload.github.com/electron/node-gyp/tar.gz/06b29aafb7708acef8b3669835c8a7857ebc92d2':- resolution: {gitHosted: true, integrity: sha512-MXgzlTDEEndJB3TBbvd5uFQO/8gaINo1Hfen8vef5rq/VHVPeB63uuv/uO5+8GFsAJ/rauu6XB79S6K4+aXc+w==, tarball: https://codeload.github.com/electron/node-gyp/tar.gz/06b29aafb7708acef8b3669835c8a7857ebc92d2}+ '@electron/node-gyp@git+ssh://[email protected]/electron/node-gyp.git#06b29aafb7708acef8b3669835c8a7857ebc92d2':+ resolution: {commit: 06b29aafb7708acef8b3669835c8a7857ebc92d2, repo: [email protected]:electron/node-gyp.git, type: git}version: 10.2.0-electron.1engines: {node: '>=12.13.0'}hasBin: true@@ -11526,6 +11532,15 @@ packages:resolution: {integrity: sha512-HAixuesxFQIUaQk3ptX2jhfO/FsOkgVkDDMawvp6n/fkB1q6BKfs3lURw9I+pK/2e2e/q/vrLrxmeqauBoyGMQ==}+ resolution: {integrity: sha512-qZ/bc9bVPnyt0keLVTofV8xiTPkdkbO6RzqrfNLe9zH/edW5PsjvJw97m1EksPZeXNJtFxsVbhi12cPaoNiWfg==}+ peerDependencies:+ maplibre-gl: '>=4'+ terra-draw: ^1.0.0++ resolution: {integrity: sha512-pQpwL8winsDW6/DbBgsaZKeMc83D+HqokxR+t1AbrN4U7C4mGgEfCtmRix1/5L4GfkLh1FE7pq44SWt76vK2Bw==}+resolution: {integrity: sha512-Eum+5ajkaOhf5KbM26osvv21kLD7BaGqQ1UA4Ami4arYwylmGUQTgHFpHDdmJod1q4QXa66p0to/FBKID+J1vA==}engines: {node: '>= 10.13.0'}@@ -14123,7 +14138,7 @@ snapshots:transitivePeerDependencies:- supports-color- '@electron/node-gyp@https://codeload.github.com/electron/node-gyp/tar.gz/06b29aafb7708acef8b3669835c8a7857ebc92d2([email protected])([email protected])':+ '@electron/node-gyp@git+ssh://[email protected]/electron/node-gyp.git#06b29aafb7708acef8b3669835c8a7857ebc92d2([email protected])([email protected])':dependencies:env-paths: 2.2.1exponential-backoff: 3.1.3@@ -14186,7 +14201,7 @@ snapshots:dependencies:- '@electron/node-gyp': https://codeload.github.com/electron/node-gyp/tar.gz/06b29aafb7708acef8b3669835c8a7857ebc92d2([email protected])([email protected])+ '@electron/node-gyp': git+ssh://[email protected]/electron/node-gyp.git#06b29aafb7708acef8b3669835c8a7857ebc92d2([email protected])([email protected])'@malept/cross-spawn-promise': 2.0.0chalk: 4.1.2debug: 4.4.3([email protected])@@ -25384,6 +25399,13 @@ snapshots:+ dependencies:+ maplibre-gl: 5.24.0+ terra-draw: 1.32.3++ [email protected]: {}+[email protected]([email protected])([email protected])([email protected])([email protected])([email protected]([email protected])([email protected])([email protected])([email protected])):dependencies:'@jridgewell/trace-mapping': 0.3.31