@ruckc/truss-ol 1.56.0 → 1.57.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -59,15 +59,18 @@ npm install @ruckc/truss-ol @ruckc/truss-ui ol
59
59
  | `featureStyle` | Per-feature styling by function (`fill`, `opacity`, `stroke`, `strokeWidth`, `radius`, `label`, `colors`). Features may also carry `style` / simplestyle properties. `colors: string[]` draws a pie marker, see below. |
60
60
  | `onviewchange`, `extent` (bindable) | `onviewchange({ center, zoom, extent })` fires on `moveend`, including a load-time fit that moved the view, but never for the starting view (`center`/`zoom`, `initialView`); `extent` is `[west, south, east, north]`. `bind:extent` is a read-only output that holds the starting view too. Neither fires when the view did not change, so applying `center`/`zoom` does not loop. |
61
61
  | `initialView` | Where the map starts, applied before anything is reported: `{ center: [lon, lat], zoom }` or `{ extent: [west, south, east, north], padding?, maxZoom? }` (fitted once the container has a size). Wins over `center`/`zoom`; `fitOnLoad` wins over it when there is data. Read once, on mount. |
62
- | `controls`, `fitTarget`, `onfit` | `controls={{ zoom: false }}` / `{{ fit: false }}` hide built-in buttons (both show by default; the `toolbar` snippet always shows). `fitTarget` (anything `fit()` takes, or a function returning it) is "the data" for the fit button, `fitOnLoad`, `fitOnDataChange`, `refitOnResize` and `fit()`; by default the markers, GeoJSON, points and `trussInteractive` layers. `onfit` replaces what the fit button does. |
62
+ | `controls`, `fitTarget`, `onfit` | `controls={{ zoom: false }}` / `{{ fit: false }}` hide built-in buttons (both show by default; the `toolbar` snippet always shows); `{{ locate: true }}` adds "Show my location". `fitTarget` (anything `fit()` takes, or a function returning it) is "the data" for the fit button, `fitOnLoad`, `fitOnDataChange`, `refitOnResize` and `fit()`; by default the markers, GeoJSON, points and `trussInteractive` layers. `onfit` replaces what the fit button does. |
63
63
  | `attribution` | `{ collapsed: false }` (default, expanded), `true`, or `'auto'`: collapsed while the map is narrower than 640px (the map's width, not the viewport's; a reader's own open/close stands until the map crosses 640px). The scale line always stacks above the attribution's measured height. |
64
64
  | `variant` | `'bare'`: no border, no radius, and the full height of its container unless `height` is set (an edge-to-edge map). |
65
65
  | `selected` (bindable), `onselect` | Selection of a marker, GeoJSON feature or point (or a feature of a `trussInteractive` layer, see below), by click or keyboard. `onselect` and `featurePopup` receive the `geometryType` (`Point`, `Polygon`, ...). |
66
66
  | `popup`, `featurePopup`, `toolbar` | Snippets: marker popup body, feature popup body, extra toolbar controls. |
67
+ | `drawMode`, `editLayer`, `snap`, `ondrawend`, `onmodifyend`, `onmoveend` | Draw a point, line or polygon, drag vertices (`'modify'`) or whole features (`'move'`) on an app layer (by its `id` property) or the map's GeoJSON. See below. |
68
+ | `onlocate`, `onlocateerror` | The `controls.locate` button's positions and errors. |
69
+ | `oncontextmenu` | Right-click, touch long-press, ContextMenu key / Shift+F10: `{ lonLat, pixel, x, y, feature?, source }`. |
67
70
  | `fitOnLoad`, `fitOnDataChange`, `refitOnResize` | When the view fits the data. `center` and `zoom` are applied only when you change them, so their defaults never undo a fit. |
68
- | `height`, `onready` | Map height: px or any CSS length (`'100%'`, `'calc(100dvh - 56px)'`), server-rendered as a nonced rule (no `style` attribute); `onready(api)` receives `{ map, fit, setView, getView, updateSize, select }`. |
71
+ | `height`, `onready` | Map height: px or any CSS length (`'100%'`, `'calc(100dvh - 56px)'`), server-rendered as a nonced rule (no `style` attribute); `onready(api)` receives `{ map, fit, setView, getView, updateSize, select, openPopup, closePopup, finishDrawing, abortDrawing, undoLastPoint }`. |
69
72
 
70
- Methods (via `bind:this`): `fit(target?, { padding, duration, maxZoom })`, `setView({ center, zoom, duration })`, `getView()`, `updateSize()`, `select(layer, id)`.
73
+ Methods (via `bind:this`): `fit(target?, { padding, duration, maxZoom })`, `setView({ center, zoom, duration })`, `getView()`, `updateSize()`, `select(layer, id)`, `openPopup(lonLat, options)`, `closePopup()`, `finishDrawing()`, `abortDrawing()`, `undoLastPoint()`.
71
74
 
72
75
  ### Your own layers
73
76
 
@@ -96,6 +99,32 @@ api.select(null, null); // clear
96
99
 
97
100
  `onviewchange` only reports moves, so saving every change never overwrites the saved view with the default one.
98
101
 
102
+ ### Your own popup, drawing, my location and a context menu (#303)
103
+
104
+ ```svelte
105
+ <script lang="ts">
106
+ import { Map, type MapApi, type MapDrawMode } from '@ruckc/truss-ol';
107
+ let api: MapApi;
108
+ let mode = $state<MapDrawMode | null>(null);
109
+ </script>
110
+
111
+ {#snippet place()}<PlaceCard feature={hit} />{/snippet}
112
+
113
+ <Map onready={(a) => (api = a)}
114
+ drawMode={mode} editLayer="places" ondrawend={saveNew} onmodifyend={saveEdits} onmoveend={saveEdits}
115
+ controls={{ locate: { follow: true } }} onlocateerror={(e) => console.warn(e.code)}
116
+ oncontextmenu={(e) => menu.open(e.x, e.y)} />
117
+
118
+ <!-- anywhere: api.openPopup(lonLat, { content: place, label: hit.name, onclose }) / api.closePopup() -->
119
+ ```
120
+
121
+ - **Popup:** `openPopup(lonLat, { content: Snippet | HTMLElement, autoPan?, closeButton?, label?, onclose? })` and `closePopup()` (on the api and the component) use the selection popup's card and arrow. One popup at a time: it replaces the selection popup until the selection changes. A `role="dialog"`; focus moves in (first control, else the card) and back on close; `Escape`, the × button, a click on the map, a new selection or another `openPopup` close it.
122
+ - **Draw and edit:** `drawMode` `'Point' | 'LineString' | 'Polygon' | 'modify' | 'move' | null` on `editLayer` (the `id` property of a vector layer you added; drawn features go into its source) or the map's own `geojson` (drawn features are only reported). `ondrawend({ feature, olFeature, layer })`, `onmodifyend` / `onmoveend({ features: [{ id, feature, olFeature }], layer })`, with GeoJSON in lon/lat. `snap` (default true), a sketch in the primary colour, clicks do not select while drawing. Keyboard on the focused map: Space adds a vertex at the centre, Enter finishes (or places a point), Backspace undoes, Escape cancels; `finishDrawing()`, `abortDrawing()`, `undoLastPoint()` on the api. The interactions load on first use.
123
+ - **Locate:** `controls={{ locate: true }}` or `{ follow, zoom, enableHighAccuracy, timeout, maximumAge }` adds a "Show my location" button: an accuracy circle and a dot in the primary colour, `onlocate({ lonLat, accuracy, heading, speed, timestamp })` on every update, an `onlocateerror({ code: 'denied' | 'unavailable' | 'timeout' | 'unsupported', message })` plus a `role="alert"` notice. `follow` keeps the view on the position until the reader pans; the next press re-centres, a press while centred stops.
124
+ - **Context menu:** `oncontextmenu({ lonLat, pixel, x, y, feature?, source })` on right-click, touch long-press, and the ContextMenu key or Shift+F10 on the focused map (at the selected feature, else the centre). It only reports where; open truss-ui's `ContextMenu` with `open(x, y)` (#304).
125
+
126
+ All new texts are `MapLabels` keys: `details`, `locate`, `located`, `locateDenied`, `locateUnavailable`, `locateUnsupported`, `drawing`.
127
+
99
128
  ### Pie markers
100
129
 
101
130
  `featureStyle` may return `{ colors, radius?, stroke?: { color, width } }` for a point. One colour is a filled circle; two to six are equal slices from 12 o'clock, clockwise (more than six are ignored); colours are any CSS colours, so hex strings from your data work. The outline defaults to black, 1px. Icons are drawn once to a canvas and cached by colours, radius and outline. A selected pie keeps its slices and gains a ring. `markers` accept `colors`, `radius` and `stroke` directly.
package/dist/Map.svelte CHANGED
@@ -32,6 +32,21 @@
32
32
  loadFailed: (reason: string) => string;
33
33
  /** Tooltip of the attribution's show/hide button. The provider credits themselves come from the tile sources and are not translated here. */
34
34
  attributions: string;
35
+ // #303
36
+ /** Accessible name of a popup opened with `openPopup` when it passes no `label`. */
37
+ details: string;
38
+ /** Accessible name of the locate button (`controls={{ locate: true }}`). */
39
+ locate: string;
40
+ /** Announced when the locate control first finds the reader; `accuracy` in metres. */
41
+ located: (accuracy: number) => string;
42
+ /** Shown when the reader refused location access. */
43
+ locateDenied: string;
44
+ /** Shown when the position could not be found (no fix, or it took too long). */
45
+ locateUnavailable: string;
46
+ /** Shown when the browser has no Geolocation API. */
47
+ locateUnsupported: string;
48
+ /** Announced when `drawMode` changes: how to draw or edit with the pointer and the keyboard. */
49
+ drawing: (mode: 'Point' | 'LineString' | 'Polygon' | 'modify' | 'move') => string;
35
50
  };
36
51
  const DEFAULTS: MapLabels = {
37
52
  map: 'Map. Arrow keys pan, plus and minus zoom.',
@@ -49,7 +64,20 @@
49
64
  high: 'High',
50
65
  legendRange: (title, from, to) => `${title}: ${from} to ${to}`,
51
66
  loadFailed: (reason) => `Map failed to load: ${reason}`,
52
- attributions: 'Attributions'
67
+ attributions: 'Attributions',
68
+ details: 'Details',
69
+ locate: 'Show my location',
70
+ located: (accuracy) => `Showing your location, accurate to about ${Math.round(accuracy)} metres`,
71
+ locateDenied: 'Location access was denied. Allow it in the browser to show where you are.',
72
+ locateUnavailable: 'Your location could not be found.',
73
+ locateUnsupported: 'This browser cannot share its location.',
74
+ drawing: (mode) => ({
75
+ Point: 'Drawing a point: click the map, or press Enter to place it at the centre. Arrow keys pan.',
76
+ LineString: 'Drawing a line: click to add points and double-click to finish. Keyboard: Space adds a point at the centre, Enter finishes, Backspace removes the last point, Escape cancels.',
77
+ Polygon: 'Drawing an area: click to add corners and double-click to finish. Keyboard: Space adds a corner at the centre, Enter finishes, Backspace removes the last corner, Escape cancels.',
78
+ modify: 'Editing shapes: drag a vertex to move it, or drag an edge to add one.',
79
+ move: 'Moving features: drag a feature to move it.'
80
+ })[mode]
53
81
  };
54
82
  </script>
55
83
 
@@ -57,11 +85,15 @@
57
85
  import { useLabels } from './labels.js';
58
86
  import { cssvars } from './cssvars.js';
59
87
  import SsrStyle from './SsrStyle.svelte';
60
- import { onMount, type Snippet } from 'svelte';
88
+ import { onMount, tick, untrack, type Snippet } from 'svelte';
61
89
  import { Button, readColorTokens, onThemeChange } from '@ruckc/truss-ui';
62
90
  import 'ol/ol.css';
63
91
  import type OLMap from 'ol/Map.js';
64
92
  import type { Basemap, FitOptions, FitTarget, MapApi, MapAttribution, MapControls, MapFeatureInfo, MapInitialView, MapMarker, MapSelection, MapViewChange, MapViewState } from './types.js';
93
+ import type { MapContextMenuEvent, MapDrawEnd, MapDrawMode, MapEditEnd, MapLocateError, MapLocation, MapPopupOptions } from './types.js';
94
+ import { createEditor, isDrawMode } from './edit.js';
95
+ import { locateOptions, watchLocation } from './locate.js';
96
+ import { wireContextMenu } from './contextmenu.js';
65
97
  import {
66
98
  DEFAULT_PALETTES, EMPTY_STORE, NATIVE_CLUSTER_MAX, aggregate, drawPie, pieKey, pieStroke, addStat, autoMode, clusterProps, clusterRadius, compactCount, compileCluster, compileStyle, cssGradient, featureTitle,
67
99
  isLight, lonLatExtent, moveMs, newStat, numbersOf, popupEntries, propertyStyle, storeExtent, toStore, validLonLat, weightsOf, withAlpha,
@@ -107,6 +139,16 @@
107
139
  onselect,
108
140
  onviewchange,
109
141
  onready,
142
+ // #303: draw and edit, locate, context menu
143
+ drawMode = null,
144
+ editLayer,
145
+ snap = true,
146
+ ondrawend,
147
+ onmodifyend,
148
+ onmoveend,
149
+ onlocate,
150
+ onlocateerror,
151
+ oncontextmenu,
110
152
  labels
111
153
  }: {
112
154
  /** [lon, lat] */
@@ -221,8 +263,38 @@
221
263
  * visible extent `[west, south, east, north]`. Not fired for the starting view (`center`/`zoom` or `initialView`) nor for a move that changed nothing.
222
264
  */
223
265
  onviewchange?: (v: MapViewChange) => void;
224
- /** Called once the map exists, with the imperative API (`map`, `fit`, `setView`, `getView`, `updateSize`, `select`). */
266
+ /** Called once the map exists, with the imperative API (`map`, `fit`, `setView`, `getView`, `updateSize`, `select`, `openPopup`, `closePopup`, `finishDrawing`, `abortDrawing`, `undoLastPoint`). */
225
267
  onready?: (api: MapApi) => void;
268
+ // ---- #303
269
+ /**
270
+ * Draw or edit (`null`, the default, does neither): `'Point'`, `'LineString'` or `'Polygon'` draws a new feature (`ondrawend`), `'modify'` drags
271
+ * vertices of existing ones (`onmodifyend`), `'move'` drags whole features (`onmoveend`). The target is `editLayer`, else the map's own `geojson`.
272
+ * While drawing, clicks do not select, and the focused map takes Space (add a vertex at the centre), Enter (finish), Backspace and Escape.
273
+ */
274
+ drawMode?: MapDrawMode | null;
275
+ /**
276
+ * The vector layer `drawMode` works on, by its `id` property: a layer your app added to `api.map` (`properties: { id: 'places' }`).
277
+ * Drawn features are added to its source. Without it, `modify` and `move` edit the map's own GeoJSON features and a drawn feature is only
278
+ * reported (add it to `geojson`). A layer that is not on the map yet is waited for.
279
+ */
280
+ editLayer?: string;
281
+ /** Snap the pointer to the vertices and edges of the features being edited. Default true. */
282
+ snap?: boolean;
283
+ /** A point, line or polygon was drawn: its GeoJSON (lon/lat) and the OpenLayers feature. */
284
+ ondrawend?: (e: MapDrawEnd) => void;
285
+ /** Vertices were dragged (`drawMode: 'modify'`): the changed features with their new geometry. */
286
+ onmodifyend?: (e: MapEditEnd) => void;
287
+ /** Features were dragged (`drawMode: 'move'`). */
288
+ onmoveend?: (e: MapEditEnd) => void;
289
+ /** The locate control (`controls.locate`) has a position: on the first fix and every update while it is on. */
290
+ onlocate?: (l: MapLocation) => void;
291
+ /** The locate control failed: permission denied, no position, a timeout, or no Geolocation API. The map shows `message` too. */
292
+ onlocateerror?: (e: MapLocateError) => void;
293
+ /**
294
+ * A right-click, a touch long-press, or the ContextMenu key / Shift+F10 on the focused map (at the selected feature, else the centre): where
295
+ * (`lonLat`, map `pixel`, viewport `x`/`y`) and the feature there. Setting it suppresses the browser's own menu on the map.
296
+ */
297
+ oncontextmenu?: (e: MapContextMenuEvent) => void;
226
298
  /** Replaces the built-in texts (translation). Missing keys keep the defaults. */
227
299
  labels?: Partial<MapLabels>;
228
300
  } = $props();
@@ -258,6 +330,35 @@
258
330
  export function updateSize() { ctl?.updateSize(); }
259
331
  /** Select a feature without firing `onselect`: `layer` `null` for the map's own features, else the `id` property of an app layer; `id` `null` clears. False when not found. */
260
332
  export function select(layer: string | null, id: string | number | null | undefined): boolean { return ctl?.select(layer, id) ?? false; }
333
+
334
+ // ---- #303: the app popup, drawing and editing, the locate control, the context menu
335
+ let appEl: HTMLDivElement;
336
+ /** The popup `openPopup` opened. While it shows it takes the selection popup's place (one popup at a time). */
337
+ let app = $state.raw<MapPopupOptions | null>(null);
338
+ /** The selection popup stays closed after an app popup replaced it, until the selection changes. */
339
+ let hush = $state(false);
340
+ /** A locate error, shown on the map until dismissed or the next try. */
341
+ let notice = $state<string>();
342
+ /** The locate control is on (watching the position). */
343
+ let tracking = $state(false);
344
+ let x303: {
345
+ open(at: [number, number], o: MapPopupOptions): void; close(): void; selChange(): void;
346
+ finish(): void; abort(): void; undo(): void; edit(): void; ctx(): void; pressLocate(): void; stopLocate(): void;
347
+ } | undefined;
348
+ /** Open the map's popup at `[lon, lat]` with your content (a snippet or an element). It replaces the selection popup. */
349
+ export function openPopup(lonLat: [number, number], options: MapPopupOptions) { x303?.open(lonLat, options); }
350
+ /** Close the popup `openPopup` opened. */
351
+ export function closePopup() { x303?.close(); }
352
+ /** Finish the line or polygon being drawn (Enter). */
353
+ export function finishDrawing() { x303?.finish(); }
354
+ /** Drop the sketch being drawn (Escape). */
355
+ export function abortDrawing() { x303?.abort(); }
356
+ /** Remove the last vertex of the sketch (Backspace). */
357
+ export function undoLastPoint() { x303?.undo(); }
358
+ const locOpts = $derived(locateOptions(controls?.locate));
359
+ const sketchMode = $derived(isDrawMode(drawMode));
360
+ /** Moves an element the app rendered into the popup, and detaches it again when the popup closes. */
361
+ const adopt = (content: HTMLElement) => (node: HTMLElement) => { node.append(content); return () => content.remove(); };
261
362
  let sync: { limits(): void; markers(): void; geo(): void; points(): void; base(): void; style(): void; select(): void; view(): void; attribution(): void } | undefined;
262
363
  let failed = $state<string>();
263
364
  let legendInfo = $state.raw<LegendInfo>({});
@@ -664,11 +765,12 @@
664
765
  }),
665
766
  updateSize: () => map.updateSize(),
666
767
  select: (layer, id) => {
667
- if (id === null || id === undefined) { clicked = undefined; selLayer = undefined; selected = mine = undefined; sync!.select(); return true; }
768
+ if (id === null || id === undefined) { x303?.selChange(); clicked = undefined; selLayer = undefined; selected = mine = undefined; sync!.select(); return true; }
668
769
  const l: any = layer === null ? undefined : map.getAllLayers().find((x: any) => layerIdOf(x) === layer && typeof x.getSource()?.getFeatureById === 'function');
669
770
  if (layer !== null && !l) return false;
670
771
  const k = String(id);
671
772
  if (!(l ? l.getSource().getFeatureById(k) : markerSrc.getFeatureById(k) ?? geoSrc.getFeatureById(k) ?? ptSrc.getFeatureById(k) ?? aggSrc.getFeatureById(k))) return false;
773
+ x303?.selChange();
672
774
  clicked = undefined; selLayer = l; selected = mine = k; sync!.select();
673
775
  return true;
674
776
  }
@@ -690,7 +792,7 @@
690
792
  refreshView();
691
793
  emitView();
692
794
  });
693
- const clear = () => { selLayer = undefined; selected = mine = undefined; sync!.select(); onselect?.(null); };
795
+ const clear = () => { x303?.selChange(); selLayer = undefined; selected = mine = undefined; sync!.select(); onselect?.(null); };
694
796
  /**
695
797
  * Select a feature (marker, GeoJSON feature, point, or a feature of a `trussInteractive` layer `l`) as a click or the keyboard would;
696
798
  * `at` anchors the popup for shapes. A feature without an id, or one that cannot be found again, clears the selection instead.
@@ -698,6 +800,7 @@
698
800
  const choose = (f: any, l: any, at?: number[]) => {
699
801
  const raw = f.getId();
700
802
  if (raw === undefined) { clear(); return; }
803
+ x303?.selChange();
701
804
  selLayer = own(l) ? undefined : l;
702
805
  const id = String(raw);
703
806
  clicked = at ? { id, at } : undefined;
@@ -723,11 +826,13 @@
723
826
  choose(next.f, next.l);
724
827
  };
725
828
  const onkey = (e: KeyboardEvent) => {
829
+ if (key303(e)) return;
726
830
  if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); cycle(e.shiftKey ? -1 : 1); }
727
831
  else if (e.key === 'Escape') { hideTip(); if (selected !== undefined) clear(); }
728
832
  };
729
833
  el.addEventListener('keydown', onkey);
730
834
  map.on('singleclick', (e) => {
835
+ if (click303()) return;
731
836
  const hit = map.forEachFeatureAtPixel(e.pixel, (f, l) => ({ f, l }), { hitTolerance: 6, layerFilter: hittable });
732
837
  const cl = hit?.f.get('_cluster');
733
838
  if (cl) {
@@ -756,8 +861,186 @@
756
861
  el.addEventListener('pointerleave', hideTip);
757
862
  map.on('movestart', hideTip);
758
863
 
864
+ // ---- #303: the app popup, drawing and editing, the locate control, the context menu
865
+ // The app popup: its own overlay and element, styled like the selection popup, which it hides while it shows.
866
+ const appOverlay = new Overlay({ element: appEl, positioning: 'bottom-center', offset: [0, -16], stopEvent: true });
867
+ map.addOverlay(appOverlay);
868
+ /** Where focus goes back to when the app popup closes (what had it when the popup opened). */
869
+ let returnTo: HTMLElement | null = null;
870
+ const closeApp = (restore = true) => {
871
+ const a = app;
872
+ if (!a) return;
873
+ const active = document.activeElement;
874
+ const inside = appEl.contains(active) || active === document.body;
875
+ app = null;
876
+ appOverlay.setPosition(undefined);
877
+ a.onclose?.();
878
+ if (restore && inside) (returnTo?.isConnected ? returnTo : el).focus({ preventScroll: true });
879
+ returnTo = null;
880
+ };
881
+ const FOCUSABLE = 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
882
+ const openApp = async (lonLat: [number, number], o: MapPopupOptions) => {
883
+ if (!validLonLat(lonLat[0], lonLat[1])) return;
884
+ const active = document.activeElement as HTMLElement | null;
885
+ // a popup replacing another keeps the first one's way back
886
+ const back = app ? returnTo : active && active !== document.body ? active : null;
887
+ closeApp(false);
888
+ returnTo = back;
889
+ hideTip();
890
+ app = o; hush = true;
891
+ appOverlay.setPosition(fromLonLat(lonLat));
892
+ await tick();
893
+ if (app !== o) return;
894
+ const card = appEl.querySelector<HTMLElement>('.card')!;
895
+ (card.querySelector<HTMLElement>(`.body :is(${FOCUSABLE})`) ?? card).focus({ preventScroll: true });
896
+ if (o.autoPan !== false) appOverlay.panIntoView({ animation: { duration: moveMs(250) }, margin: 24 });
897
+ };
898
+ // Escape inside either popup closes it and gives focus back; other keys there are the popup's own (never the map's Enter or arrows)
899
+ const popKey = (e: KeyboardEvent) => {
900
+ if (e.key !== 'Escape') return;
901
+ e.stopPropagation();
902
+ if (e.currentTarget === appEl) closeApp();
903
+ else { el.focus({ preventScroll: true }); clear(); }
904
+ };
905
+ appEl.addEventListener('keydown', popKey);
906
+ popupEl.addEventListener('keydown', popKey);
907
+
908
+ // Drawing and editing (edit.ts): ol/interaction/* load when a drawMode is first set.
909
+ let sketchKey = '', sketchStyle: any;
910
+ const sketch = () => {
911
+ const k = `${T.primary}|${T.surface}`;
912
+ if (k !== sketchKey) {
913
+ sketchKey = k;
914
+ sketchStyle = new Style({
915
+ image: new CircleStyle({ radius: 6, fill: new Fill({ color: T.primary }), stroke: new Stroke({ color: T.surface, width: 2 }) }),
916
+ stroke: new Stroke({ color: T.primary, width: 2.5, lineDash: [6, 4] }),
917
+ fill: new Fill({ color: rgba(T.primary, 0.15) })
918
+ });
919
+ }
920
+ return sketchStyle;
921
+ };
922
+ const gj = new GeoJSON();
923
+ const editor = createEditor({
924
+ map, own: geoLayer, style: sketch,
925
+ find: (id) => map.getAllLayers().find((l: any) => layerIdOf(l) === id && typeof l.getSource?.()?.getFeatures === 'function'),
926
+ toGeoJSON: (f) => gj.writeFeatureObject(f, { featureProjection: 'EPSG:3857', dataProjection: 'EPSG:4326' }) as any,
927
+ events: () => ({ drawend: ondrawend, modifyend: onmodifyend, moveend: onmoveend })
928
+ });
929
+ let lastMode: MapDrawMode | null = null;
930
+
931
+ // The locate control (locate.ts): an accuracy circle and a dot in the primary colour, on a layer of its own that takes no clicks.
932
+ let stopWatch: (() => void) | undefined;
933
+ let locSrc: any, locLayer: any, circular: any, lastFix: MapLocation | undefined;
934
+ /** The reader moved the map since we last centred it: `follow` pauses, and the button re-centres instead of turning off. */
935
+ let panned = false;
936
+ const locStyle = (f: any) => f.get('acc')
937
+ ? new Style({ fill: new Fill({ color: rgba(T.primary, 0.12) }), stroke: new Stroke({ color: rgba(T.primary, 0.5), width: 1 }) })
938
+ : [new Style({ image: new CircleStyle({ radius: 13, fill: new Fill({ color: rgba(T.primary, 0.2) }) }) }), new Style({ image: new CircleStyle({ radius: 7, fill: new Fill({ color: T.primary }), stroke: new Stroke({ color: T.surface, width: 2.5 }) }) })];
939
+ const centreOn = (l: MapLocation, zoomTo?: number) => view.animate({ center: fromLonLat(l.lonLat), ...(zoomTo !== undefined && { zoom: Math.max(view.getZoom()!, zoomTo) }), duration: moveMs(400) });
940
+ const stopLocate = () => { stopWatch?.(); stopWatch = undefined; tracking = false; locSrc?.clear(); lastFix = undefined; };
941
+ const startLocate = async () => {
942
+ notice = undefined; tracking = true; panned = false;
943
+ if (!locSrc) {
944
+ circular = (await import('ol/geom/Polygon.js')).circular;
945
+ locSrc = new VectorSource();
946
+ map.addLayer(locLayer = new VectorLayer({ source: locSrc, style: locStyle, zIndex: 30 }));
947
+ }
948
+ if (!tracking) return; // turned off (or unmounted) while loading
949
+ let first = true;
950
+ const o = locOpts!;
951
+ stopWatch = watchLocation(o, (l) => {
952
+ lastFix = l;
953
+ locSrc.clear(true);
954
+ locSrc.addFeatures([new Feature({ geometry: circular(l.lonLat, l.accuracy, 64).transform('EPSG:4326', 'EPSG:3857'), acc: true }), new Feature(new Point(fromLonLat(l.lonLat)))]);
955
+ if (first || (o.follow && !panned)) centreOn(l, first ? o.zoom : undefined);
956
+ if (first) announce = L.located(l.accuracy);
957
+ first = false;
958
+ onlocate?.(l);
959
+ }, (code) => {
960
+ stopLocate();
961
+ const message = code === 'denied' ? L.locateDenied : code === 'unsupported' ? L.locateUnsupported : L.locateUnavailable;
962
+ notice = message;
963
+ onlocateerror?.({ code, message });
964
+ });
965
+ };
966
+ map.on('pointerdrag', () => { panned = true; });
967
+
968
+ // The context menu (contextmenu.ts): right-click and touch long-press; the keyboard is in key303.
969
+ let ctxWire: ReturnType<typeof wireContextMenu> | undefined;
970
+ /** A long-press just reported itself: the click OpenLayers makes of its lift must not select or clear. */
971
+ let pressed = false;
972
+ const onDown = () => { pressed = false; };
973
+ el.addEventListener('pointerdown', onDown, true);
974
+ const infoOf = (f: any, l: any, at: number[]): MapFeatureInfo => {
975
+ const g = f.getGeometry(), { geometry, ...properties } = f.getProperties(), layer = own(l) ? undefined : layerIdOf(l);
976
+ return { id: String(f.getId()), properties, geometryType: g.getType(), lonLat: toLonLat(g.getType() === 'Point' ? g.getCoordinates() : at) as [number, number], ...(layer !== undefined && { layer }) };
977
+ };
978
+ const fireCtx = (pixel: number[], source: MapContextMenuEvent['source'], feature?: MapFeatureInfo) => {
979
+ const r = el.getBoundingClientRect();
980
+ const ll = toLonLat(map.getCoordinateFromPixel(pixel));
981
+ oncontextmenu?.({ lonLat: [ll[0], ll[1]], pixel: [pixel[0], pixel[1]], x: r.left + pixel[0], y: r.top + pixel[1], ...(feature && { feature }), source });
982
+ };
983
+ const ctxAt = (x: number, y: number, source: 'mouse' | 'touch') => {
984
+ const r = el.getBoundingClientRect(), px = [x - r.left, y - r.top];
985
+ if (source === 'touch') pressed = true;
986
+ const hit = map.forEachFeatureAtPixel(px, (f, l) => ({ f, l }), { hitTolerance: 6, layerFilter: hittable });
987
+ fireCtx(px, source, hit && !hit.f.get('_cluster') && hit.f.getId() !== undefined ? infoOf(hit.f, hit.l, map.getCoordinateFromPixel(px)) : undefined);
988
+ };
989
+ /** The keyboard: at the selected feature (where its popup points), else the map centre. */
990
+ const ctxKey = () => {
991
+ ctxWire?.keyboard();
992
+ const m: any = sel ? markerSrc.getFeatureById(sel.id) : undefined;
993
+ const at = fsel ? fromLonLat(fsel.lonLat) : m ? m.getGeometry().getCoordinates() : view.getCenter()!;
994
+ fireCtx(map.getPixelFromCoordinate(at), 'keyboard', fsel ?? (m ? infoOf(m, markerLayer, at) : undefined));
995
+ };
996
+
997
+ /** Keys on the focused map for #303; true when used, or when they come from inside it (a popup, an OpenLayers control), so the map's own handler skips them. */
998
+ function key303(e: KeyboardEvent): boolean {
999
+ const t = e.target as Node;
1000
+ if (t !== el) return true; // a key in a popup or on an OpenLayers control (the attribution button) is theirs
1001
+ if (e.key.startsWith('Arrow')) panned = true;
1002
+ if (editor.key(e, view.getCenter()!)) return true;
1003
+ if (oncontextmenu && (e.key === 'ContextMenu' || (e.key === 'F10' && e.shiftKey))) { e.preventDefault(); ctxKey(); return true; }
1004
+ return false;
1005
+ }
1006
+ /** Whether OpenLayers' click is not a selection: the lift of a long-press, or a click that adds a vertex. */
1007
+ function click303(): boolean {
1008
+ if (pressed) { pressed = false; return true; }
1009
+ return editor.drawing;
1010
+ }
1011
+ /** The theme changed: the location layer and the sketch redraw with the new tokens. */
1012
+ function restyle303() { locLayer?.changed(); editor.restyle(); }
1013
+
1014
+ x303 = {
1015
+ open: (at, o) => void openApp(at, o),
1016
+ close: () => closeApp(),
1017
+ selChange: () => { hush = false; closeApp(); },
1018
+ finish: editor.finish, abort: editor.abort, undo: editor.undo,
1019
+ edit: () => {
1020
+ void editor.set(drawMode, editLayer, snap);
1021
+ // announced once the effects of this change have run (a selection sync resets the live region)
1022
+ const m = drawMode;
1023
+ if (m !== lastMode && m) void tick().then(() => { if (drawMode === m) announce = L.drawing(m); });
1024
+ lastMode = m;
1025
+ },
1026
+ ctx: () => {
1027
+ if (oncontextmenu && !ctxWire) ctxWire = wireContextMenu(el, ctxAt, () => !editor.drawing);
1028
+ else if (!oncontextmenu && ctxWire) { ctxWire.dispose(); ctxWire = undefined; }
1029
+ },
1030
+ pressLocate: () => {
1031
+ if (!tracking) void startLocate();
1032
+ else if (panned && lastFix) { panned = false; centreOn(lastFix); }
1033
+ else stopLocate();
1034
+ },
1035
+ stopLocate
1036
+ };
1037
+ const dispose303 = () => {
1038
+ editor.dispose(); stopLocate(); ctxWire?.dispose();
1039
+ appEl.removeEventListener('keydown', popKey); popupEl.removeEventListener('keydown', popKey); el.removeEventListener('pointerdown', onDown, true);
1040
+ };
1041
+
759
1042
  // ---- follow theme (data-theme or data-truss-theme on the map or any ancestor, or the OS preference)
760
- const restyle = () => sync?.style();
1043
+ const restyle = () => { sync?.style(); restyle303(); };
761
1044
  const unwatch = onThemeChange(el, restyle);
762
1045
 
763
1046
  // the container may not be laid out yet (a pane that is still sizing): fit once it has a size, and keep the map measured
@@ -782,12 +1065,16 @@
782
1065
  if (fitPending && el.clientWidth && el.clientHeight) { fitPending = false; ctl.fit(undefined, { duration: 0 }); }
783
1066
  ready = true;
784
1067
  emitView();
785
- onready?.({ map, fit: ctl.fit, setView: ctl.setView, getView: ctl.getView, updateSize: ctl.updateSize, select: ctl.select });
786
-
1068
+ // set before onready runs: an app callback that throws must not leave the observers behind
787
1069
  dispose = () => {
788
- unwatch(); el.removeEventListener('keydown', onkey); ro.disconnect(); attrRo.disconnect();
1070
+ unwatch(); el.removeEventListener('keydown', onkey); ro.disconnect(); attrRo.disconnect(); dispose303();
789
1071
  map.setTarget(undefined);
790
1072
  };
1073
+ x303.edit(); x303.ctx();
1074
+ onready?.({
1075
+ map, fit: ctl.fit, setView: ctl.setView, getView: ctl.getView, updateSize: ctl.updateSize, select: ctl.select,
1076
+ openPopup, closePopup, finishDrawing, abortDrawing, undoLastPoint
1077
+ });
791
1078
  })().catch((e) => (failed = e instanceof Error ? e.message : String(e)));
792
1079
 
793
1080
  return () => { dead = true; dispose(); };
@@ -811,14 +1098,21 @@
811
1098
  $effect(() => { if (selected !== mine) selLayer = undefined; if (ready) sync?.select(); });
812
1099
  $effect(() => { center; zoom; if (ready) sync?.view(); });
813
1100
  $effect(() => { attribution; L.attributions; if (ready) sync?.attribution(); });
1101
+ // #303
1102
+ $effect(() => { drawMode; editLayer; snap; if (ready) untrack(() => x303?.edit()); });
1103
+ $effect(() => { oncontextmenu; if (ready) untrack(() => x303?.ctx()); });
1104
+ $effect(() => { if (!locOpts && ready) untrack(() => x303?.stopLocate()); });
1105
+ /** A `selected` the consumer set closes the app popup and lets the selection popup show again (the map's own changes do this themselves). */
1106
+ let seenSel: string | undefined;
1107
+ $effect(() => { const s = selected; untrack(() => { if (s !== seenSel) { seenSel = s; if (s !== mine) x303?.selChange(); } }); });
814
1108
  </script>
815
1109
 
816
1110
  <SsrStyle {uid} rules={{ '': `height:${cssHeight}` }} />
817
- <div class="trm" class:bare={variant === 'bare'} data-sv={uid} bind:this={root} {@attach cssvars(() => ({ 'height': cssHeight }))}>
1111
+ <div class="trm" class:bare={variant === 'bare'} class:drawing={sketchMode} data-sv={uid} bind:this={root} {@attach cssvars(() => ({ 'height': cssHeight }))}>
818
1112
  <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
819
1113
  <div class="map" bind:this={el} tabindex="0" role="application" aria-label={L.map}></div>
820
1114
 
821
- <div class="popup" bind:this={popupEl} hidden={!sel && !fsel}>
1115
+ <div class="popup" bind:this={popupEl} hidden={!!app || hush || (!sel && !fsel)}>
822
1116
  {#if sel}
823
1117
  <div class="card" role="dialog" aria-label={sel.label ?? L.location}>
824
1118
  <button type="button" class="x" aria-label={L.close} onclick={() => { selected = undefined; onselect?.(null); }}>×</button>
@@ -840,18 +1134,30 @@
840
1134
  </div>
841
1135
  {/if}
842
1136
  </div>
1137
+ <!-- #303: the popup openPopup() opens, in the selection popup's card -->
1138
+ <div class="popup" bind:this={appEl} hidden={!app}>
1139
+ {#if app}
1140
+ <div class="card app" class:nox={app.closeButton === false} role="dialog" aria-label={app.label ?? L.details} tabindex="-1">
1141
+ {#if app.closeButton !== false}<button type="button" class="x" aria-label={L.close} onclick={() => x303?.close()}>×</button>{/if}
1142
+ <div class="body">
1143
+ {#if typeof app.content === 'function'}{@render app.content()}{:else}<div class="adopt" {@attach adopt(app.content)}></div>{/if}
1144
+ </div>
1145
+ </div>
1146
+ {/if}
1147
+ </div>
843
1148
  <div class="tip" bind:this={tipEl} id={tipId} role="tooltip" hidden={!tip || (!featureTooltip && !tipText)}>
844
1149
  {#if tip}{#if featureTooltip}{@render featureTooltip(tip)}{:else}{tipText}{/if}{/if}
845
1150
  </div>
846
1151
  <div class="sr" aria-live="polite">{announce}</div>
847
1152
 
848
- {#if showZoom || showFit || toolbar}
1153
+ {#if showZoom || showFit || locOpts || toolbar}
849
1154
  <div class="controls" role="toolbar" aria-label={L.controls}>
850
1155
  {#if showZoom}
851
1156
  <Button variant="minimal" intent="neutral" size="sm" icon="plus" aria-label={L.zoomIn} onclick={() => ctl?.zoomBy(1)} />
852
1157
  <Button variant="minimal" intent="neutral" size="sm" icon="minus" aria-label={L.zoomOut} onclick={() => ctl?.zoomBy(-1)} />
853
1158
  {/if}
854
1159
  {#if showFit}<Button variant="minimal" intent="neutral" size="sm" icon="expand" aria-label={L.fitToData} onclick={() => (onfit ? onfit() : ctl?.fit())} />{/if}
1160
+ {#if locOpts}<Button variant="minimal" intent="neutral" size="sm" icon="locate" aria-label={L.locate} pressed={tracking} onclick={() => x303?.pressLocate()} data-testid="trm-locate" />{/if}
855
1161
  {#if toolbar}{@render toolbar()}{/if}
856
1162
  </div>
857
1163
  {/if}
@@ -880,6 +1186,9 @@
880
1186
  {/each}
881
1187
  </div>
882
1188
  {/if}
1189
+ {#if notice}
1190
+ <div class="notice" role="alert">{notice}<button type="button" class="x" aria-label={L.close} onclick={() => (notice = undefined)}>×</button></div>
1191
+ {/if}
883
1192
  {#if failed}<div class="err" role="alert">{L.loadFailed(failed)}</div>{/if}
884
1193
  </div>
885
1194
 
@@ -915,6 +1224,12 @@
915
1224
  .lcat { list-style: none; margin: 4px 0 0; padding: 0; display: grid; gap: 2px; }
916
1225
  .lcat li { display: flex; align-items: center; gap: 6px; }
917
1226
  .lcat i { display: block; width: 10px; height: 10px; border-radius: 50%; }
1227
+ /* #303: the app popup (a dialog that takes focus itself when its content has nothing focusable), the keyboard crosshair while drawing, the locate notice */
1228
+ .card.app { outline: none; }
1229
+ .card.app.nox { padding-right: 12px; }
1230
+ .adopt { display: contents; }
1231
+ .trm.drawing .map:focus-visible::after { content: ''; position: absolute; left: 50%; top: 50%; width: 21px; height: 21px; margin: -10px 0 0 -10px; pointer-events: none; background: linear-gradient(var(--tr-primary), var(--tr-primary)) center / 2px 100% no-repeat, linear-gradient(var(--tr-primary), var(--tr-primary)) center / 100% 2px no-repeat; }
1232
+ .notice { position: absolute; z-index: 4; top: 8px; left: 50%; transform: translateX(-50%); width: max-content; max-width: calc(100% - 112px); padding: 8px 32px 8px 12px; background: var(--tr-surface-container-highest); border: 1px solid var(--tr-outline-variant); border-radius: var(--tr-radius-md); box-shadow: var(--tr-elevation-2); color: var(--tr-on-surface); font: var(--tr-text-sm) var(--tr-font-sans); }
918
1233
  .err { position: absolute; inset: auto 8px 8px; padding: 8px 12px; border-radius: var(--tr-radius-md); background: var(--tr-danger-container); color: var(--tr-on-danger-container); }
919
1234
 
920
1235
  /* Dark mode: tint raster tiles to the theme */
@@ -31,10 +31,25 @@ export type MapLabels = {
31
31
  loadFailed: (reason: string) => string;
32
32
  /** Tooltip of the attribution's show/hide button. The provider credits themselves come from the tile sources and are not translated here. */
33
33
  attributions: string;
34
+ /** Accessible name of a popup opened with `openPopup` when it passes no `label`. */
35
+ details: string;
36
+ /** Accessible name of the locate button (`controls={{ locate: true }}`). */
37
+ locate: string;
38
+ /** Announced when the locate control first finds the reader; `accuracy` in metres. */
39
+ located: (accuracy: number) => string;
40
+ /** Shown when the reader refused location access. */
41
+ locateDenied: string;
42
+ /** Shown when the position could not be found (no fix, or it took too long). */
43
+ locateUnavailable: string;
44
+ /** Shown when the browser has no Geolocation API. */
45
+ locateUnsupported: string;
46
+ /** Announced when `drawMode` changes: how to draw or edit with the pointer and the keyboard. */
47
+ drawing: (mode: 'Point' | 'LineString' | 'Polygon' | 'modify' | 'move') => string;
34
48
  };
35
49
  import { type Snippet } from 'svelte';
36
50
  import 'ol/ol.css';
37
51
  import type { Basemap, FitOptions, FitTarget, MapApi, MapAttribution, MapControls, MapFeatureInfo, MapInitialView, MapMarker, MapSelection, MapViewChange, MapViewState } from './types.js';
52
+ import type { MapContextMenuEvent, MapDrawEnd, MapDrawMode, MapEditEnd, MapLocateError, MapLocation, MapPopupOptions } from './types.js';
38
53
  import { type ClusterStyle, type FeatureStyle, type HeatmapOptions, type MapStyle, type PointsInput, type PointsMode, type Props } from './util.js';
39
54
  type $$ComponentProps = {
40
55
  /** [lon, lat] */
@@ -152,8 +167,37 @@ type $$ComponentProps = {
152
167
  * visible extent `[west, south, east, north]`. Not fired for the starting view (`center`/`zoom` or `initialView`) nor for a move that changed nothing.
153
168
  */
154
169
  onviewchange?: (v: MapViewChange) => void;
155
- /** Called once the map exists, with the imperative API (`map`, `fit`, `setView`, `getView`, `updateSize`, `select`). */
170
+ /** Called once the map exists, with the imperative API (`map`, `fit`, `setView`, `getView`, `updateSize`, `select`, `openPopup`, `closePopup`, `finishDrawing`, `abortDrawing`, `undoLastPoint`). */
156
171
  onready?: (api: MapApi) => void;
172
+ /**
173
+ * Draw or edit (`null`, the default, does neither): `'Point'`, `'LineString'` or `'Polygon'` draws a new feature (`ondrawend`), `'modify'` drags
174
+ * vertices of existing ones (`onmodifyend`), `'move'` drags whole features (`onmoveend`). The target is `editLayer`, else the map's own `geojson`.
175
+ * While drawing, clicks do not select, and the focused map takes Space (add a vertex at the centre), Enter (finish), Backspace and Escape.
176
+ */
177
+ drawMode?: MapDrawMode | null;
178
+ /**
179
+ * The vector layer `drawMode` works on, by its `id` property: a layer your app added to `api.map` (`properties: { id: 'places' }`).
180
+ * Drawn features are added to its source. Without it, `modify` and `move` edit the map's own GeoJSON features and a drawn feature is only
181
+ * reported (add it to `geojson`). A layer that is not on the map yet is waited for.
182
+ */
183
+ editLayer?: string;
184
+ /** Snap the pointer to the vertices and edges of the features being edited. Default true. */
185
+ snap?: boolean;
186
+ /** A point, line or polygon was drawn: its GeoJSON (lon/lat) and the OpenLayers feature. */
187
+ ondrawend?: (e: MapDrawEnd) => void;
188
+ /** Vertices were dragged (`drawMode: 'modify'`): the changed features with their new geometry. */
189
+ onmodifyend?: (e: MapEditEnd) => void;
190
+ /** Features were dragged (`drawMode: 'move'`). */
191
+ onmoveend?: (e: MapEditEnd) => void;
192
+ /** The locate control (`controls.locate`) has a position: on the first fix and every update while it is on. */
193
+ onlocate?: (l: MapLocation) => void;
194
+ /** The locate control failed: permission denied, no position, a timeout, or no Geolocation API. The map shows `message` too. */
195
+ onlocateerror?: (e: MapLocateError) => void;
196
+ /**
197
+ * A right-click, a touch long-press, or the ContextMenu key / Shift+F10 on the focused map (at the selected feature, else the centre): where
198
+ * (`lonLat`, map `pixel`, viewport `x`/`y`) and the feature there. Setting it suppresses the browser's own menu on the map.
199
+ */
200
+ oncontextmenu?: (e: MapContextMenuEvent) => void;
157
201
  /** Replaces the built-in texts (translation). Missing keys keep the defaults. */
158
202
  labels?: Partial<MapLabels>;
159
203
  };
@@ -165,6 +209,11 @@ declare const Map: import("svelte").Component<$$ComponentProps, {
165
209
  getView: () => MapViewState | undefined;
166
210
  updateSize: () => void;
167
211
  select: (layer: string | null, id: string | number | null | undefined) => boolean;
212
+ openPopup: (lonLat: [number, number], options: MapPopupOptions) => void;
213
+ closePopup: () => void;
214
+ finishDrawing: () => void;
215
+ abortDrawing: () => void;
216
+ undoLastPoint: () => void;
168
217
  }, "center" | "selected" | "zoom" | "extent">;
169
218
  type Map = ReturnType<typeof Map>;
170
219
  export default Map;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * @internal The Map's context-menu gestures (#303): a right-click (`contextmenu`) and a touch long-press (the core's `longPress`, the gesture
3
+ * the tooltips use). The keyboard (ContextMenu key, Shift+F10) is handled by the Map's own key handler, which calls `keyboard()` so the
4
+ * native `contextmenu` event some platforms send after the key is not reported twice.
5
+ */
6
+ export declare function wireContextMenu(el: HTMLElement, fire: (x: number, y: number, source: 'mouse' | 'touch') => void, touchOk: () => boolean): {
7
+ keyboard(): void;
8
+ dispose(): void;
9
+ };
@@ -0,0 +1,23 @@
1
+ import { longPress } from '@ruckc/truss-ui';
2
+ /**
3
+ * @internal The Map's context-menu gestures (#303): a right-click (`contextmenu`) and a touch long-press (the core's `longPress`, the gesture
4
+ * the tooltips use). The keyboard (ContextMenu key, Shift+F10) is handled by the Map's own key handler, which calls `keyboard()` so the
5
+ * native `contextmenu` event some platforms send after the key is not reported twice.
6
+ */
7
+ export function wireContextMenu(el, fire, touchOk) {
8
+ let kb = -Infinity;
9
+ const menu = (e) => {
10
+ e.preventDefault();
11
+ // a long-press in progress reports itself; a key press just did
12
+ if (el.hasAttribute('data-tr-pressing') || performance.now() - kb < 800)
13
+ return;
14
+ fire(e.clientX, e.clientY, 'mouse');
15
+ };
16
+ el.addEventListener('contextmenu', menu);
17
+ const press = longPress(el, ({ x, y }) => { if (touchOk())
18
+ fire(x, y, 'touch'); }, () => { });
19
+ return {
20
+ keyboard() { kb = performance.now(); },
21
+ dispose() { el.removeEventListener('contextmenu', menu); press.dispose(); }
22
+ };
23
+ }
package/dist/edit.d.ts ADDED
@@ -0,0 +1,42 @@
1
+ import type OLMap from 'ol/Map.js';
2
+ import type { GeoJSONFeature, MapDrawEnd, MapDrawMode, MapEditEnd } from './types.js';
3
+ /**
4
+ * @internal Drawing and editing for the Map (#303): OpenLayers' Draw, Modify, Translate and Snap, loaded on first use.
5
+ * The target is a vector layer found by its `id` property (`editLayer`, an app layer or, later, a `layers` entry of #302), or the
6
+ * Map's own GeoJSON layer. Kept out of Map.svelte so the component only wires props to it.
7
+ */
8
+ export type EditDeps = {
9
+ map: OLMap;
10
+ /** The Map's own GeoJSON layer: the target without `editLayer`. */
11
+ own: any;
12
+ /** A vector layer by its `id` property. */
13
+ find(id: string): any;
14
+ /** The sketch style (themed; read at each call). */
15
+ style: () => any;
16
+ toGeoJSON(f: any): GeoJSONFeature;
17
+ /** The current callbacks (props can change after the editor was created). */
18
+ events(): {
19
+ drawend?: (e: MapDrawEnd) => void;
20
+ modifyend?: (e: MapEditEnd) => void;
21
+ moveend?: (e: MapEditEnd) => void;
22
+ };
23
+ };
24
+ export declare const isDrawMode: (m: MapDrawMode | null | undefined) => m is "Point" | "LineString" | "Polygon";
25
+ /** Real vertices of a sketch (the last coordinate follows the pointer; a polygon's ring is closed back to its first vertex as well). */
26
+ export declare function sketchVertices(type: string, coords: any): number;
27
+ export declare function createEditor(d: EditDeps): {
28
+ set: (m: MapDrawMode | null, layer: string | undefined, snap: boolean) => Promise<void>;
29
+ finish: () => void;
30
+ abort: () => void;
31
+ undo: () => void;
32
+ /** Whether a draw mode (point, line, polygon) is active. */
33
+ readonly drawing: boolean;
34
+ /**
35
+ * The keyboard on the focused map while drawing: Space adds a vertex at the map centre (`center`), Enter finishes (or places a point),
36
+ * Backspace removes the last vertex, Escape drops the sketch. Returns whether the key was used.
37
+ */
38
+ key(e: KeyboardEvent, center: number[]): boolean;
39
+ /** The theme changed: redraw the sketch and the vertex handles (their style reads the tokens when drawn). */
40
+ restyle(): void;
41
+ dispose(): void;
42
+ };
package/dist/edit.js ADDED
@@ -0,0 +1,116 @@
1
+ export const isDrawMode = (m) => m === 'Point' || m === 'LineString' || m === 'Polygon';
2
+ /** Real vertices of a sketch (the last coordinate follows the pointer; a polygon's ring is closed back to its first vertex as well). */
3
+ export function sketchVertices(type, coords) {
4
+ return type === 'Polygon' ? Math.max(0, coords[0].length - 2) : coords.length - 1;
5
+ }
6
+ export function createEditor(d) {
7
+ let mode = null;
8
+ let ints = [];
9
+ let draw;
10
+ let sketch;
11
+ let token = 0;
12
+ let unwait;
13
+ const teardown = () => {
14
+ for (const i of ints)
15
+ d.map.removeInteraction(i);
16
+ ints = [];
17
+ draw = undefined;
18
+ sketch = undefined;
19
+ unwait?.();
20
+ unwait = undefined;
21
+ };
22
+ /** Switch to `m` on the layer `layer` (`undefined`: the Map's own GeoJSON); `null` stops. A layer that is not on the map yet is waited for. */
23
+ async function set(m, layer, snap) {
24
+ const t = ++token;
25
+ teardown();
26
+ mode = m;
27
+ if (!m)
28
+ return;
29
+ const l = layer === undefined ? d.own : d.find(layer);
30
+ if (!l) {
31
+ // a layer the app adds a moment later (created, then added in its own effect): start once it is there
32
+ const coll = d.map.getLayers();
33
+ const on = () => { if (d.find(layer))
34
+ void set(m, layer, snap); };
35
+ coll.on('add', on);
36
+ unwait = () => coll.un('add', on);
37
+ return;
38
+ }
39
+ const [{ default: Draw }, { default: Modify }, { default: Translate }, { default: Snap }] = await Promise.all([
40
+ import('ol/interaction/Draw.js'), import('ol/interaction/Modify.js'), import('ol/interaction/Translate.js'), import('ol/interaction/Snap.js')
41
+ ]);
42
+ if (t !== token)
43
+ return;
44
+ const source = l.getSource();
45
+ const tag = layer === undefined ? {} : { layer };
46
+ const report = (fs) => fs.map((f) => ({ ...(f.getId() !== undefined && { id: f.getId() }), feature: d.toGeoJSON(f), olFeature: f }));
47
+ if (isDrawMode(m)) {
48
+ // with an editLayer the drawn feature goes into its source; without one it is only reported (the app adds it to `geojson`)
49
+ draw = new Draw({ ...(layer !== undefined && { source }), type: m, style: d.style });
50
+ draw.on('drawstart', (e) => { sketch = e.feature; });
51
+ draw.on('drawabort', () => { sketch = undefined; });
52
+ draw.on('drawend', (e) => { sketch = undefined; d.events().drawend?.({ feature: d.toGeoJSON(e.feature), olFeature: e.feature, ...tag }); });
53
+ ints.push(draw);
54
+ }
55
+ else if (m === 'modify') {
56
+ const mod = new Modify({ source, style: d.style });
57
+ mod.on('modifyend', (e) => d.events().modifyend?.({ features: report(e.features.getArray()), ...tag }));
58
+ ints.push(mod);
59
+ }
60
+ else {
61
+ const tr = new Translate({ layers: [l], hitTolerance: 6 });
62
+ tr.on('translateend', (e) => d.events().moveend?.({ features: report(e.features.getArray()), ...tag }));
63
+ ints.push(tr);
64
+ }
65
+ // Snap goes last, so it sees the pointer before the interactions above
66
+ if (snap)
67
+ ints.push(new Snap({ source }));
68
+ for (const i of ints)
69
+ d.map.addInteraction(i);
70
+ }
71
+ const enough = () => {
72
+ const g = sketch?.getGeometry();
73
+ return !!g && sketchVertices(g.getType(), g.getCoordinates()) >= (mode === 'Polygon' ? 3 : 2);
74
+ };
75
+ const finish = () => { if (draw && sketch && enough())
76
+ draw.finishDrawing(); };
77
+ const abort = () => { draw?.abortDrawing(); };
78
+ const undo = () => { if (sketch)
79
+ draw.removeLastPoint(); };
80
+ /** Add a vertex at `at` (map coordinates), from the keyboard: a point is placed at once, a line or polygon grows. */
81
+ const add = (at) => {
82
+ draw.appendCoordinates([at]);
83
+ if (mode === 'Point')
84
+ draw.finishDrawing();
85
+ };
86
+ return {
87
+ set,
88
+ finish, abort, undo,
89
+ /** Whether a draw mode (point, line, polygon) is active. */
90
+ get drawing() { return !!draw; },
91
+ /**
92
+ * The keyboard on the focused map while drawing: Space adds a vertex at the map centre (`center`), Enter finishes (or places a point),
93
+ * Backspace removes the last vertex, Escape drops the sketch. Returns whether the key was used.
94
+ */
95
+ key(e, center) {
96
+ if (!draw)
97
+ return false;
98
+ if (e.key === ' ' || (e.key === 'Enter' && mode === 'Point'))
99
+ add(center);
100
+ else if (e.key === 'Enter')
101
+ finish();
102
+ else if (e.key === 'Backspace' && sketch)
103
+ undo();
104
+ else if (e.key === 'Escape' && sketch)
105
+ abort();
106
+ else
107
+ return false;
108
+ e.preventDefault();
109
+ return true;
110
+ },
111
+ /** The theme changed: redraw the sketch and the vertex handles (their style reads the tokens when drawn). */
112
+ restyle() { for (const i of ints)
113
+ i.getOverlay?.().changed(); },
114
+ dispose() { token++; teardown(); mode = null; }
115
+ };
116
+ }
package/dist/index.d.ts CHANGED
@@ -8,7 +8,7 @@ export { default as ScaleBar } from './ScaleBar.svelte';
8
8
  export type { ScaleBarLabels } from './ScaleBar.svelte';
9
9
  export { default as Attribution } from './Attribution.svelte';
10
10
  export type { AttributionLabels } from './Attribution.svelte';
11
- export type { MapMarker, MarkerKind, Basemap, MapSelection, MapFeatureInfo, MapViewState, MapViewChange, FitOptions, FitTarget, MapApi, MapInitialView, MapControls, MapAttribution } from './types.js';
11
+ export type { MapMarker, MarkerKind, Basemap, MapSelection, MapFeatureInfo, MapViewState, MapViewChange, FitOptions, FitTarget, MapApi, MapInitialView, MapControls, MapAttribution, MapPopupOptions, MapDrawMode, GeoJSONFeature, MapDrawEnd, MapEditEnd, MapLocateOptions, MapLocation, MapLocateError, MapContextMenuEvent } from './types.js';
12
12
  export type { MapStyle, SizeSpec, ColorSpec, FeatureStyle, PieStroke, LegendInfo, ClusterStyle, ClusterSizeSpec, ClusterColorSpec, ClusterBy, ClusterAgg, ClusterInfo } from './style.js';
13
13
  export type { PointsInput, PointInput, PointsMode, HeatmapOptions } from './points.js';
14
14
  export type { ControlPosition, ScaleUnit, HeadingStatus } from './util.js';
@@ -0,0 +1,9 @@
1
+ import type { MapLocateError, MapLocateOptions, MapLocation } from './types.js';
2
+ /** @internal The Geolocation API behind the Map's locate control (#303). */
3
+ /** A `GeolocationPositionError` code as the Map reports it. */
4
+ export declare function locateErrorCode(code: number): MapLocateError['code'];
5
+ export declare function toLocation(p: GeolocationPosition): MapLocation;
6
+ /** Resolved `controls.locate` options; `undefined` when the control is off. */
7
+ export declare function locateOptions(v: boolean | MapLocateOptions | undefined): Required<MapLocateOptions> | undefined;
8
+ /** Watch the position: `onfix` on each update, `onerror` once (the watch stops). Returns the stop function. */
9
+ export declare function watchLocation(o: Required<MapLocateOptions>, onfix: (l: MapLocation) => void, onerror: (code: MapLocateError['code']) => void): () => void;
package/dist/locate.js ADDED
@@ -0,0 +1,29 @@
1
+ /** @internal The Geolocation API behind the Map's locate control (#303). */
2
+ /** A `GeolocationPositionError` code as the Map reports it. */
3
+ export function locateErrorCode(code) {
4
+ return code === 1 ? 'denied' : code === 3 ? 'timeout' : 'unavailable';
5
+ }
6
+ export function toLocation(p) {
7
+ const c = p.coords;
8
+ return { lonLat: [c.longitude, c.latitude], accuracy: c.accuracy, heading: c.heading ?? null, speed: c.speed ?? null, timestamp: p.timestamp };
9
+ }
10
+ /** Resolved `controls.locate` options; `undefined` when the control is off. */
11
+ export function locateOptions(v) {
12
+ if (!v)
13
+ return undefined;
14
+ const o = v === true ? {} : v;
15
+ return { follow: o.follow ?? false, zoom: o.zoom ?? 15, enableHighAccuracy: o.enableHighAccuracy ?? true, timeout: o.timeout ?? 15000, maximumAge: o.maximumAge ?? 30000 };
16
+ }
17
+ /** Watch the position: `onfix` on each update, `onerror` once (the watch stops). Returns the stop function. */
18
+ export function watchLocation(o, onfix, onerror) {
19
+ // `Object(undefined)` is `{}`: no navigator (SSR) and no Geolocation API are the same case
20
+ const geo = Object(globalThis.navigator).geolocation;
21
+ let id;
22
+ const stop = () => { if (id !== undefined)
23
+ geo.clearWatch(id); id = undefined; };
24
+ if (!geo)
25
+ onerror('unsupported');
26
+ else
27
+ id = geo.watchPosition((p) => onfix(toLocation(p)), (e) => { stop(); onerror(locateErrorCode(e.code)); }, { enableHighAccuracy: o.enableHighAccuracy, timeout: o.timeout, maximumAge: o.maximumAge });
28
+ return stop;
29
+ }
package/dist/types.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type OLMap from 'ol/Map.js';
2
+ import type { Snippet } from 'svelte';
2
3
  export type MarkerKind = 'neutral' | 'primary' | 'success' | 'warning' | 'danger';
3
4
  export type MapMarker = {
4
5
  id: string;
@@ -98,6 +99,16 @@ export type MapApi = {
98
99
  * `id` `null`/`undefined` clears the selection. Returns false (and changes nothing) when the layer or the feature is not found.
99
100
  */
100
101
  select(layer: string | null, id: string | number | null | undefined): boolean;
102
+ /** Open the map's popup at `[lon, lat]` with your content (#303). It replaces the selection popup: one popup shows at a time. */
103
+ openPopup(lonLat: [number, number], options: MapPopupOptions): void;
104
+ /** Close the popup `openPopup` opened (its `onclose` runs). Does nothing when none is open. */
105
+ closePopup(): void;
106
+ /** Finish the line or polygon being drawn (`drawMode`), as Enter does. */
107
+ finishDrawing(): void;
108
+ /** Drop the sketch being drawn, as Escape does. */
109
+ abortDrawing(): void;
110
+ /** Remove the last vertex of the sketch being drawn, as Backspace does. */
111
+ undoLastPoint(): void;
101
112
  };
102
113
  /** Where the Map starts (`initialView`): a centre and zoom, or a lon/lat extent fitted once the container has a size. */
103
114
  export type MapInitialView = {
@@ -117,9 +128,100 @@ export type MapControls = {
117
128
  zoom?: boolean;
118
129
  /** Fit to data (see `fitTarget` and `onfit`). */
119
130
  fit?: boolean;
131
+ /** "Show my location" (off by default): `true`, or options. See `onlocate` / `onlocateerror`. */
132
+ locate?: boolean | MapLocateOptions;
120
133
  };
121
134
  /** OpenLayers' attribution control of the Map (`attribution`). */
122
135
  export type MapAttribution = {
123
136
  /** `false` (expanded, the default), `true` (collapsed behind its button), or `'auto'`: collapsed while the map is narrower than 640px. */
124
137
  collapsed?: boolean | 'auto';
125
138
  };
139
+ /** What `openPopup` takes. */
140
+ export type MapPopupOptions = {
141
+ /** The popup body: a snippet, or an element you rendered (it is moved into the popup, and detached again when the popup closes). */
142
+ content: Snippet | HTMLElement;
143
+ /** Pan the map so the whole popup shows. Default true. */
144
+ autoPan?: boolean;
145
+ /** Show the × button. Default true; Escape closes the popup either way. */
146
+ closeButton?: boolean;
147
+ /** The popup's accessible name (it is a `role="dialog"`). Default: the `details` label. */
148
+ label?: string;
149
+ /** Runs once when the popup closes: × button, Escape, a click on the map, a new selection, another `openPopup`, or `closePopup()`. */
150
+ onclose?: () => void;
151
+ };
152
+ /** What the map draws or edits (`drawMode`): a new point, line or polygon, the vertices of existing features (`modify`), or whole features (`move`). */
153
+ export type MapDrawMode = 'Point' | 'LineString' | 'Polygon' | 'modify' | 'move';
154
+ /** A GeoJSON Feature in lon/lat (EPSG:4326). */
155
+ export type GeoJSONFeature = {
156
+ type: 'Feature';
157
+ id?: string | number;
158
+ geometry: {
159
+ type: string;
160
+ coordinates: unknown;
161
+ } | null;
162
+ properties: Record<string, unknown> | null;
163
+ };
164
+ /** What `ondrawend` receives. */
165
+ export type MapDrawEnd = {
166
+ /** The new feature as GeoJSON (lon/lat). */
167
+ feature: GeoJSONFeature;
168
+ /**
169
+ * The OpenLayers feature. With `editLayer` it is added to that layer's source right after this call: give it an id (`olFeature.setId(saved.id)`)
170
+ * once you have saved it, or remove it again (`source.removeFeature(olFeature)`). Without `editLayer` it is not added anywhere; add `feature` to your `geojson`.
171
+ */
172
+ olFeature: any;
173
+ /** The `editLayer` it was drawn into; absent for the map's own GeoJSON. */
174
+ layer?: string;
175
+ };
176
+ /** What `onmodifyend` and `onmoveend` receive: every feature the gesture changed, with its new geometry. */
177
+ export type MapEditEnd = {
178
+ features: {
179
+ id?: string | number;
180
+ feature: GeoJSONFeature;
181
+ olFeature: any;
182
+ }[];
183
+ /** The `editLayer`; absent for the map's own GeoJSON. */
184
+ layer?: string;
185
+ };
186
+ /** The `locate` control's options (`controls={{ locate: { ... } }}`). */
187
+ export type MapLocateOptions = {
188
+ /** Keep the view centred on each new position until the reader pans the map; pressing the button again re-centres and resumes. Default false. */
189
+ follow?: boolean;
190
+ /** Zoom in to at least this level on the first fix. Default 15. */
191
+ zoom?: number;
192
+ /** `PositionOptions.enableHighAccuracy`. Default true. */
193
+ enableHighAccuracy?: boolean;
194
+ /** `PositionOptions.timeout` in ms. Default 15000. */
195
+ timeout?: number;
196
+ /** `PositionOptions.maximumAge` in ms. Default 30000. */
197
+ maximumAge?: number;
198
+ };
199
+ /** What `onlocate` receives, on every position update while the locate control is on. */
200
+ export type MapLocation = {
201
+ /** `[lon, lat]` */
202
+ lonLat: [number, number];
203
+ /** Radius of the accuracy circle, in metres. */
204
+ accuracy: number;
205
+ heading: number | null;
206
+ speed: number | null;
207
+ timestamp: number;
208
+ };
209
+ /** What `onlocateerror` receives: `denied` (permission refused), `unavailable`, `timeout` or `unsupported` (no Geolocation API). `message` is the text the map shows. */
210
+ export type MapLocateError = {
211
+ code: 'denied' | 'unavailable' | 'timeout' | 'unsupported';
212
+ message: string;
213
+ };
214
+ /** What `oncontextmenu` receives: a right-click, a touch long-press, or the ContextMenu key / Shift+F10 on the focused map. */
215
+ export type MapContextMenuEvent = {
216
+ /** `[lon, lat]` of the point (the map centre, or the selected feature, from the keyboard). */
217
+ lonLat: [number, number];
218
+ /** The point in map pixels, from the map's top-left corner. */
219
+ pixel: [number, number];
220
+ /** The point in viewport (client) pixels: where to open a menu (`ContextMenu.open(x, y)`). */
221
+ x: number;
222
+ y: number;
223
+ /** The feature under the point (the selected one, from the keyboard): the map's own or a `trussInteractive` layer's. */
224
+ feature?: MapFeatureInfo;
225
+ /** What opened it. */
226
+ source: 'mouse' | 'touch' | 'keyboard';
227
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ruckc/truss-ol",
3
- "version": "1.56.0",
3
+ "version": "1.57.0",
4
4
  "description": "OpenLayers map styled with Truss UI",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -24,7 +24,7 @@
24
24
  },
25
25
  "peerDependencies": {
26
26
  "svelte": "^5.20.0",
27
- "@ruckc/truss-ui": "^1.0.0",
27
+ "@ruckc/truss-ui": "^1.57.0",
28
28
  "ol": "^10.0.0"
29
29
  },
30
30
  "devDependencies": {