@ruckc/truss-ol 1.55.1 → 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/dist/Map.svelte CHANGED
@@ -30,6 +30,23 @@
30
30
  legendRange: (title: string, from: string, to: string) => string;
31
31
  /** Shown when the map could not be created; `reason` is the error message. */
32
32
  loadFailed: (reason: string) => string;
33
+ /** Tooltip of the attribution's show/hide button. The provider credits themselves come from the tile sources and are not translated here. */
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;
33
50
  };
34
51
  const DEFAULTS: MapLabels = {
35
52
  map: 'Map. Arrow keys pan, plus and minus zoom.',
@@ -46,7 +63,21 @@
46
63
  low: 'Low',
47
64
  high: 'High',
48
65
  legendRange: (title, from, to) => `${title}: ${from} to ${to}`,
49
- loadFailed: (reason) => `Map failed to load: ${reason}`
66
+ loadFailed: (reason) => `Map failed to load: ${reason}`,
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]
50
81
  };
51
82
  </script>
52
83
 
@@ -54,11 +85,15 @@
54
85
  import { useLabels } from './labels.js';
55
86
  import { cssvars } from './cssvars.js';
56
87
  import SsrStyle from './SsrStyle.svelte';
57
- import { onMount, type Snippet } from 'svelte';
88
+ import { onMount, tick, untrack, type Snippet } from 'svelte';
58
89
  import { Button, readColorTokens, onThemeChange } from '@ruckc/truss-ui';
59
90
  import 'ol/ol.css';
60
91
  import type OLMap from 'ol/Map.js';
61
- import type { Basemap, FitOptions, FitTarget, MapApi, MapFeatureInfo, MapMarker, MapSelection, MapViewChange, MapViewState } from './types.js';
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';
62
97
  import {
63
98
  DEFAULT_PALETTES, EMPTY_STORE, NATIVE_CLUSTER_MAX, aggregate, drawPie, pieKey, pieStroke, addStat, autoMode, clusterProps, clusterRadius, compactCount, compileCluster, compileStyle, cssGradient, featureTitle,
64
99
  isLight, lonLatExtent, moveMs, newStat, numbersOf, popupEntries, propertyStyle, storeExtent, toStore, validLonLat, weightsOf, withAlpha,
@@ -91,13 +126,29 @@
91
126
  legend = false,
92
127
  selected = $bindable(),
93
128
  extent = $bindable(),
94
- height = 420,
129
+ height,
130
+ variant = 'default',
95
131
  fitOnLoad = true,
132
+ initialView,
133
+ controls,
134
+ fitTarget,
135
+ onfit,
136
+ attribution,
96
137
  popup,
97
138
  toolbar,
98
139
  onselect,
99
140
  onviewchange,
100
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,
101
152
  labels
102
153
  }: {
103
154
  /** [lon, lat] */
@@ -166,10 +217,28 @@
166
217
  selected?: string;
167
218
  /** The visible lon/lat extent `[west, south, east, north]`, updated whenever the map moves. Bindable, read-only output: setting it does nothing. */
168
219
  extent?: [number, number, number, number];
169
- /** Map height: px, or any CSS length. Default 420. */
220
+ /** Map height: px, or any CSS length (`'100%'`, `'60vh'`, `'calc(100dvh - 56px)'`). Default 420, or `'100%'` with `variant="bare"`. */
170
221
  height?: number | string;
171
- /** Fit the view to markers/features/points on first load (once the container has a size). */
222
+ /** `bare`: no border and no corner radius, and (unless `height` says otherwise) the full height of its container, for an edge-to-edge map. */
223
+ variant?: 'default' | 'bare';
224
+ /** Fit the view to the data (`fitTarget`, else markers/features/points) on first load, once the container has a size. It wins over `initialView` when there is data. */
172
225
  fitOnLoad?: boolean;
226
+ /**
227
+ * Where the map starts, applied before anything is reported: `{ center: [lon, lat], zoom }`, or `{ extent: [west, south, east, north], padding?, maxZoom? }`
228
+ * (fitted as soon as the container has a size). Wins over `center` and `zoom`; read once, on mount. A saved view restored here never makes `onviewchange` fire.
229
+ */
230
+ initialView?: MapInitialView;
231
+ /** Which built-in toolbar buttons show: `{ zoom: false }` hides zoom in/out, `{ fit: false }` the fit button. Both show by default; the `toolbar` snippet always does. */
232
+ controls?: MapControls;
233
+ /**
234
+ * What "the data" is for the fit button, `fitOnLoad`, `fitOnDataChange`, `refitOnResize` and `fit()` without an argument: anything `fit()` accepts,
235
+ * or a function returning it (called at each fit; `undefined` means nothing to fit). Default: the markers, GeoJSON, points and `trussInteractive` layers.
236
+ */
237
+ fitTarget?: FitTarget | (() => FitTarget | undefined);
238
+ /** Replaces what the fit button does (for example a fit with your own options). `fitOnLoad` and `fit()` are unaffected. */
239
+ onfit?: () => void;
240
+ /** OpenLayers' attribution: `collapsed` `false` (default: expanded), `true`, or `'auto'` (collapsed while the map is narrower than 640px, measured on the map, not the viewport). */
241
+ attribution?: MapAttribution;
173
242
  /** Fit the view again whenever `markers`, `geojson` or `points` change. Default false. */
174
243
  fitOnDataChange?: boolean;
175
244
  /** Re-measure the map when its container resizes (always), and also refit to the data. Default false. */
@@ -184,11 +253,48 @@
184
253
  featurePopup?: Snippet<[feature: MapFeatureInfo]>;
185
254
  /** Extra controls appended to the toolbar. */
186
255
  toolbar?: Snippet;
256
+ /**
257
+ * A click or the keyboard selected a marker, GeoJSON feature or point (or cleared the selection: `null`). Layers your app adds to `api.map`
258
+ * take no part unless they carry the `trussInteractive: true` property; their features then report the layer's `id` property as `layer`.
259
+ */
187
260
  onselect?: (s: MapSelection | null) => void;
188
- /** Fired when the map has moved (`moveend`) and once after the initial load and fit: the centre `[lon, lat]`, zoom and visible extent `[west, south, east, north]`. Not fired for a move that changed nothing. */
261
+ /**
262
+ * Fired when the map has moved (`moveend`), including the load-time fit of `fitOnLoad` when it moved the view: the centre `[lon, lat]`, zoom and
263
+ * visible extent `[west, south, east, north]`. Not fired for the starting view (`center`/`zoom` or `initialView`) nor for a move that changed nothing.
264
+ */
189
265
  onviewchange?: (v: MapViewChange) => void;
190
- /** Called once the map exists, with the imperative API (`map`, `fit`, `setView`, `getView`, `updateSize`). */
266
+ /** Called once the map exists, with the imperative API (`map`, `fit`, `setView`, `getView`, `updateSize`, `select`, `openPopup`, `closePopup`, `finishDrawing`, `abortDrawing`, `undoLastPoint`). */
191
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;
192
298
  /** Replaces the built-in texts (translation). Missing keys keep the defaults. */
193
299
  labels?: Partial<MapLabels>;
194
300
  } = $props();
@@ -198,7 +304,9 @@
198
304
  let el: HTMLDivElement;
199
305
  let popupEl: HTMLDivElement;
200
306
  let ready = $state(false);
201
- let ctl: { zoomBy(d: number): void; fit(target?: FitTarget, o?: FitOptions): void; setView(v: Partial<Pick<MapViewState, 'center' | 'zoom'>> & { duration?: number }): void; getView(): MapViewState; updateSize(): void } | undefined;
307
+ let ctl: { zoomBy(d: number): void; fit(target?: FitTarget, o?: FitOptions): void; setView(v: Partial<Pick<MapViewState, 'center' | 'zoom'>> & { duration?: number }): void; getView(): MapViewState; updateSize(): void; select: MapApi['select'] } | undefined;
308
+ // the app layer (`trussInteractive`, or picked by `select(layerId, …)`) the selected feature belongs to; undefined for the map's own features
309
+ let selLayer = $state.raw<any>(undefined);
202
310
  let fsel = $state.raw<MapFeatureInfo | null>(null);
203
311
  let tip = $state.raw<MapFeatureInfo | null>(null);
204
312
  let tipEl: HTMLDivElement;
@@ -209,6 +317,8 @@
209
317
  let seenC: [number, number] | undefined;
210
318
  let seenZ: number | undefined;
211
319
  let announce = $state('');
320
+ /** The `selected` value the map itself set last (click, keyboard, `select()`), to tell it from one the consumer set. */
321
+ let mine: string | undefined;
212
322
 
213
323
  /** Fit the view to a lon/lat extent, `{ lon, lat }` points, GeoJSON, or (no argument) everything on the map. */
214
324
  export function fit(target?: FitTarget, options?: FitOptions) { ctl?.fit(target, options); }
@@ -218,11 +328,48 @@
218
328
  export function getView(): MapViewState | undefined { return ctl?.getView(); }
219
329
  /** Re-measure the container (the map does this by itself when its container resizes). */
220
330
  export function updateSize() { ctl?.updateSize(); }
221
- let sync: { limits(): void; markers(): void; geo(): void; points(): void; base(): void; style(): void; select(): void; view(): void } | undefined;
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. */
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(); };
362
+ let sync: { limits(): void; markers(): void; geo(): void; points(): void; base(): void; style(): void; select(): void; view(): void; attribution(): void } | undefined;
222
363
  let failed = $state<string>();
223
364
  let legendInfo = $state.raw<LegendInfo>({});
224
365
 
225
- const sel = $derived(markers.find((m) => m.id === selected));
366
+ const sel = $derived(selLayer ? undefined : markers.find((m) => m.id === selected));
367
+ const cssHeight = $derived.by(() => { const v = height ?? (variant === 'bare' ? '100%' : 420); return typeof v === 'number' ? `${v}px` : v; });
368
+ const showZoom = $derived(controls?.zoom !== false);
369
+ const showFit = $derived(controls?.fit !== false);
370
+ /** Narrower than this (map width, px), `attribution={{ collapsed: 'auto' }}` collapses the credits. */
371
+ const NARROW = 640;
372
+ let root: HTMLDivElement;
226
373
 
227
374
  onMount(() => {
228
375
  let dispose = () => {};
@@ -305,6 +452,8 @@
305
452
  for (const k of cprops) { const st = out[k] = newStat(); for (const m of members) { const v = m.get(k); addStat(st, typeof v === 'number' || (typeof v === 'string' && v.trim() !== '') ? Number(v) : NaN); } }
306
453
  return out;
307
454
  };
455
+ /** An app layer's name for `onselect`, `select()` and `MapFeatureInfo.layer`: its `id` property. */
456
+ const layerIdOf = (l: any): string | undefined => { const v = l.get('id'); return v === undefined || v === null ? undefined : String(v); };
308
457
  const idOf = (p: Props, i: number): string | undefined => {
309
458
  const v = typeof idBy === 'function' ? idBy(p, i) : idBy ? p[idBy] : undefined;
310
459
  return v === undefined || v === null || v === '' ? undefined : String(v);
@@ -326,7 +475,7 @@
326
475
  const pieRing = (r: number) => new Style({ image: new CircleStyle({ radius: r + 6, fill: new Fill({ color: rgba(T.primary, 0.25) }), stroke: new Stroke({ color: T.primary, width: 2.5 }) }) });
327
476
 
328
477
  const markerStyle = (f: any) => {
329
- const on = f.getId() === selected;
478
+ const on = !selLayer && f.getId() === selected;
330
479
  const c = tone(f.get('kind'));
331
480
  const colors: string[] | undefined = f.get('colors');
332
481
  if (colors?.length) {
@@ -349,7 +498,7 @@
349
498
  })
350
499
  ];
351
500
  };
352
- const isSel = (f: any) => selected !== undefined && String(f.getId()) === selected;
501
+ const isSel = (f: any) => !selLayer && selected !== undefined && String(f.getId()) === selected;
353
502
  const zoomOk = () => labelMinZoom === undefined || (view.getZoom() ?? 0) >= labelMinZoom;
354
503
  const labelText = (text: string | undefined, offsetY: number) => text === undefined || declutter || !zoomOk() ? undefined
355
504
  : new Text({ text: String(text), offsetY, font: '600 12px Inter Variable, system-ui, sans-serif', fill: new Fill({ color: T['on-surface'] }), stroke: new Stroke({ color: T.surface, width: 3 }) });
@@ -415,13 +564,24 @@
415
564
  const labelPtLayer = new VectorLayer({ source: ptSrc, style: labelStyle, declutter: true, visible: false, zIndex: 26 });
416
565
 
417
566
  let baseLayers: any[] = [];
567
+ /** `attribution.collapsed`, with `'auto'` resolved against the map's own width (unknown while it has none). */
568
+ const narrow = () => el.clientWidth > 0 && el.clientWidth < NARROW;
569
+ const wantCollapsed = () => { const c = attribution?.collapsed ?? false; return c === 'auto' ? narrow() : c; };
570
+ const attrCtl = new Attribution({ collapsible: true, collapsed: wantCollapsed(), tipLabel: L.attributions });
571
+ const attrEl: HTMLElement = (attrCtl as any).element; // protected in the typings, public in practice (every control has one)
572
+ let wasNarrow = narrow();
573
+ // the starting view: initialView over center/zoom; written back to the bindings so their defaults never move it
574
+ const iv = initialView;
575
+ if (iv?.center) center = [iv.center[0], iv.center[1]];
576
+ if (iv?.zoom !== undefined) zoom = iv.zoom;
418
577
  seenC = [...center]; seenZ = zoom;
419
578
  const view = new View({ center: fromLonLat(center), zoom, minZoom, maxZoom });
579
+ let startExtent = iv?.extent;
420
580
  const map = new OLMap({
421
581
  target: el,
422
582
  view,
423
583
  layers: [heatLayer, geoLayer, ptLayer, markerLayer, labelGeoLayer, labelPtLayer],
424
- controls: [new Attribution({ collapsible: true, collapsed: false }), new ScaleLine({ units: 'metric', minWidth: 64 })],
584
+ controls: [attrCtl, new ScaleLine({ units: 'metric', minWidth: 64 })],
425
585
  keyboardEventTarget: el
426
586
  });
427
587
 
@@ -462,13 +622,21 @@
462
622
  };
463
623
  let lastView = '';
464
624
  /** Tell the consumer where the map is now, unless it is where we last said. */
465
- const emitView = () => {
625
+ const emitView = (quiet = false) => {
466
626
  const v = ctl!.getView() as MapViewChange;
467
627
  const key = `${v.center}|${v.zoom}|${v.extent}`;
468
628
  if (key === lastView) return;
469
629
  lastView = key;
470
630
  extent = v.extent;
471
- onviewchange?.(v);
631
+ if (!quiet) onviewchange?.(v);
632
+ };
633
+ /** The `initialView` extent, once the container has a size: the app's own starting view, so it is recorded without an `onviewchange`. */
634
+ const applyStart = () => {
635
+ if (!startExtent || !el.clientWidth || !el.clientHeight) return;
636
+ const pad = typeof iv!.padding === 'number' ? [iv!.padding, iv!.padding, iv!.padding, iv!.padding] : iv!.padding ?? [0, 0, 0, 0];
637
+ view.fit(transformExtent(startExtent, 'EPSG:4326', 'EPSG:3857'), { padding: pad, maxZoom: iv!.maxZoom ?? view.getMaxZoom(), duration: 0 });
638
+ startExtent = undefined;
639
+ emitView(true);
472
640
  };
473
641
  const refreshView = () => { if (mode === 'heatmap') refreshHeat(); else if (mode === 'cluster' && store.n > NATIVE_CLUSTER_MAX) refreshAgg(); };
474
642
  const heatGradient = () => {
@@ -535,15 +703,20 @@
535
703
  markerLayer.changed(); geoLayer.changed(); ptLayer.changed(); labelGeoLayer.changed(); labelPtLayer.changed(); this.base();
536
704
  },
537
705
  limits() { view.setMinZoom(minZoom); view.setMaxZoom(maxZoom); },
706
+ attribution() {
707
+ attrCtl.setCollapsed(wantCollapsed());
708
+ (attrEl.querySelector('button') as HTMLButtonElement).title = L.attributions;
709
+ },
538
710
  select() {
539
711
  markerLayer.changed(); geoLayer.changed(); ptLayer.changed();
540
- const m = markers.find((x) => x.id === selected);
541
- const f: any = m || selected === undefined ? undefined : geoSrc.getFeatureById(selected) ?? ptSrc.getFeatureById(selected) ?? aggSrc.getFeatureById(selected);
542
- if (f) {
543
- const g = f.getGeometry();
712
+ const m = selLayer ? undefined : markers.find((x) => x.id === selected);
713
+ const f: any = m || selected === undefined ? undefined : selLayer ? selLayer.getSource()?.getFeatureById(selected) : geoSrc.getFeatureById(selected) ?? ptSrc.getFeatureById(selected) ?? aggSrc.getFeatureById(selected);
714
+ const g = f?.getGeometry();
715
+ if (g) {
544
716
  const pos = clicked && clicked.id === selected ? clicked.at : g.getType() === 'Point' ? g.getCoordinates() : getCenter(g.getExtent());
545
717
  const { geometry, ...properties } = f.getProperties();
546
- fsel = { id: selected!, properties, geometryType: g.getType(), lonLat: toLonLat(pos) as [number, number] };
718
+ const layer = selLayer ? layerIdOf(selLayer) : undefined;
719
+ fsel = { id: selected!, properties, geometryType: g.getType(), lonLat: toLonLat(pos) as [number, number], ...(layer !== undefined && { layer }) };
547
720
  announce = featureTitle(properties);
548
721
  overlay.setPosition(pos);
549
722
  } else {
@@ -564,8 +737,12 @@
564
737
  zoomBy: (d) => view.animate({ zoom: Math.min(Math.max((view.getZoom() ?? 0) + d, view.getMinZoom()), view.getMaxZoom()), duration: moveMs(200) }),
565
738
  fit: (target, o = {}) => {
566
739
  let ext = createEmpty();
740
+ if (target === undefined && fitTarget !== undefined) {
741
+ target = typeof fitTarget === 'function' ? fitTarget() : fitTarget;
742
+ if (target === undefined) return;
743
+ }
567
744
  if (target === undefined) {
568
- for (const src of [markerSrc, geoSrc]) extend(ext, src.getExtent()!);
745
+ for (const src of [markerSrc, geoSrc, ...map.getAllLayers().filter((l: any) => !own(l) && interactive(l)).map((l: any) => l.getSource())]) extend(ext, src.getExtent()!);
569
746
  const pe = storeExtent(store);
570
747
  if (pe) extend(ext, pe);
571
748
  } else {
@@ -586,12 +763,27 @@
586
763
  zoom: view.getZoom() ?? 0,
587
764
  extent: transformExtent(view.calculateExtent(map.getSize()), 'EPSG:3857', 'EPSG:4326') as [number, number, number, number]
588
765
  }),
589
- updateSize: () => map.updateSize()
766
+ updateSize: () => map.updateSize(),
767
+ select: (layer, id) => {
768
+ if (id === null || id === undefined) { x303?.selChange(); clicked = undefined; selLayer = undefined; selected = mine = undefined; sync!.select(); return true; }
769
+ const l: any = layer === null ? undefined : map.getAllLayers().find((x: any) => layerIdOf(x) === layer && typeof x.getSource()?.getFeatureById === 'function');
770
+ if (layer !== null && !l) return false;
771
+ const k = String(id);
772
+ if (!(l ? l.getSource().getFeatureById(k) : markerSrc.getFeatureById(k) ?? geoSrc.getFeatureById(k) ?? ptSrc.getFeatureById(k) ?? aggSrc.getFeatureById(k))) return false;
773
+ x303?.selChange();
774
+ clicked = undefined; selLayer = l; selected = mine = k; sync!.select();
775
+ return true;
776
+ }
590
777
  };
591
778
 
592
779
  // ---- user interaction
593
- /** Only data layers take part in hit tests: not the basemap (graticule lines are features) nor the heatmap. */
594
- const hittable = (l: any) => l !== heatLayer && l !== labelGeoLayer && l !== labelPtLayer && !baseLayers.includes(l);
780
+ /**
781
+ * Only the map's own data layers take part in hit tests (not the basemap, the heatmap nor the label layers), plus the layers your
782
+ * app added with the `trussInteractive: true` property: clicks, hover, the tooltip and keyboard selection never touch any other layer.
783
+ */
784
+ const own = (l: any) => l === markerLayer || l === geoLayer || l === ptLayer;
785
+ const interactive = (l: any) => l.get('trussInteractive') === true && l.getVisible() && typeof l.getSource?.()?.getFeatures === 'function';
786
+ const hittable = (l: any) => own(l) || interactive(l);
595
787
  map.on('moveend', () => {
596
788
  const c = toLonLat(view.getCenter()!);
597
789
  center = [Number(c[0].toFixed(5)), Number(c[1].toFixed(5))];
@@ -600,35 +792,47 @@
600
792
  refreshView();
601
793
  emitView();
602
794
  });
603
- /** Select a feature (marker, GeoJSON feature or point) as a click or the keyboard would; `at` anchors the popup for shapes. */
604
- const choose = (f: any, at?: number[]) => {
605
- const id = String(f.getId());
795
+ const clear = () => { x303?.selChange(); selLayer = undefined; selected = mine = undefined; sync!.select(); onselect?.(null); };
796
+ /**
797
+ * Select a feature (marker, GeoJSON feature, point, or a feature of a `trussInteractive` layer `l`) as a click or the keyboard would;
798
+ * `at` anchors the popup for shapes. A feature without an id, or one that cannot be found again, clears the selection instead.
799
+ */
800
+ const choose = (f: any, l: any, at?: number[]) => {
801
+ const raw = f.getId();
802
+ if (raw === undefined) { clear(); return; }
803
+ x303?.selChange();
804
+ selLayer = own(l) ? undefined : l;
805
+ const id = String(raw);
606
806
  clicked = at ? { id, at } : undefined;
607
- selected = id;
807
+ selected = mine = id;
608
808
  sync!.select();
609
- if (markerSrc.getFeatureById(id)) onselect?.({ type: 'marker', marker: markers.find((x) => x.id === id)! });
610
- else onselect?.({ type: 'feature', id: f.getId(), properties: fsel!.properties, geometryType: fsel!.geometryType });
809
+ if (l === markerLayer && sel) onselect?.({ type: 'marker', marker: sel });
810
+ else if (fsel) onselect?.({ type: 'feature', id: raw, properties: fsel.properties, geometryType: fsel.geometryType, ...(fsel.layer !== undefined && { layer: fsel.layer }) });
811
+ else clear();
611
812
  };
612
- const clear = () => { selected = undefined; sync!.select(); onselect?.(null); };
613
- /** Features shown inside the current view, in a stable order, for keyboard selection. */
813
+ /** Features shown inside the current view, in a stable order, for keyboard selection: the map's own, then the `trussInteractive` layers'. */
614
814
  const visible = () => {
615
815
  const ext = view.calculateExtent(map.getSize());
616
- const out: any[] = [];
617
- for (const src of [markerSrc, geoSrc, ptLayer.getSource()!]) for (const f of src.getFeatures() as any[]) if (!f.get('_cluster') && intersects(f.getGeometry().getExtent(), ext)) out.push(f);
816
+ const out: { f: any; l: any }[] = [];
817
+ const layers = [[markerLayer, markerSrc], [geoLayer, geoSrc], [ptLayer, ptLayer.getSource()!], ...map.getAllLayers().filter((l: any) => !own(l) && interactive(l)).map((l: any) => [l, l.getSource()])];
818
+ for (const [l, src] of layers) for (const f of src.getFeatures() as any[]) if (!f.get('_cluster') && f.getId() !== undefined && f.getGeometry() && intersects(f.getGeometry().getExtent(), ext)) out.push({ f, l });
618
819
  return out;
619
820
  };
620
821
  const cycle = (dir: number) => {
621
822
  const list = visible();
622
823
  if (!list.length) return;
623
- const at = list.findIndex((f) => String(f.getId()) === selected);
624
- choose(list[at < 0 ? (dir > 0 ? 0 : list.length - 1) : (at + dir + list.length) % list.length]);
824
+ const at = list.findIndex((x) => String(x.f.getId()) === selected && (own(x.l) ? !selLayer : x.l === selLayer));
825
+ const next = list[at < 0 ? (dir > 0 ? 0 : list.length - 1) : (at + dir + list.length) % list.length];
826
+ choose(next.f, next.l);
625
827
  };
626
828
  const onkey = (e: KeyboardEvent) => {
829
+ if (key303(e)) return;
627
830
  if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); cycle(e.shiftKey ? -1 : 1); }
628
831
  else if (e.key === 'Escape') { hideTip(); if (selected !== undefined) clear(); }
629
832
  };
630
833
  el.addEventListener('keydown', onkey);
631
834
  map.on('singleclick', (e) => {
835
+ if (click303()) return;
632
836
  const hit = map.forEachFeatureAtPixel(e.pixel, (f, l) => ({ f, l }), { hitTolerance: 6, layerFilter: hittable });
633
837
  const cl = hit?.f.get('_cluster');
634
838
  if (cl) {
@@ -636,7 +840,7 @@
636
840
  const [x0, y0, x1, y1] = cl.bbox;
637
841
  if (x1 - x0 < 1 && y1 - y0 < 1) view.animate({ center: [x0, y0], zoom: Math.min((view.getZoom() ?? 0) + 2, view.getMaxZoom()), duration: moveMs(300) });
638
842
  else view.fit(cl.bbox, { padding: [60, 60, 60, 60], duration: moveMs(300), maxZoom: view.getMaxZoom() });
639
- } else if (hit) choose(hit.f, e.coordinate);
843
+ } else if (hit) choose(hit.f, hit.l, e.coordinate);
640
844
  else clear();
641
845
  });
642
846
  map.on('pointermove', (e) => {
@@ -657,8 +861,186 @@
657
861
  el.addEventListener('pointerleave', hideTip);
658
862
  map.on('movestart', hideTip);
659
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
+
660
1042
  // ---- follow theme (data-theme or data-truss-theme on the map or any ancestor, or the OS preference)
661
- const restyle = () => sync?.style();
1043
+ const restyle = () => { sync?.style(); restyle303(); };
662
1044
  const unwatch = onThemeChange(el, restyle);
663
1045
 
664
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
@@ -666,20 +1048,33 @@
666
1048
  const ro = new ResizeObserver(() => {
667
1049
  map.updateSize();
668
1050
  if (!el.clientWidth || !el.clientHeight) return;
1051
+ // 'auto' follows the map's width, but only when it crosses the breakpoint: a reader who opened the credits keeps them open
1052
+ const n = narrow();
1053
+ if (n !== wasNarrow) { wasNarrow = n; if (attribution?.collapsed === 'auto') attrCtl.setCollapsed(n); }
1054
+ applyStart();
669
1055
  if (fitPending || refitOnResize) { fitPending = false; ctl!.fit(undefined, { duration: 0 }); }
670
1056
  });
671
1057
  ro.observe(el);
1058
+ // the scale line stacks above the attribution, however many lines the credits wrap to (or none, when the source has none)
1059
+ const attrRo = new ResizeObserver(() => root.style.setProperty('--trm-attribution-h', `${attrEl.offsetHeight}px`));
1060
+ attrRo.observe(attrEl);
672
1061
 
673
1062
  sync.base(); sync.markers(); sync.geo(); sync.points();
1063
+ applyStart();
1064
+ emitView(true); // the starting view: `bind:extent` gets it, `onviewchange` only hears of a move
674
1065
  if (fitPending && el.clientWidth && el.clientHeight) { fitPending = false; ctl.fit(undefined, { duration: 0 }); }
675
1066
  ready = true;
676
1067
  emitView();
677
- onready?.({ map, fit: ctl.fit, setView: ctl.setView, getView: ctl.getView, updateSize: ctl.updateSize });
678
-
1068
+ // set before onready runs: an app callback that throws must not leave the observers behind
679
1069
  dispose = () => {
680
- unwatch(); el.removeEventListener('keydown', onkey); ro.disconnect();
1070
+ unwatch(); el.removeEventListener('keydown', onkey); ro.disconnect(); attrRo.disconnect(); dispose303();
681
1071
  map.setTarget(undefined);
682
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
+ });
683
1078
  })().catch((e) => (failed = e instanceof Error ? e.message : String(e)));
684
1079
 
685
1080
  return () => { dead = true; dispose(); };
@@ -699,16 +1094,25 @@
699
1094
  $effect(() => { minZoom; maxZoom; if (ready) sync?.limits(); });
700
1095
  $effect(() => { style; if (ready) sync?.style(); });
701
1096
  $effect(() => { basemap; if (ready) sync?.base(); });
702
- $effect(() => { selected; if (ready) sync?.select(); });
1097
+ // a `selected` the consumer set (not one a click, the keyboard or `select()` set) names one of the map's own features
1098
+ $effect(() => { if (selected !== mine) selLayer = undefined; if (ready) sync?.select(); });
703
1099
  $effect(() => { center; zoom; if (ready) sync?.view(); });
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(); } }); });
704
1108
  </script>
705
1109
 
706
- <SsrStyle {uid} rules={{ '': `height:${typeof height === 'number' ? `${height}px` : height}` }} />
707
- <div class="trm" data-sv={uid} {@attach cssvars(() => ({ 'height': typeof height === 'number' ? `${height}px` : height }))}>
1110
+ <SsrStyle {uid} rules={{ '': `height:${cssHeight}` }} />
1111
+ <div class="trm" class:bare={variant === 'bare'} class:drawing={sketchMode} data-sv={uid} bind:this={root} {@attach cssvars(() => ({ 'height': cssHeight }))}>
708
1112
  <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
709
1113
  <div class="map" bind:this={el} tabindex="0" role="application" aria-label={L.map}></div>
710
1114
 
711
- <div class="popup" bind:this={popupEl} hidden={!sel && !fsel}>
1115
+ <div class="popup" bind:this={popupEl} hidden={!!app || hush || (!sel && !fsel)}>
712
1116
  {#if sel}
713
1117
  <div class="card" role="dialog" aria-label={sel.label ?? L.location}>
714
1118
  <button type="button" class="x" aria-label={L.close} onclick={() => { selected = undefined; onselect?.(null); }}>×</button>
@@ -730,17 +1134,33 @@
730
1134
  </div>
731
1135
  {/if}
732
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>
733
1148
  <div class="tip" bind:this={tipEl} id={tipId} role="tooltip" hidden={!tip || (!featureTooltip && !tipText)}>
734
1149
  {#if tip}{#if featureTooltip}{@render featureTooltip(tip)}{:else}{tipText}{/if}{/if}
735
1150
  </div>
736
1151
  <div class="sr" aria-live="polite">{announce}</div>
737
1152
 
738
- <div class="controls" role="toolbar" aria-label={L.controls}>
739
- <Button variant="minimal" intent="neutral" size="sm" icon="plus" aria-label={L.zoomIn} onclick={() => ctl?.zoomBy(1)} />
740
- <Button variant="minimal" intent="neutral" size="sm" icon="minus" aria-label={L.zoomOut} onclick={() => ctl?.zoomBy(-1)} />
741
- <Button variant="minimal" intent="neutral" size="sm" icon="expand" aria-label={L.fitToData} onclick={() => ctl?.fit()} />
742
- {#if toolbar}{@render toolbar()}{/if}
743
- </div>
1153
+ {#if showZoom || showFit || locOpts || toolbar}
1154
+ <div class="controls" role="toolbar" aria-label={L.controls}>
1155
+ {#if showZoom}
1156
+ <Button variant="minimal" intent="neutral" size="sm" icon="plus" aria-label={L.zoomIn} onclick={() => ctl?.zoomBy(1)} />
1157
+ <Button variant="minimal" intent="neutral" size="sm" icon="minus" aria-label={L.zoomOut} onclick={() => ctl?.zoomBy(-1)} />
1158
+ {/if}
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}
1161
+ {#if toolbar}{@render toolbar()}{/if}
1162
+ </div>
1163
+ {/if}
744
1164
  {#if legend && (legendInfo.size || legendInfo.color || legendInfo.clusterSize || legendInfo.clusterColor || legendInfo.heatmap)}
745
1165
  <div class="legend" role="group" aria-label={L.legend}>
746
1166
  {#each [legendInfo.size, legendInfo.clusterSize] as lg, i (i)}
@@ -766,11 +1186,15 @@
766
1186
  {/each}
767
1187
  </div>
768
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}
769
1192
  {#if failed}<div class="err" role="alert">{L.loadFailed(failed)}</div>{/if}
770
1193
  </div>
771
1194
 
772
1195
  <style>
773
1196
  .trm { position: relative; overflow: hidden; border: 1px solid var(--tr-outline-variant); border-radius: var(--tr-radius-md); background: var(--tr-surface-container); }
1197
+ .trm.bare { border: 0; border-radius: 0; }
774
1198
  .map { position: absolute; inset: 0; outline: none; }
775
1199
  .map:focus-visible { box-shadow: inset 0 0 0 2px var(--tr-primary); }
776
1200
  /* the buttons sit at least 24px apart centre to centre (WCAG 2.5.8 spacing): 2px apart, 4px once compact makes them 20px (#292) */
@@ -800,6 +1224,12 @@
800
1224
  .lcat { list-style: none; margin: 4px 0 0; padding: 0; display: grid; gap: 2px; }
801
1225
  .lcat li { display: flex; align-items: center; gap: 6px; }
802
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); }
803
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); }
804
1234
 
805
1235
  /* Dark mode: tint raster tiles to the theme */
@@ -807,12 +1237,21 @@
807
1237
  @media (prefers-color-scheme: dark) {
808
1238
  :global(:root:not([data-theme='light']) .tr-basemap) { filter: invert(1) hue-rotate(180deg) brightness(0.92) contrast(0.9) saturate(0.7); }
809
1239
  }
810
- /* Restyle OpenLayers' built-in controls with design tokens */
811
- :global(.trm .ol-attribution) { right: 8px; bottom: 8px; max-width: 70%; background: var(--tr-surface-container-highest); border: 1px solid var(--tr-outline-variant); border-radius: var(--tr-radius-pill); font: var(--tr-text-xs) var(--tr-font-sans); color: var(--tr-on-surface-variant); }
812
- :global(.trm .ol-attribution ul) { margin: 0; padding: 2px 10px; color: var(--tr-on-surface-variant); text-shadow: none; }
813
- :global(.trm .ol-attribution a) { color: var(--tr-primary-text, var(--tr-primary)); }
814
- :global(.trm .ol-attribution button) { background: none; color: var(--tr-on-surface-variant); }
815
- :global(.trm .ol-attribution button:hover) { background: var(--tr-surface-container-high); }
816
- :global(.trm .ol-scale-line) { left: auto; right: 8px; bottom: 36px; background: var(--tr-surface-container-highest); border: 1px solid var(--tr-outline-variant); border-radius: var(--tr-radius-pill); padding: 2px 8px; }
1240
+ /*
1241
+ * Restyle OpenLayers' built-in controls with design tokens. ol.css loads after these rules, and some of its selectors weigh as much as
1242
+ * `.trm .ol-attribution` (0,2,0): `.ol-attribution:not(.ol-collapsed)` (a translucent white background, unreadable under the dark text
1243
+ * tokens, #300), `.ol-attribution.ol-uncollapsible` (position, radius) and `.ol-control button:hover/:focus` (0,2,1: colour, outline).
1244
+ * So every attribution rule names `.ol-control` too, (0,3,0) and up, and wins whatever the load order. The scale line's own rules
1245
+ * (`.ol-scale-line`, `.ol-scale-line-inner`, 0,1,0) never tie with `.trm .ol-scale-line` (0,2,0).
1246
+ */
1247
+ :global(.trm .ol-attribution.ol-control) { right: 8px; bottom: 8px; max-width: 70%; background: var(--tr-surface-container-highest); border: 1px solid var(--tr-outline-variant); border-radius: var(--tr-radius-pill); font: var(--tr-text-xs) var(--tr-font-sans); color: var(--tr-on-surface-variant); }
1248
+ :global(.trm .ol-attribution.ol-control ul) { margin: 0; padding: 2px 10px; color: var(--tr-on-surface-variant); text-shadow: none; }
1249
+ :global(.trm .ol-attribution.ol-control a) { color: var(--tr-primary-text, var(--tr-primary)); }
1250
+ :global(.trm .ol-attribution.ol-control button) { background: none; color: var(--tr-on-surface-variant); }
1251
+ :global(.trm .ol-attribution.ol-control button:hover) { background: var(--tr-surface-container-high); color: var(--tr-on-surface); outline: none; }
1252
+ :global(.trm .ol-attribution.ol-control button:focus) { outline: none; }
1253
+ :global(.trm .ol-attribution.ol-control button:focus-visible) { box-shadow: var(--tr-focus-ring); }
1254
+ /* above the attribution's measured height (--trm-attribution-h, set from a ResizeObserver), never lower than the classic 36px */
1255
+ :global(.trm .ol-scale-line) { left: auto; right: 8px; bottom: max(36px, calc(var(--trm-attribution-h, 0px) + 14px)); background: var(--tr-surface-container-highest); border: 1px solid var(--tr-outline-variant); border-radius: var(--tr-radius-pill); padding: 2px 8px; }
817
1256
  :global(.trm .ol-scale-line-inner) { border-color: var(--tr-on-surface-variant); color: var(--tr-on-surface-variant); font: var(--tr-text-xs) var(--tr-font-sans); }
818
1257
  </style>