Skip to content

Build your personal knowledge base with Trilium Notes

Merge origin/main into the geo-map drawing spike

Elian Doranf29b5cd02df3
diff --cc apps/client/package.json
index fbc2e5a2be,9c697fc69b..183ec00dc5
--- a/apps/client/package.json
+++ b/apps/client/package.json
@@@ -70,9 -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.4"
++ "temporal-polyfill": "1.0.4",
+ "terra-draw": "1.32.3",
+ "terra-draw-maplibre-gl-adapter": "1.4.1"
},
"devDependencies": {
"@ckeditor/ckeditor5-inspector": "5.0.3",
diff --cc apps/client/src/widgets/collections/geomap/DetailPane.tsx
index ac74c6be4b,39d1c607d3..4f343543d0
--- a/apps/client/src/widgets/collections/geomap/DetailPane.tsx
+++ b/apps/client/src/widgets/collections/geomap/DetailPane.tsx
@@@ -19,8 -22,6 +22,8 @@@ import { type Bounds, boundsOf } from "
import { GPX_MIME, trackHitLayers, trackSourceId } from "./GpxTrack";
import { ParentMap } from "./map";
import { formatLocation, LOCATION_ATTRIBUTE, MARKER_LAYER, parseLocation } from "./Markers";
+import { shapeHitLayers } from "./ShapeLayer";
- import { boundsOfPoints, type GeoBounds, geoShapeBounds, parseGeoShape, SHAPE_ATTRIBUTE } from "./shapes";
++import { geoShapeBounds, parseGeoShape, SHAPE_ATTRIBUTE } from "./shapes";
/**
* Which marker the pane stands for, and why it came to be selected.
@@@ -118,22 -127,28 +133,31 @@@ export default function DetailPane({ no
return true;
}, [ notes, onSelect ]);
+ // The pane comes back up beside the map rather than over it, however it was left: the state
+ // outlives the pane, being the map's (see the props), where a card that is taken down and built
+ // again would have forgotten by itself. Switching from one marker to another keeps it — the room
+ // was asked for, not the marker it was asked on — which is why this waits on the pane going down
+ // rather than on the note changing.
+ useEffect(() => {
+ if (!selection) onMaximizedChange(false);
+ }, [ selection, onMaximizedChange ]);
+
- // A note no longer on the map takes the pane with it. Its location may merely have been cleared
- // — which is all "remove from map" does — so the note being gone is not the only case. A GPX
- // track is on the map by being one: its place is its line, not a location label.
+ // The pane closes once its note is no longer on the map. "Remove from map" only clears the
+ // label that put it there, so a note that is gone is not the only case. See standsOnMap().
useEffect(() => {
- if (selection && (!note || (note.mime !== GPX_MIME && !parseLocation(location)))) {
+ if (selection && !(note && standsOnMap(note))) {
void closePane();
}
- }, [ selection, note, location, closePane ]);
+ }, [ selection, note, location, shapeValue, closePane ]);
- // A marker or a GPX track selects, anywhere else clears. Read off the rendered layers rather
- // than bound to them (`map.on("click", MARKER_LAYER, ...)`) so one handler answers all, with no
- // ordering to rely on. The markers come ahead of the tracks for the reason the context menu
- // puts them there: a pin standing on its own line is the smaller target, and the one aimed at.
+ // A marker, a GPX track or a drawn shape selects, anywhere else clears. Read off the rendered
+ // layers rather than bound to them (`map.on("click", MARKER_LAYER, ...)`) so one handler answers
+ // all.
+ //
+ // The shapes are queried separately, and only where the markers and tracks were missed:
+ // queryRenderedFeatures() answers in the map's drawing order rather than in the order of the
+ // `layers` argument, and an area's fill covers its whole inside and is drawn above the markers.
+ // One combined query would therefore return the polygon for every click inside it.
useEffect(() => {
if (!map || placing) return;
@@@ -158,22 -171,21 +182,31 @@@
// created — is held clear of the pane the same way as one that was clicked; and off the
// location too, so a marker that has just been put somewhere else is followed there.
//
- // A GPX track is not a point but a shape, so it is fitted rather than centred: panned and
- // zoomed until it stands in the part of the map the pane leaves uncovered — the whole file,
- // or only what the click named where it named more (see PaneFocus).
+ // A GPX track and a drawn shape are not points but extents, so they are fitted rather than
+ // centred: panned and zoomed until they stand in the part of the map the pane leaves uncovered
+ // — the whole file, or only what the click named where it named more (see PaneFocus).
useEffect(() => {
if (!map || !note) return;
+ // Nothing is aimed at behind a surface that covers the map: the camera would be moving to a
+ // place nobody can see, and the move is seen — the map slides while the pane is still
+ // growing over it. Waiting instead is what makes the dependency below worth having, the
+ // pane coming back down being the moment the marker is worth framing again.
+ //
+ // A phone shows the marker as a dialog over the whole screen rather than as a pane beside
+ // the map (see MarkerSheet), so there is never a half of the map to hold it clear of: the
+ // camera has nothing to do there at all, and what it did was pan the map behind a sheet.
+ if (maximized || isMobile()) return;
+ // A shape is measured off its own label, which holds every point the map draws from and
+ // holds them at once, so there is no source to wait for as a track's file needs.
+ if (shape) {
+ const bounds = geoShapeBounds(shape);
+ if (bounds) {
+ map.fitBounds(bounds, { padding: fitPadding(map), maxZoom: FIT_MAX_ZOOM });
+ }
+ return;
+ }
+
if (note.mime === GPX_MIME) {
const focus = selection?.focus;
@@@ -219,15 -231,24 +252,24 @@@
const coordinates = parseLocation(location);
if (!coordinates) return;
- map.easeTo({ center: coordinates, offset: paneOffset(map) });
+ const aim: EaseToOptions = { center: coordinates, offset: paneOffset(map) };
+ if (selection?.zoom !== undefined) {
+ aim.zoom = selection.zoom;
+ }
+ map.easeTo(aim);
// The focus is depended on by identity, which a click renews even on the same note: every
// click is a fresh ask, and re-clicking what is already open brings it back into view.
- }, [ map, note?.noteId, location, shapeValue, selection?.focus ]);
+ //
+ // Growing and shrinking the pane are asks of the same kind, the room the camera is aiming
+ // into being what changed: a pane put back down brings its marker clear of it again, rather
+ // than leaving it under the pane until something else happens to move the camera.
- }, [ map, note?.noteId, location, selection?.focus, selection?.zoom, maximized ]);
++ }, [ map, note?.noteId, location, shapeValue, selection?.focus, selection?.zoom, maximized ]);
// Bound only while something is selected, so the map's other Escape — giving up on placing a
- // marker (see index.tsx) — stands alone when nothing is.
+ // marker (see index.tsx) — stands alone when nothing is. A phone's dialog answers the key
+ // itself (see MarkerSheet), and two answers to one press would close it twice over.
useEffect(() => {
- if (!selection) return;
+ if (!selection || isMobile()) return;
const onKeyDown = (e: KeyboardEvent) => {
if (e.key === "Escape") {
@@@ -411,30 -434,103 +468,103 @@@ function MarkerDetails({ note, parentNo
containerRef={paneRef}
className={clsx("geo-detail-pane", colorClass)}
header={<TitleRow compact />}
- headerActions={<MaximizeToQuickEditAction note={note} onClose={onClose} />}
+ maximized={maximized}
+ headerActions={
+ <MaximizeAction
+ icon={maximized ? "bx bx-collapse-alt" : "bx bx-expand-alt"}
+ text={maximized ? t("geo-map.restore-details") : t("geo-map.expand-details")}
+ onClick={() => onMaximizedChange(!maximized)}
+ />
+ }
close={{ text: t("geo-map.close-details"), onClick: onClose }}
>
- <OverlayPanelBody className="geo-detail-pane-body tn-embedded-note-pane">
- <MarkerLocation note={note} />
-
- <MarkerActions note={note} parentNote={parentNote} isReadOnly={isReadOnly} onRelocate={onRelocate} />
+ {/* Grown over the map, the pane has a note's width, so what it holds is laid out for one
+ (see `tn-embedded-note-pane-wide` in EmbeddedNotePane.css). */}
+ <OverlayPanelBody className={clsx("geo-detail-pane-body tn-embedded-note-pane", maximized && "tn-embedded-note-pane-wide")}>
+ <MarkerContents note={note} parentNote={parentNote} isReadOnly={isReadOnly} onRelocate={onRelocate} />
+ </OverlayPanelBody>
+ </OverlayPanel>
+ );
+ }
- {/* Whatever fields the note's own definitions ask for, ahead of the note as the quick
- editor puts them — a marker is often a note whose type says less about it than
- its fields do. Nothing at all is shown for a note that promotes none.
+ /**
+ * The marker as a phone shows it: the sheet the app raises its dialogs as, rather than a pane laid
+ * over the map. A pane holding a whole note takes most of a phone's screen whatever is done to it,
+ * so one drawn over the map leaves the map neither readable nor reachable — and the maximize that
+ * would give it the rest of the screen has nothing left to give. The note is shown as a note
+ * instead, and the map is left alone behind it (see the camera above).
+ *
+ * Dressed as the quick editor and the calendar's own sheet are, those being the app's ways of
+ * showing a whole note over whatever raised it (see the shared rules in PopupEditor.css).
+ *
+ * `show` is not a state because every way out of this dialog is also a way out of the selection:
+ * what answers `onHidden` clears it, and the sheet goes with it. Bootstrap is told to hide as the
+ * element leaves the tree, so nothing is left dimming the page behind it (see Modal).
+ */
+ function MarkerSheet({ note, parentNote, isReadOnly, onClose, onRelocate, onFollowLink }: {
+ note: FNote;
+ parentNote: FNote;
+ isReadOnly: boolean;
+ onClose(): void;
+ onRelocate(): void;
+ onFollowLink(noteId: string): boolean;
+ }) {
+ // Marked on the dialog rather than on its body, so that what heads it — the note's own title
+ // row, handed to the dialog — is inside the marked element too (see the pane above).
+ const modalRef = useRef<HTMLDivElement>(null);
+ useLegacyComponentElement(modalRef);
+ useFollowLinksWithin(modalRef, onFollowLink);
+
+ // Tinted by the marker's own colour as the pane over the map is, and by the same means the
+ // quick editor is (see the `.with-hue` rules in theme-next-{light,dark}.css) — a sheet being
+ // opaque, it takes the dialog's colours rather than the pane's.
+ const colorClass = useNoteColorClass(note);
- Neither the location nor the geometry is among them: promoted, each is a field of
- raw digits beside a map that already draws it, and a marker is moved rather than
- retyped. */}
- <PromotedAttributes omit={[ LOCATION_ATTRIBUTE, SHAPE_ATTRIBUTE ]} />
+ return (
+ <Modal
+ className={clsx("geo-detail-sheet", colorClass)}
+ size="lg"
+ title={<TitleRow />}
+ modalRef={modalRef}
+ show
+ onHidden={onClose}
+ >
+ <div className="geo-detail-pane-body tn-embedded-note-pane">
+ <MarkerContents note={note} parentNote={parentNote} isReadOnly={isReadOnly} onRelocate={onRelocate} />
+ </div>
+ </Modal>
+ );
+ }
- {/* The note itself, drawn by whichever widget its type calls for — the same one the
- quick editor mounts, so a marker is written in exactly as it is anywhere else.
- No toolbar stands beside it: the pane asks for the floating one, which the editor
- carries with it (see the view scope below). */}
- <NoteDetail />
- </OverlayPanelBody>
- </OverlayPanel>
+ /** What is shown of the marker, under whatever heads it. Shared by the pane and the sheet, which
+ * differ only in what they put around this and how they are dismissed. */
+ function MarkerContents({ note, parentNote, isReadOnly, onRelocate }: {
+ note: FNote;
+ parentNote: FNote;
+ isReadOnly: boolean;
+ onRelocate(): void;
+ }) {
+ return (
+ <>
+ <MarkerLocation note={note} />
+
+ <MarkerActions note={note} parentNote={parentNote} isReadOnly={isReadOnly} onRelocate={onRelocate} />
+
+ {/* Whatever fields the note's own definitions ask for, ahead of the note as the quick
+ editor puts them — a marker is often a note whose type says less about it than
+ its fields do. Nothing at all is shown for a note that promotes none.
+
- The location is not among them, the line above naming it better: promoted, it is
- a box of raw digits standing beside a map of the very place it names, and the way
- to put a marker somewhere else here is to move it. */}
- <PromotedAttributes omit={[ LOCATION_ATTRIBUTE ]} />
++ Neither the location nor the geometry is among them: promoted, each is a field of
++ raw digits beside a map that already draws it, and a marker is moved rather than
++ retyped. */}
++ <PromotedAttributes omit={[ LOCATION_ATTRIBUTE, SHAPE_ATTRIBUTE ]} />
+
+ {/* The note itself, drawn by whichever widget its type calls for — the same one the
+ quick editor mounts, so a marker is written in exactly as it is anywhere else.
+ No toolbar stands beside it: the pane asks for the floating one, which the editor
+ carries with it (see the view scope above). */}
+ <NoteDetail />
+ </>
);
}
diff --cc apps/client/src/widgets/collections/geomap/EditToolbar.tsx
index ba28628ea7,37284bce1c..b744c70a0b
--- a/apps/client/src/widgets/collections/geomap/EditToolbar.tsx
+++ b/apps/client/src/widgets/collections/geomap/EditToolbar.tsx
@@@ -1,10 -1,9 +1,10 @@@
import "./EditToolbar.css";
- import { useContext, useRef } from "preact/hooks";
+ import { useContext } from "preact/hooks";
import { t } from "../../../services/i18n";
- import { useStaticTooltip } from "../../react/hooks";
+ import OverlayControlGroup, { OverlayControlButton } from "../../react/OverlayControlGroup";
+import type { DrawTool } from "./DrawShape";
import { ParentMap } from "./map";
interface EditToolbarProps {
@@@ -24,18 -19,10 +24,18 @@@
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") },
+ { tool: "rectangle", icon: "bx-rectangle", title: () => t("geo-map.draw-rectangle") },
+ { tool: "circle", icon: "bx-shape-circle", title: () => t("geo-map.draw-circle") }
+];
+
/**
- * 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,
- * the drawing tools, and bringing in a GPX track.
+ * The editing actions, standing in the middle of the map's foot on an {@link OverlayControlGroup} of
- * their own — 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.
++ * their own — 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
@@@ -48,59 -35,30 +48,43 @@@
* 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, drawingTool, onToggleDrawing, onAddGpxTrack }: EditToolbarProps) {
const map = useContext(ParentMap);
- const addMarkerRef = 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
- // otherwise fall off.
- useStaticTooltip(addMarkerRef, {
- title: placing ? t("geo-map.create-child-note-cancel") : t("geo-map.create-child-note-title"),
- 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).
if (!map) return null;
return (
- <div
- className="geo-edit-toolbar tn-overlay-control-group"
- /* Keep a press on the controls from reaching the canvas underneath, which would
- otherwise take it for the start of a drag. */
- onMouseDown={(e) => e.stopPropagation()}
- >
- <button
- ref={addMarkerRef}
- type="button"
- className={`tn-overlay-text-button geo-add-marker-button ${placing ? "active" : ""}`}
+ <OverlayControlGroup className="geo-edit-toolbar" placement="bottom-center" overCanvas>
+ {/* The pin a note dropped on the map wears (see GEO_MARKER_ICON in commons) — the
+ button shows the very thing it drops, which is also the ghost that will follow the
+ pointer once armed. The words beside it are what names the button; the tooltip says
+ at more length what it does. */}
+ <OverlayControlButton
+ title={placing ? t("geo-map.create-child-note-cancel") : t("geo-map.create-child-note-title")}
+ icon="bx-pin"
+ text={placing ? t("geo-map.add-marker-cancel") : t("geo-map.add-marker")}
+ className="geo-add-marker-button"
+ active={placing}
disabled={isReadOnly}
onClick={onTogglePlacement}
- >
- {/* The pin a note dropped on the map wears (see CHILD_NOTE_ICON in api.ts) — the
- button shows the very thing it drops, which is also the ghost that will follow
- the pointer once armed. A child rather than a class on the button: the boxicons
- class sets the icon font on whatever wears it, and the words beside it are to
- stay words. */}
- <span className="bx bx-pin" aria-hidden="true" />
- {placing ? t("geo-map.add-marker-cancel") : t("geo-map.add-marker")}
- </button>
+ />
++ {/* Each tool wears the shape it draws and no words, the pin's name being enough to say
++ what the row is for. An armed tool's tooltip says what a second press does, as the
++ marker button's does. */}
+ {DRAW_TOOLS.map(({ tool, icon, title }) => (
- <DrawToolButton
++ <OverlayControlButton
+ key={tool}
- icon={icon}
+ title={drawingTool === tool ? t("geo-map.draw-cancel") : title()}
++ icon={icon}
+ active={drawingTool === tool}
+ disabled={isReadOnly}
+ onClick={() => onToggleDrawing(tool)}
+ />
+ ))}
- <button
- ref={gpxRef}
- type="button"
- className="tn-overlay-icon-button bx bx-trip"
- aria-label={t("geo-map.add-gpx-track")}
+ <OverlayControlButton
+ title={t("geo-map.add-gpx-track")}
+ icon="bx-trip"
disabled={isReadOnly}
onClick={onAddGpxTrack}
/>
diff --cc apps/client/src/widgets/collections/geomap/api.spec.ts
index 49d08ff13c,3b16fef25b..7329a4f6a9
--- a/apps/client/src/widgets/collections/geomap/api.spec.ts
+++ b/apps/client/src/widgets/collections/geomap/api.spec.ts
@@@ -1,13 -1,17 +1,19 @@@
/**
- * What the geo map writes when something is put on it (see api.ts): the note a placement click
- * creates, and the note a GPX file is brought in as. Both go through the ordinary note-creation
- * service; what is checked here is what they ask it for.
+ * What the geo map writes when something is put on it or taken off it (see api.ts): the note a
+ * placement click creates, the note a searched place is kept as, the note a GPX file is brought in
+ * as, and what becomes of a marker the reader is done with. All go through the ordinary note
+ * services; what is checked here is what they are asked for.
*/
- import { describe, expect, it, vi } from "vitest";
+ import { beforeEach, describe, expect, it, vi } from "vitest";
+ import attributes from "../../../services/attributes";
+ import dialog from "../../../services/dialog";
import note_create from "../../../services/note_create";
+ import { deleteNoteOrBranch } from "../../../services/note_deletion";
import { buildNote } from "../../../test/easy-froca";
- import { createNewNote, createShapeNote, importGpxTrack } from "./api";
-import { createNewNote, createNoteForPlace, importGpxTrack, moveMarker, removeFromMap } from "./api";
++import {
++ createNewNote, createNoteForPlace, createShapeNote, importGpxTrack, moveMarker, removeFromMap
++} from "./api";
vi.mock("../../../services/note_create", () => ({
default: { createNote: vi.fn(async () => ({ note: { noteId: "created" }, branch: null })) }
diff --cc apps/client/src/widgets/collections/geomap/api.ts
index 9f179b21ce,10d9b69efc..3a614d31a3
--- a/apps/client/src/widgets/collections/geomap/api.ts
+++ b/apps/client/src/widgets/collections/geomap/api.ts
@@@ -7,18 -9,10 +9,18 @@@ import { deleteNoteOrBranch } from "../
import { GPX_MIME } from "./GpxTrack";
import type { GeoMouseEvent } from "./map";
import { LOCATION_ATTRIBUTE } from "./Markers";
+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 type a note put on the map is created as, and so what a template handed to it must match. */
+ export const MARKER_NOTE_TYPE: NoteType = "text";
+/** 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",
+ circle: "bx bx-shape-circle"
+} 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(",") : "";
await attributes.setLabel(noteId, LOCATION_ATTRIBUTE, value);
diff --cc apps/client/src/widgets/collections/geomap/index.tsx
index ad44ae9169,c7fd20a46e..b3ea96a850
--- a/apps/client/src/widgets/collections/geomap/index.tsx
+++ b/apps/client/src/widgets/collections/geomap/index.tsx
@@@ -9,27 -9,40 +9,43 @@@ import froca from "../../../services/fr
import { t } from "../../../services/i18n";
import server from "../../../services/server";
import toast from "../../../services/toast";
+ import { logError } from "../../../services/ws";
import CollectionProperties from "../../note_bars/CollectionProperties";
- import ActionButton from "../../react/ActionButton";
- import { useCollectionTreeDrag, useNoteBlob, useNoteLabel, useNoteLabelBoolean, useNoteProperty, useSpacedUpdate } from "../../react/hooks";
+ import { useCollectionTreeDrag, useColorScheme, useEffectiveReadOnly, useNoteBlob, useNoteContext, useNoteLabel, useNoteLabelBoolean, useNoteProperty, useSpacedUpdate } from "../../react/hooks";
import { ViewModeProps } from "../interface";
- import { createNewNote, createShapeNote, importGpxTrack, moveMarker } from "./api";
-import { createNewNote, createNoteForPlace, importGpxTrack, moveMarker } from "./api";
++import { createNewNote, createNoteForPlace, createShapeNote, importGpxTrack, moveMarker } from "./api";
import Buildings from "./Buildings";
import ContextMenus from "./ContextMenus";
+ import { pointPlace } from "./coordinates";
import DetailPane, { PaneSelection } from "./DetailPane";
+import DrawShape, { DrawTool } from "./DrawShape";
import EditToolbar from "./EditToolbar";
import GhostPin from "./GhostPin";
import { GPX_MIME, GpxTrack } from "./GpxTrack";
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 { GeoShape, parseGeoShape, SHAPE_ATTRIBUTE } from "./shapes";
+ import type { GeoSearchResult } from "./geocoding";
+ import Markers, { DEFAULT_MARKER_COLOR, FitToNotes, LOCATION_ATTRIBUTE } from "./Markers";
+ import PlaceMarker from "./PlaceMarker";
+ import PlacePanel from "./PlacePanel";
+ import Pois from "./Pois";
+ import ResultNavigator from "./ResultNavigator";
+ import { NOTE_ZOOM, type SearchResult } from "./results";
+ import SearchBox from "./SearchBox";
+import { ShapeLayer } from "./ShapeLayer";
++import { GeoShape, parseGeoShape, SHAPE_ATTRIBUTE } from "./shapes";
import Tooltips from "./Tooltips";
- const DEFAULT_COORDINATES: [number, number] = [3.878638227135724, 446.6630455551659];
+ /**
+ * Where a map stands when there is nothing to stand it on: no view has been saved and no note it
+ * holds has a place. Latitude first, as {@link MapData} holds a centre.
+ *
+ * A little north of the equator on the prime meridian, which at {@link DEFAULT_ZOOM} is most of the
+ * inhabited world. A map that holds located notes never opens here — it frames them instead (see
+ * {@link FitToNotes}).
+ */
+ const DEFAULT_COORDINATES: [number, number] = [20, 0];
/**
* The instruction toast that says what the map is waiting for. One id for both kinds of placement:
@@@ -60,10 -76,10 +82,11 @@@ interface MapData
*/
type Placement =
| { mode: "new" }
- | { mode: "move"; noteId: string };
+ | { mode: "move"; noteId: string }
+ | { mode: "draw"; tool: DrawTool };
export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewModeProps<MapData>) {
+ const { noteContext } = useNoteContext();
const [ placement, setPlacement ] = useState<Placement>();
// Which marker the detail pane stands for. Held here rather than in the pane so that creating a
// note can open the pane on it (see createNoteAt below).
@@@ -105,26 -245,6 +252,26 @@@
setPlacement((current) => current?.mode === "new" ? undefined : { mode: "new" });
}, []);
const startMarkerRelocation = useCallback((noteId: string) => setPlacement({ mode: "move", noteId }), []);
+ 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 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 shape nobody is looking at any more.
+ */
+ const finishShape = useCallback(async (shape: GeoShape) => {
+ setPlacement(undefined);
+
+ const created = await createShapeNote(note, shape);
+ if (!created) return;
+
+ setNotes((current) => current.some((n) => n.noteId === created.noteId) ? current : [ ...current, created ]);
- setSelection({ noteId: created.noteId, isNew: true });
- }, [ note ]);
++ selectNote({ noteId: created.noteId, isNew: true });
++ }, [ note, selectNote ]);
/**
* Creates a note where the click landed and opens the pane on it, title selected, so naming the
@@@ -278,17 -410,23 +441,27 @@@
isReadOnly={isReadOnly}
placing={placement?.mode === "new"}
onTogglePlacement={toggleNotePlacement}
+ drawingTool={placement?.mode === "draw" ? placement.tool : null}
+ onToggleDrawing={toggleDrawing}
onAddGpxTrack={addGpxTrack}
/>
- <Tooltips selectedNoteId={selection?.noteId ?? null} />
+ <Tooltips selectedNoteId={selection?.noteId ?? null} paneMaximized={paneMaximized} />
{/* The preview under the pointer while a click is armed to mean a place — the note
- being moved wearing its own pin, a note to be created wearing the pin it will be
- 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} />}
+ being moved wearing its own pin, a note to be created wearing the one the map
- would give it (see GhostPin). */}
- {placement && <GhostPin
++ would give it (see GhostPin). A drawing session previews itself, so no ghost
++ then. */}
++ {placement && placement.mode !== "draw" && <GhostPin
+ parentNote={note}
+ note={placement.mode === "move"
+ ? notes.find((n) => n.noteId === placement.noteId)
+ : undefined}
+ />}
+ {placement?.mode === "draw" && <DrawShape tool={placement.tool} onFinish={finishShape} />}
- <DetailPane notes={notes} parentNote={note} placing={!!placement} isReadOnly={isReadOnly} selection={selection} onSelect={setSelection} onRelocate={startMarkerRelocation} />
+ <DetailPane
+ notes={notes} parentNote={note} placing={!!placement} isReadOnly={isReadOnly}
+ selection={selection} onSelect={selectNote} onRelocate={startMarkerRelocation}
+ maximized={paneMaximized} onMaximizedChange={setPaneMaximized}
+ />
<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
and not merely the angle it is seen from. */}
@@@ -297,8 -438,8 +473,9 @@@
open 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} />)}
+ <FitToNotes notes={notes} enabled={!viewConfig?.view} />
</Map>}
</div>
);
diff --cc apps/client/src/widgets/collections/geomap/shapes.spec.ts
index f638b22c70,0000000000..7fecaed1f0
mode 100644,000000..100644
--- a/apps/client/src/widgets/collections/geomap/shapes.spec.ts
+++ b/apps/client/src/widgets/collections/geomap/shapes.spec.ts
@@@ -1,178 -1,0 +1,175 @@@
+import { describe, expect, it } from "vitest";
+
+import {
- boundsOfPoints, circleRing, closeRing, type GeoShape, geoShapeBounds, parseGeoShape,
- polygonFromRing, ringCenter, serializeGeoShape
++ circleRing, closeRing, type GeoShape, geoShapeBounds, parseGeoShape, polygonFromRing,
++ ringCenter, serializeGeoShape
+} from "./shapes";
+
+describe("serializeGeoShape", () => {
+ it("writes lat,lng pairs behind the kind's prefix, rounded but not padded", () => {
+ 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("writes a circle as its centre and its reach, not the ring that would approximate it", () => {
+ expect(serializeGeoShape({
+ type: "circle",
+ center: [ 2.2946944444, 48.8580925 ],
+ radiusMeters: 512.3456
+ })).toBe("circle:48.858093,2.294694 512.3");
+ });
+
+ it("round-trips through parseGeoShape", () => {
+ const coordinates: [number, number][] = [
+ [ 13.404954, 52.520008 ],
+ [ 13.412, 52.531 ],
+ [ -0.1276, 51.5072 ]
+ ];
+ for (const type of [ "line", "polygon" ] as const) {
+ expect(parseGeoShape(serializeGeoShape({ type, coordinates }))).toEqual({ type, coordinates });
+ }
+
+ const circle: GeoShape = { type: "circle", center: [ 13.404954, 52.520008 ], radiusMeters: 500 };
+ expect(parseGeoShape(serializeGeoShape(circle))).toEqual(circle);
+ });
+});
+
+describe("parseGeoShape", () => {
+ 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: [
+ [ 2.294694, 48.858093 ],
+ [ 2.35, 48.86 ]
+ ]
+ });
+ });
+
+ it("tolerates surrounding and repeated whitespace", () => {
+ expect(parseGeoShape("line: 1,2 3,4 ")).toEqual({ type: "line", coordinates: [ [ 2, 1 ], [ 4, 3 ] ] });
+ });
+
+ 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();
+ // 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();
+ });
+
+ it("holds a circle to a centre and a positive reach", () => {
+ expect(parseGeoShape("circle:48.85,2.29 500")).toEqual({
+ type: "circle",
+ center: [ 2.29, 48.85 ],
+ radiusMeters: 500
+ });
+ // No radius, two centres, a reach of nothing, and one of nonsense.
+ expect(parseGeoShape("circle:48.85,2.29")).toBeNull();
+ expect(parseGeoShape("circle:48.85,2.29 48.86,2.35 500")).toBeNull();
+ expect(parseGeoShape("circle:48.85,2.29 0")).toBeNull();
+ expect(parseGeoShape("circle:48.85,2.29 far")).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([]);
+ expect(ringCenter([])).toBeNull();
+ });
+
+ it("walks a circle out as a ring of points its reach away from the centre", () => {
+ const center: [number, number] = [ 2.294694, 48.858093 ];
+ const radiusMeters = 500;
+ const ring = circleRing(center, radiusMeters);
+
+ expect(ring).toHaveLength(64);
+ // Not closed — the closing repeat is closeRing's to add, as for any other ring.
+ expect(ring[0]).not.toEqual(ring[ring.length - 1]);
+ // Every point stands the same distance out, give or take the arithmetic.
+ for (const point of ring) {
+ expect(haversineMeters(center, point)).toBeCloseTo(radiusMeters, 0);
+ }
+ // And the ring stands around where it was asked to.
+ const [ lng, lat ] = ringCenter(ring) ?? [ NaN, NaN ];
+ expect(lng).toBeCloseTo(center[0], 4);
+ expect(lat).toBeCloseTo(center[1], 4);
+ });
+});
+
++/** How the box itself is measured is `boundsOf`'s own business (see coordinates.spec); what these
++ * pin down is which points of a shape are handed to it. */
+describe("bounds", () => {
- it("boxes a line and a polygon by their own points, and answers nothing for none", () => {
++ it("boxes a line and a polygon by their own points", () => {
+ expect(geoShapeBounds({
+ type: "line",
+ coordinates: [ [ 24.13, 45.79 ], [ 24.16, 45.96 ], [ 24.08, 45.89 ] ]
+ })).toEqual([ [ 24.08, 45.79 ], [ 24.16, 45.96 ] ]);
+
- expect(boundsOfPoints([])).toBeNull();
++ expect(geoShapeBounds({
++ type: "polygon",
++ coordinates: [ [ 24.13, 45.79 ], [ 24.16, 45.96 ], [ 24.08, 45.89 ] ]
++ })).toEqual([ [ 24.08, 45.79 ], [ 24.16, 45.96 ] ]);
+ });
+
+ /** A circle is stored as a centre and a radius, so the box has to cover the radius. */
+ it("boxes a circle across the ring its radius walks out", () => {
+ const circle: GeoShape = { type: "circle", center: [ 2.29, 48.85 ], radiusMeters: 1000 };
+ const bounds = geoShapeBounds(circle);
+ const [ [ west, south ], [ east, north ] ] = bounds ?? [ [ NaN, NaN ], [ NaN, NaN ] ];
+
+ // A kilometre spans about 0.018° of latitude, and more of longitude at this latitude. The
+ // centre sits in the middle of both.
+ expect((south + north) / 2).toBeCloseTo(48.85, 4);
+ expect((west + east) / 2).toBeCloseTo(2.29, 4);
+ expect(north - south).toBeCloseTo(0.018, 3);
+ expect(east - west).toBeGreaterThan(north - south);
+ });
+
- /**
- * Longitude wraps. Points either side of ±180° sit metres apart on the ground but span nearly
- * the world when measured raw, so the same longitudes are measured again with the seam at 0°
- * and the narrower box wins.
- */
++ /** A shape reaches `boundsOf` whole, so one drawn across the seam is framed at the crossing. */
+ it("frames a shape crossing the antimeridian rather than the world", () => {
+ expect(geoShapeBounds({
+ type: "polygon",
+ coordinates: [ [ 179.9, -16.5 ], [ -179.9, -16.5 ], [ -179.95, -16.6 ] ]
+ })).toEqual([ [ 179.9, -16.6 ], [ 180.1, -16.5 ] ]);
-
- // A shape that really spans half the earth stays wide in both frames.
- expect(boundsOfPoints([ [ -120, 10 ], [ 0, 20 ], [ 120, 30 ] ]))
- .toEqual([ [ -120, 10 ], [ 120, 30 ] ]);
+ });
+});
+
+/** The distance between two points the way the ring generator must honour it: over the sphere. */
+function haversineMeters([ lng1, lat1 ]: [number, number], [ lng2, lat2 ]: [number, number]): number {
+ const toRad = (d: number) => (d * Math.PI) / 180;
+ const dLat = toRad(lat2 - lat1);
+ const dLng = toRad(lng2 - lng1);
+ const a = Math.sin(dLat / 2) ** 2 +
+ Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLng / 2) ** 2;
+ return 6371008.8 * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
+}
diff --cc apps/client/src/widgets/collections/geomap/shapes.ts
index b85ae7a26e,0000000000..46f1b26ac0
mode 100644,000000..100644
--- a/apps/client/src/widgets/collections/geomap/shapes.ts
+++ b/apps/client/src/widgets/collections/geomap/shapes.ts
@@@ -1,263 -1,0 +1,232 @@@
+/**
+ * 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 — 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
+ * 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).
+ */
+
++import { type Bounds, boundsOf } from "./coordinates";
++
+/** 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][];
+}
+
+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][];
+}
+
+export interface GeoShapeCircle {
+ type: "circle";
+ /** `[lng, lat]` of the centre. */
+ center: [number, number];
+ /** How far the circle reaches, in metres — the one number the points would only approximate. */
+ radiusMeters: number;
+}
+
+/** Every kind of shape a note can carry. */
+export type GeoShape = GeoShapeLine | GeoShapePolygon | GeoShapeCircle;
+
+/** The fewest points each point-list kind is a shape at all with: one point is no line, and two
+ * no area. A circle is not among them — it is a centre and a reach, not a walk. */
+const MINIMUM_POINTS = { line: 2, polygon: 3 } as const;
+
+/**
+ * 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. A circle
+ * is its centre and then its radius in metres, `circle:48.85,2.29 500`, rather than the ring of
+ * points a drawing library holds it as: the ring is an approximation regenerated at whatever
+ * fineness the reader wants (see {@link circleRing}), and sixty-odd points would swell the label
+ * for less information than two numbers carry.
+ */
+export function serializeGeoShape(shape: GeoShape): string {
+ if (shape.type === "circle") {
+ const [ lng, lat ] = shape.center;
+ return `circle:${round(lat)},${round(lng)} ${Math.round(shape.radiusMeters * 10) / 10}`;
+ }
+
+ 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 point a finite `lat,lng`
+ * pair, and enough of them for the kind (see {@link MINIMUM_POINTS}).
+ */
+export function parseGeoShape(value: string): GeoShape | null {
+ const divide = value.indexOf(":");
+ if (divide < 0) return null;
+
+ const type = value.slice(0, divide);
+ const rest = value.slice(divide + 1);
+
+ if (type === "circle") {
+ return parseCircle(rest);
+ }
+
+ if (!isPointKind(type)) return null;
+
+ const coordinates = parsePoints(rest);
+ if (!coordinates || coordinates.length < MINIMUM_POINTS[type]) return null;
+
+ return { type, coordinates };
+}
+
+function parseCircle(rest: string): GeoShapeCircle | null {
+ const parts = rest.trim().split(/\s+/);
+ if (parts.length !== 2) return null;
+
+ const center = parsePoints(parts[0]);
+ const radiusMeters = Number(parts[1]);
+ if (!center || center.length !== 1 || !Number.isFinite(radiusMeters) || radiusMeters <= 0) {
+ return null;
+ }
+
+ return { type: "circle", center: center[0], radiusMeters };
+}
+
+/**
+ * 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] ];
+}
+
+/** The mean of the earth's radii, as MapLibre also takes it. */
+const EARTH_RADIUS_METERS = 6371008.8;
+
+/** How many corners a circle's ring is drawn with — enough that nobody sees them. */
+const CIRCLE_SEGMENTS = 64;
+
+/**
+ * A circle's reach walked out as a ring, one point per bearing, without the closing repeat — the
+ * ring a circle label is drawn from (see {@link serializeGeoShape} for why it is not stored).
+ * Great-circle rather than flat arithmetic, so a wide circle far from the equator keeps its shape.
+ */
+export function circleRing(center: [number, number], radiusMeters: number, segments = CIRCLE_SEGMENTS): [number, number][] {
+ const [ lng, lat ] = center;
+ const angular = radiusMeters / EARTH_RADIUS_METERS;
+ const latRad = toRadians(lat);
+ const lngRad = toRadians(lng);
+
+ const ring: [number, number][] = [];
+ for (let i = 0; i < segments; i++) {
+ const bearing = (2 * Math.PI * i) / segments;
+ const pointLat = Math.asin(
+ Math.sin(latRad) * Math.cos(angular) +
+ Math.cos(latRad) * Math.sin(angular) * Math.cos(bearing)
+ );
+ const pointLng = lngRad + Math.atan2(
+ Math.sin(bearing) * Math.sin(angular) * Math.cos(latRad),
+ Math.cos(angular) - Math.sin(latRad) * Math.sin(pointLat)
+ );
+ ring.push([ toDegrees(pointLng), toDegrees(pointLat) ]);
+ }
+
+ return ring;
+}
+
+/**
+ * Where a ring stands: the mean of its points. Exact for the regular ring a circle tool hands
+ * over, which is all it is asked about — this is how the centre a circle label stores is read
+ * back off the ring Terra Draw drew (see `shapeFromFeature`).
+ */
+export function ringCenter(ring: [number, number][]): [number, number] | null {
+ if (ring.length === 0) return null;
+
+ let lngSum = 0;
+ let latSum = 0;
+ for (const [ lng, lat ] of ring) {
+ lngSum += lng;
+ latSum += lat;
+ }
+ return [ lngSum / ring.length, latSum / ring.length ];
+}
+
- /** `[[west, south], [east, north]]`, the form `fitBounds` takes. */
- export type GeoBounds = [[number, number], [number, number]];
-
+/**
+ * The corners of a shape, which `DetailPane` frames the shape it opens on by. A circle is measured
- * across {@link circleRing} rather than at its centre, so the box covers the whole radius.
++ * across {@link circleRing} rather than at its centre, so the box covers the whole radius; the seam
++ * at ±180° is {@link boundsOf}'s to deal with, as it is for a track.
+ */
- export function geoShapeBounds(shape: GeoShape): GeoBounds | null {
- return boundsOfPoints(shape.type === "circle"
++export function geoShapeBounds(shape: GeoShape): Bounds | null {
++ return boundsOf(shape.type === "circle"
+ ? circleRing(shape.center, shape.radiusMeters)
+ : shape.coordinates);
+}
+
- /**
- * The box a set of points fits in, or `null` for no points at all.
- *
- * Longitude is measured twice because it wraps. Points either side of ±180° sit metres apart on the
- * ground, but their raw minimum and maximum span nearly the world, so the same longitudes are
- * measured again with the seam at 0° — each western value moved a turn east — and the narrower of
- * the two boxes wins. Only a shape that really spans half the earth stays wide in both. The shifted
- * box can name longitudes past 180°, which `fitBounds` accepts.
- */
- export function boundsOfPoints(points: Iterable<number[]>): GeoBounds | null {
- let west = Infinity, south = Infinity, east = -Infinity, north = -Infinity;
- let westShifted = Infinity, eastShifted = -Infinity;
-
- for (const [ lng, lat ] of points) {
- west = Math.min(west, lng);
- south = Math.min(south, lat);
- east = Math.max(east, lng);
- north = Math.max(north, lat);
-
- const shifted = lng < 0 ? lng + 360 : lng;
- westShifted = Math.min(westShifted, shifted);
- eastShifted = Math.max(eastShifted, shifted);
- }
-
- if (!Number.isFinite(west)) return null;
-
- return eastShifted - westShifted < east - west
- ? [ [ westShifted, south ], [ eastShifted, north ] ]
- : [ [ west, south ], [ east, north ] ];
- }
-
+function toRadians(degrees: number): number {
+ return (degrees * Math.PI) / 180;
+}
+
+function toDegrees(radians: number): number {
+ return (radians * 180) / Math.PI;
+}
+
+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.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 ]);
+ }
+
+ return 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 --cc pnpm-lock.yaml
index d1273a4303,f11be29d60..c25faa6cbd
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@@ -355,14 -363,8 +363,14 @@@ importers
specifier: 6.5.2
version: 6.5.2
temporal-polyfill:
- specifier: 1.0.3
- version: 1.0.3
+ specifier: 1.0.4
+ version: 1.0.4
+ terra-draw:
+ specifier: 1.32.3
+ version: 1.32.3
+ terra-draw-maplibre-gl-adapter:
+ specifier: 1.4.1
devDependencies:
'@ckeditor/ckeditor5-inspector':
specifier: 5.0.3
@@@ -11529,63 -10853,11 +10859,20 @@@ packages
resolution: {integrity: sha512-wxVoanmDeavXie1vu2JaQ3WIc3JZnWAOYFBsJyATaVsXsycKYUflGsyBmrRSnoCpZJpwPyr38VpgSUlQ8CbFxg==}
- resolution: {integrity: sha512-HAixuesxFQIUaQk3ptX2jhfO/FsOkgVkDDMawvp6n/fkB1q6BKfs3lURw9I+pK/2e2e/q/vrLrxmeqauBoyGMQ==}
+ resolution: {integrity: sha512-1B8Dl4KzrOvsNUlpoWGno2VLQlxroLjDgc5NBjVC9ax9ymdo+ezfyvhyjEMx+IVfhINr6CIG2gcnlP95iRrybQ==}
+ 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'}
- peerDependencies:
- '@minify-html/node': '*'
- '@swc/core': '*'
- '@swc/css': '*'
- '@swc/html': '*'
- clean-css: '*'
- cssnano: '*'
- csso: '*'
- esbuild: '*'
- html-minifier-terser: '*'
- lightningcss: '*'
- postcss: '*'
- uglify-js: '*'
- webpack: '>=5.104.1'
- peerDependenciesMeta:
- '@minify-html/node':
- optional: true
- '@swc/core':
- optional: true
- '@swc/css':
- optional: true
- '@swc/html':
- optional: true
- clean-css:
- optional: true
- cssnano:
- optional: true
- csso:
- optional: true
- esbuild:
- optional: true
- html-minifier-terser:
- optional: true
- lightningcss:
- optional: true
- postcss:
- optional: true
- uglify-js:
- optional: true
-
- resolution: {integrity: sha512-tPbLXTI6ohPASb/1YViL428oEHu6/qv1OxqYnfaonVCFHqx4+wCd95pHrQWsL5X4pl90CTyW9piSAsS2L0VoMw==}
+ resolution: {integrity: sha512-bWnjSNscmuI+GJze6ZupnHP8G/cTcsJF+bXCeQknk2SHQsgbNJnLrqiH9jZ2W4STPVXH2mDKKRX3iwPhc9Cn/Q==}
engines: {node: '>=10'}
hasBin: true
@@@ -25397,32 -23718,12 +23733,19 @@@ snapshots
+ dependencies:
- maplibre-gl: 5.24.0
++ maplibre-gl: 6.8.0
+ terra-draw: 1.32.3
+
+
- dependencies:
- '@jridgewell/trace-mapping': 0.3.31
- jest-worker: 27.5.1
- schema-utils: 4.3.3
- terser: 5.47.1
- optionalDependencies:
- csso: 5.0.5
- esbuild: 0.28.1
- lightningcss: 1.33.0
- postcss: 8.5.20
-
dependencies:
'@jridgewell/source-map': 0.3.11
- acorn: 8.17.0
+ acorn: 8.18.0
commander: 2.20.3
source-map-support: 0.5.21