@ruckc/truss-ol 1.56.0 → 1.58.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
@@ -32,6 +32,26 @@
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;
50
+ // #302
51
+ /** Accessible name and tooltip of the basemap switcher. */
52
+ basemap: string;
53
+ /** The switcher's name for a `basemaps` entry without a `label`, by its `id` (the `esriBasemaps` presets, `osm`, `none`; any other id as itself). */
54
+ basemapName: (id: string) => string;
35
55
  };
36
56
  const DEFAULTS: MapLabels = {
37
57
  map: 'Map. Arrow keys pan, plus and minus zoom.',
@@ -49,7 +69,22 @@
49
69
  high: 'High',
50
70
  legendRange: (title, from, to) => `${title}: ${from} to ${to}`,
51
71
  loadFailed: (reason) => `Map failed to load: ${reason}`,
52
- attributions: 'Attributions'
72
+ attributions: 'Attributions',
73
+ details: 'Details',
74
+ locate: 'Show my location',
75
+ located: (accuracy) => `Showing your location, accurate to about ${Math.round(accuracy)} metres`,
76
+ locateDenied: 'Location access was denied. Allow it in the browser to show where you are.',
77
+ locateUnavailable: 'Your location could not be found.',
78
+ locateUnsupported: 'This browser cannot share its location.',
79
+ drawing: (mode) => ({
80
+ Point: 'Drawing a point: click the map, or press Enter to place it at the centre. Arrow keys pan.',
81
+ 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.',
82
+ 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.',
83
+ modify: 'Editing shapes: drag a vertex to move it, or drag an edge to add one.',
84
+ move: 'Moving features: drag a feature to move it.'
85
+ })[mode],
86
+ basemap: 'Basemap',
87
+ basemapName: (id) => ({ 'esri-imagery': 'Imagery', 'esri-streets': 'Streets', 'esri-topo': 'Topographic', 'esri-hybrid': 'Imagery with labels', osm: 'OpenStreetMap', none: 'None' })[id] ?? id
53
88
  };
54
89
  </script>
55
90
 
@@ -57,14 +92,22 @@
57
92
  import { useLabels } from './labels.js';
58
93
  import { cssvars } from './cssvars.js';
59
94
  import SsrStyle from './SsrStyle.svelte';
60
- import { onMount, type Snippet } from 'svelte';
61
- import { Button, readColorTokens, onThemeChange } from '@ruckc/truss-ui';
95
+ import { onMount, tick, untrack, type Snippet } from 'svelte';
96
+ import { Button, MenuButton, readColorTokens, onThemeChange } from '@ruckc/truss-ui';
62
97
  import 'ol/ol.css';
63
98
  import type OLMap from 'ol/Map.js';
99
+ // #302: layers, basemap stacks and the switcher
100
+ import type { LayerManager } from './layers-ol.js';
101
+ import type { MapLayer, BasemapOption } from './types.js';
102
+ import { basemapTiles, pickBasemap } from './basemaps.js';
64
103
  import type { Basemap, FitOptions, FitTarget, MapApi, MapAttribution, MapControls, MapFeatureInfo, MapInitialView, MapMarker, MapSelection, MapViewChange, MapViewState } from './types.js';
104
+ import type { MapContextMenuEvent, MapDrawEnd, MapDrawMode, MapEditEnd, MapLocateError, MapLocation, MapPopupOptions } from './types.js';
105
+ import { createEditor, isDrawMode } from './edit.js';
106
+ import { locateOptions, watchLocation } from './locate.js';
107
+ import { wireContextMenu } from './contextmenu.js';
65
108
  import {
66
109
  DEFAULT_PALETTES, EMPTY_STORE, NATIVE_CLUSTER_MAX, aggregate, drawPie, pieKey, pieStroke, addStat, autoMode, clusterProps, clusterRadius, compactCount, compileCluster, compileStyle, cssGradient, featureTitle,
67
- isLight, lonLatExtent, moveMs, newStat, numbersOf, popupEntries, propertyStyle, storeExtent, toStore, validLonLat, weightsOf, withAlpha,
110
+ isLight, lonLatExtent, moveMs, newStat, numbersOf, popupEntries, propertyStyle, drawableSymbol, storeExtent, toStore, validLonLat, weightsOf, withAlpha,
68
111
  type ClusterInfo, type ClusterStyle, type Compiled, type CompiledCluster, type FeatureStyle, type HeatmapOptions, type LegendInfo, type MapStyle, type Palettes, type PointStore, type PointsInput, type PointsMode, type Props
69
112
  } from './util.js';
70
113
 
@@ -107,11 +150,30 @@
107
150
  onselect,
108
151
  onviewchange,
109
152
  onready,
110
- labels
153
+ // #303: draw and edit, locate, context menu
154
+ drawMode = null,
155
+ editLayer,
156
+ snap = true,
157
+ ondrawend,
158
+ onmodifyend,
159
+ onmoveend,
160
+ onlocate,
161
+ onlocateerror,
162
+ oncontextmenu,
163
+ labels,
164
+ // #302
165
+ layers,
166
+ basemaps,
167
+ basemapId = $bindable(),
168
+ onbasemapchange
111
169
  }: {
112
170
  /** [lon, lat] */
113
171
  center?: [number, number];
114
172
  zoom?: number;
173
+ /**
174
+ * `'osm'` (default), `'none'` (a themed graticule), `{ url, attribution?, maxZoom?, opacity?, themed? }` (XYZ tiles), `{ osm: true, ... }`, or a stack
175
+ * `{ layers: [...], themed? }` drawn bottom to top (imagery, then label overlays). Only OSM tiles are `themed` (inverted in dark mode) by default.
176
+ */
115
177
  basemap?: Basemap;
116
178
  markers?: MapMarker[];
117
179
  /** GeoJSON FeatureCollection/Feature. Optional `properties.kind` picks the intent color. */
@@ -221,10 +283,52 @@
221
283
  * visible extent `[west, south, east, north]`. Not fired for the starting view (`center`/`zoom` or `initialView`) nor for a move that changed nothing.
222
284
  */
223
285
  onviewchange?: (v: MapViewChange) => void;
224
- /** Called once the map exists, with the imperative API (`map`, `fit`, `setView`, `getView`, `updateSize`, `select`). */
286
+ /** Called once the map exists, with the imperative API (`map`, `fit`, `setView`, `getView`, `updateSize`, `select`, `openPopup`, `closePopup`, `finishDrawing`, `abortDrawing`, `undoLastPoint`). */
225
287
  onready?: (api: MapApi) => void;
288
+ // ---- #303
289
+ /**
290
+ * Draw or edit (`null`, the default, does neither): `'Point'`, `'LineString'` or `'Polygon'` draws a new feature (`ondrawend`), `'modify'` drags
291
+ * vertices of existing ones (`onmodifyend`), `'move'` drags whole features (`onmoveend`). The target is `editLayer`, else the map's own `geojson`.
292
+ * While drawing, clicks do not select, and the focused map takes Space (add a vertex at the centre), Enter (finish), Backspace and Escape.
293
+ */
294
+ drawMode?: MapDrawMode | null;
295
+ /**
296
+ * The vector layer `drawMode` works on, by its `id` property: a layer your app added to `api.map` (`properties: { id: 'places' }`).
297
+ * 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
298
+ * reported (add it to `geojson`). A layer that is not on the map yet is waited for.
299
+ */
300
+ editLayer?: string;
301
+ /** Snap the pointer to the vertices and edges of the features being edited. Default true. */
302
+ snap?: boolean;
303
+ /** A point, line or polygon was drawn: its GeoJSON (lon/lat) and the OpenLayers feature. */
304
+ ondrawend?: (e: MapDrawEnd) => void;
305
+ /** Vertices were dragged (`drawMode: 'modify'`): the changed features with their new geometry. */
306
+ onmodifyend?: (e: MapEditEnd) => void;
307
+ /** Features were dragged (`drawMode: 'move'`). */
308
+ onmoveend?: (e: MapEditEnd) => void;
309
+ /** The locate control (`controls.locate`) has a position: on the first fix and every update while it is on. */
310
+ onlocate?: (l: MapLocation) => void;
311
+ /** The locate control failed: permission denied, no position, a timeout, or no Geolocation API. The map shows `message` too. */
312
+ onlocateerror?: (e: MapLocateError) => void;
313
+ /**
314
+ * 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
315
+ * (`lonLat`, map `pixel`, viewport `x`/`y`) and the feature there. Setting it suppresses the browser's own menu on the map.
316
+ */
317
+ oncontextmenu?: (e: MapContextMenuEvent) => void;
226
318
  /** Replaces the built-in texts (translation). Missing keys keep the defaults. */
227
319
  labels?: Partial<MapLabels>;
320
+ /**
321
+ * Data layers, each an OpenLayers vector layer the Map manages: `{ id, geojson | source | loader, style?, visible?, zIndex?, interactive?, label?, opacity? }`.
322
+ * Matched by `id`; only what changed is applied. Interactive layers (the default) take part in selection, which reports their `id` as `layer`.
323
+ * Pass a plain array (or `$state.raw`), as for `geojson`.
324
+ */
325
+ layers?: MapLayer[];
326
+ /** Basemaps to choose from (`{ id, label?, ...basemap }`, e.g. `Object.values(esriBasemaps)`). With two or more, the toolbar shows a switcher (`controls.basemap`). Wins over `basemap`. */
327
+ basemaps?: BasemapOption[];
328
+ /** The `id` of the `basemaps` entry shown; bindable. Unset or unknown, the first entry shows. */
329
+ basemapId?: string;
330
+ /** The switcher picked a basemap (to remember it, say). */
331
+ onbasemapchange?: (id: string) => void;
228
332
  } = $props();
229
333
 
230
334
  const L = useLabels('Map', DEFAULTS, () => labels);
@@ -258,7 +362,40 @@
258
362
  export function updateSize() { ctl?.updateSize(); }
259
363
  /** 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
364
  export function select(layer: string | null, id: string | number | null | undefined): boolean { return ctl?.select(layer, id) ?? false; }
261
- let sync: { limits(): void; markers(): void; geo(): void; points(): void; base(): void; style(): void; select(): void; view(): void; attribution(): void } | undefined;
365
+
366
+ // ---- #303: the app popup, drawing and editing, the locate control, the context menu
367
+ let appEl: HTMLDivElement;
368
+ /** The popup `openPopup` opened. While it shows it takes the selection popup's place (one popup at a time). */
369
+ let app = $state.raw<MapPopupOptions | null>(null);
370
+ /** The selection popup stays closed after an app popup replaced it, until the selection changes. */
371
+ let hush = $state(false);
372
+ /** A locate error, shown on the map until dismissed or the next try. */
373
+ let notice = $state<string>();
374
+ /** The locate control is on (watching the position). */
375
+ let tracking = $state(false);
376
+ let x303: {
377
+ open(at: [number, number], o: MapPopupOptions): void; close(): void; selChange(): void;
378
+ finish(): void; abort(): void; undo(): void; edit(): void; ctx(): void; pressLocate(): void; stopLocate(): void;
379
+ } | undefined;
380
+ /** Open the map's popup at `[lon, lat]` with your content (a snippet or an element). It replaces the selection popup. */
381
+ export function openPopup(lonLat: [number, number], options: MapPopupOptions) { x303?.open(lonLat, options); }
382
+ /** Close the popup `openPopup` opened. */
383
+ export function closePopup() { x303?.close(); }
384
+ /** Finish the line or polygon being drawn (Enter). */
385
+ export function finishDrawing() { x303?.finish(); }
386
+ /** Drop the sketch being drawn (Escape). */
387
+ export function abortDrawing() { x303?.abort(); }
388
+ /** Remove the last vertex of the sketch (Backspace). */
389
+ export function undoLastPoint() { x303?.undo(); }
390
+ const locOpts = $derived(locateOptions(controls?.locate));
391
+ const sketchMode = $derived(isDrawMode(drawMode));
392
+ /** Moves an element the app rendered into the popup, and detaches it again when the popup closes. */
393
+ const adopt = (content: HTMLElement) => (node: HTMLElement) => { node.append(content); return () => content.remove(); };
394
+ let sync: { limits(): void; markers(): void; geo(): void; points(): void; base(): void; layers(): void; style(): void; select(): void; view(): void; attribution(): void } | undefined;
395
+ /** The OpenLayers vector layer of the `layers` entry `id`. */
396
+ export function layer(id: string) { return layerMgr?.layer(id); }
397
+ /** Load a `loader` layer again now. */
398
+ export function reloadLayer(id: string) { layerMgr?.reload(id); }
262
399
  let failed = $state<string>();
263
400
  let legendInfo = $state.raw<LegendInfo>({});
264
401
 
@@ -266,6 +403,11 @@
266
403
  const cssHeight = $derived.by(() => { const v = height ?? (variant === 'bare' ? '100%' : 420); return typeof v === 'number' ? `${v}px` : v; });
267
404
  const showZoom = $derived(controls?.zoom !== false);
268
405
  const showFit = $derived(controls?.fit !== false);
406
+ // #302: the basemap shown (a `basemaps` entry wins over `basemap`) and the switcher
407
+ const activeBasemap = $derived(pickBasemap(basemaps, basemapId));
408
+ const showBasemap = $derived(controls?.basemap !== false && (basemaps?.length ?? 0) > 1);
409
+ const basemapItems = $derived((basemaps ?? []).map((b) => ({ label: b.label ?? L.basemapName(b.id), checked: b.id === activeBasemap?.id, onselect: () => { basemapId = b.id; onbasemapchange?.(b.id); } })));
410
+ let layerMgr: LayerManager | undefined;
269
411
  /** Narrower than this (map width, px), `attribution={{ collapsed: 'auto' }}` collapses the credits. */
270
412
  const NARROW = 640;
271
413
  let root: HTMLDivElement;
@@ -279,12 +421,14 @@
279
421
  { default: OLMap }, { default: View }, { default: TileLayer }, { default: VectorLayer }, { default: VectorSource },
280
422
  { default: OSM }, { default: XYZ }, { default: Overlay }, { default: Feature }, { default: Point }, { default: GeoJSON },
281
423
  { Style, Circle: CircleStyle, Fill, Stroke, Text, Icon }, { fromLonLat, toLonLat, transformExtent }, { default: Attribution }, { default: ScaleLine },
282
- { default: Graticule }, { createEmpty, extend, isEmpty, boundingExtent, getCenter, intersects }, { default: Cluster }, { default: Heatmap }
424
+ { default: Graticule }, { createEmpty, extend, isEmpty, boundingExtent, getCenter, intersects }, { default: Cluster }, { default: Heatmap },
425
+ { createOlStyle }, { LayerManager }
283
426
  ] = await Promise.all([
284
427
  import('ol/Map.js'), import('ol/View.js'), import('ol/layer/Tile.js'), import('ol/layer/Vector.js'), import('ol/source/Vector.js'),
285
428
  import('ol/source/OSM.js'), import('ol/source/XYZ.js'), import('ol/Overlay.js'), import('ol/Feature.js'), import('ol/geom/Point.js'), import('ol/format/GeoJSON.js'),
286
429
  import('ol/style.js'), import('ol/proj.js'), import('ol/control/Attribution.js'), import('ol/control/ScaleLine.js'),
287
- import('ol/layer/Graticule.js'), import('ol/extent.js'), import('ol/source/Cluster.js'), import('ol/layer/Heatmap.js')
430
+ import('ol/layer/Graticule.js'), import('ol/extent.js'), import('ol/source/Cluster.js'), import('ol/layer/Heatmap.js'),
431
+ import('./ol-style.js'), import('./layers-ol.js')
288
432
  ]);
289
433
  if (dead) return;
290
434
 
@@ -399,8 +543,6 @@
399
543
  };
400
544
  const isSel = (f: any) => !selLayer && selected !== undefined && String(f.getId()) === selected;
401
545
  const zoomOk = () => labelMinZoom === undefined || (view.getZoom() ?? 0) >= labelMinZoom;
402
- const labelText = (text: string | undefined, offsetY: number) => text === undefined || declutter || !zoomOk() ? undefined
403
- : 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 }) });
404
546
  /**
405
547
  * GeoJSON features and individual points. Precedence: `featureStyle` function, the feature's own `style`/simplestyle
406
548
  * properties, the data-driven `style`, then the `kind` tone. A selected feature gets a heavier outline (shapes) or a halo (points).
@@ -409,26 +551,11 @@
409
551
  const p: Props = f.getProperties();
410
552
  const t = f.getGeometry()?.getType();
411
553
  const o: FeatureStyle = { ...propertyStyle(p), ...featureStyle?.(p, { id: f.getId(), type: t }) };
412
- const base = compiled.color?.(p) ?? tone(f.get('kind'));
413
- const fillC = o.fill ?? base, op = o.opacity ?? compiled.opacity, on = isSel(f);
414
- const strokeC = typeof o.stroke === 'object' ? o.stroke.color : o.stroke, strokeW = typeof o.stroke === 'object' ? o.stroke.width : undefined;
415
- if (t === 'Point' || t === 'MultiPoint') {
416
- const r = o.radius ?? compiled.size?.(p) ?? 5;
417
- if (o.colors?.length) {
418
- const pie = new Style({ image: pieIcon(o.colors, r, pieStroke(o.stroke, o.strokeWidth)), text: labelText(o.label, r + 12) });
419
- return on ? [pieRing(r), pie] : pie;
420
- }
421
- const dot = new Style({
422
- image: new CircleStyle({ radius: on ? r + 2 : r, fill: new Fill({ color: op === undefined ? fillC : rgba(fillC, op) }), stroke: new Stroke({ color: strokeC ?? T.surface, width: o.strokeWidth ?? strokeW ?? 1.5 }) }),
423
- text: labelText(o.label, r + 12)
424
- });
425
- return on ? [new Style({ image: new CircleStyle({ radius: r + 8, fill: new Fill({ color: rgba(fillC, 0.25) }) }) }), dot] : dot;
426
- }
427
- return new Style({
428
- stroke: new Stroke({ color: strokeC ?? base, width: (o.strokeWidth ?? strokeW ?? 2.5) + (on ? 1.5 : 0), lineCap: 'round', lineJoin: 'round' }),
429
- fill: new Fill({ color: rgba(fillC, Math.min(1, (op ?? 0.14) + (on ? 0.14 : 0))) }),
430
- text: labelText(o.label, 0)
431
- });
554
+ const pt = t === 'Point' || t === 'MultiPoint';
555
+ // the shared builder (createOlStyle, exported for app layers) draws it; data-driven size and opacity fill what the feature leaves out
556
+ const look: FeatureStyle = { ...o, opacity: o.opacity ?? compiled.opacity, ...(pt && { radius: o.radius ?? compiled.size?.(p) ?? 5 }) };
557
+ const out = createOlStyle(look, { selected: isSel(f), geometryType: t, tokens: T as any, color: compiled.color?.(p) ?? tone(f.get('kind')), labels: !declutter && zoomOk() });
558
+ return out.length === 1 ? out[0] : out;
432
559
  };
433
560
  const pointStyle = (f: any) => {
434
561
  const cl = f.get('_cluster');
@@ -442,7 +569,7 @@
442
569
  const o: FeatureStyle = { ...propertyStyle(p), ...featureStyle?.(p, { id: f.getId(), type: t }) };
443
570
  if (o.label === undefined) return undefined;
444
571
  const pt = t === 'Point' || t === 'MultiPoint';
445
- const r = o.radius ?? compiled.size?.(p) ?? 5;
572
+ const r0 = o.radius ?? compiled.size?.(p) ?? 5, r = drawableSymbol(o.symbol) ? Math.max(r0, 9) : r0;
446
573
  return new Style({ text: new Text({ text: String(o.label), offsetY: pt ? r + 12 : 0, font: '600 12px Inter Variable, system-ui, sans-serif', fill: new Fill({ color: T['on-surface'] }), stroke: new Stroke({ color: T.surface, width: 3 }) }) });
447
574
  };
448
575
 
@@ -463,6 +590,7 @@
463
590
  const labelPtLayer = new VectorLayer({ source: ptSrc, style: labelStyle, declutter: true, visible: false, zIndex: 26 });
464
591
 
465
592
  let baseLayers: any[] = [];
593
+ let baseKey = '';
466
594
  /** `attribution.collapsed`, with `'auto'` resolved against the map's own width (unknown while it has none). */
467
595
  const narrow = () => el.clientWidth > 0 && el.clientWidth < NARROW;
468
596
  const wantCollapsed = () => { const c = attribution?.collapsed ?? false; return c === 'auto' ? narrow() : c; };
@@ -483,6 +611,13 @@
483
611
  controls: [attrCtl, new ScaleLine({ units: 'metric', minWidth: 64 })],
484
612
  keyboardEventTarget: el
485
613
  });
614
+ // #302: the `layers` prop's vector layers (styled by the same builder; selection, tokens and label zoom come from the Map)
615
+ layerMgr = new LayerManager({
616
+ map, tokens: () => T as any, labels: () => zoomOk(),
617
+ selected: (l, f) => selLayer === l && selected !== undefined && String(f.getId()) === selected,
618
+ // a layer went (or its features were replaced): a selection in a layer that left is cleared, anything else rechecked
619
+ changed: () => { if (selLayer && !map.getAllLayers().includes(selLayer)) clear(); else sync!.select(); }
620
+ });
486
621
 
487
622
  const overlay = new Overlay({ element: popupEl, positioning: 'bottom-center', offset: [0, -16], stopEvent: true });
488
623
  map.addOverlay(overlay);
@@ -547,18 +682,27 @@
547
682
 
548
683
  // ---- sync functions (called from effects)
549
684
  sync = {
685
+ // #302: a basemap is a stack of tile layers (a `basemaps` entry wins over `basemap`); only `themed` layers carry the dark-mode filter.
686
+ // Unchanged tiles are kept (a theme change only redraws the graticule).
550
687
  base() {
688
+ const tiles = basemapTiles(activeBasemap ?? basemap);
689
+ const key = JSON.stringify(tiles);
690
+ if (key === baseKey && tiles !== 'none') return;
691
+ baseKey = key;
551
692
  for (const l of baseLayers) map.removeLayer(l);
552
693
  baseLayers = [];
553
- const osm = basemap === 'osm' ? ({} as { attribution?: string; maxZoom?: number }) : typeof basemap === 'object' && 'osm' in basemap ? basemap : undefined;
554
- if (osm) baseLayers = [new TileLayer({ source: new OSM({ attributions: osm.attribution, maxZoom: osm.maxZoom ?? 19 }), className: 'tr-basemap', zIndex: 0 })];
555
- else if (basemap === 'none') {
694
+ if (tiles === 'none') {
556
695
  baseLayers = [new Graticule({ strokeStyle: new Stroke({ color: rgba(T.outline, 0.45), width: 1 }), showLabels: true, wrapX: true, zIndex: 0,
557
696
  latLabelStyle: new Text({ font: '11px Inter Variable, system-ui', fill: new Fill({ color: T.outline }) }),
558
697
  lonLabelStyle: new Text({ font: '11px Inter Variable, system-ui', fill: new Fill({ color: T.outline }) }) })];
559
- } else if (typeof basemap === 'object' && 'url' in basemap) baseLayers = [new TileLayer({ source: new XYZ({ url: basemap.url, attributions: basemap.attribution, maxZoom: basemap.maxZoom ?? 19 }), className: 'tr-basemap', zIndex: 0 })];
698
+ } else baseLayers = tiles.map((t) => new TileLayer({
699
+ source: t.osm ? new OSM({ attributions: t.attribution, maxZoom: t.maxZoom }) : new XYZ({ url: t.url, attributions: t.attribution, maxZoom: t.maxZoom, ...(t.minZoom !== undefined && { minZoom: t.minZoom }) }),
700
+ className: t.themed ? 'tr-basemap' : 'tr-basemap tr-basemap-plain', zIndex: 0, ...(t.opacity !== undefined && { opacity: t.opacity })
701
+ }));
560
702
  for (const l of baseLayers) map.addLayer(l);
561
703
  },
704
+ // #302: the `layers` prop
705
+ layers() { layerMgr!.sync(layers ?? []); },
562
706
  markers() {
563
707
  markerSrc.clear();
564
708
  markerSrc.addFeatures(markers.filter((m) => validLonLat(m.lon, m.lat)).map((m) => {
@@ -599,7 +743,7 @@
599
743
  style() {
600
744
  read(); clusterStyles.clear(); recompile(); heatLayer.setGradient(heatGradient());
601
745
  labelGeoLayer.setVisible(declutter); labelPtLayer.setVisible(declutter);
602
- markerLayer.changed(); geoLayer.changed(); ptLayer.changed(); labelGeoLayer.changed(); labelPtLayer.changed(); this.base();
746
+ markerLayer.changed(); geoLayer.changed(); ptLayer.changed(); labelGeoLayer.changed(); labelPtLayer.changed(); this.base(); layerMgr?.restyle();
603
747
  },
604
748
  limits() { view.setMinZoom(minZoom); view.setMaxZoom(maxZoom); },
605
749
  attribution() {
@@ -607,7 +751,7 @@
607
751
  (attrEl.querySelector('button') as HTMLButtonElement).title = L.attributions;
608
752
  },
609
753
  select() {
610
- markerLayer.changed(); geoLayer.changed(); ptLayer.changed();
754
+ markerLayer.changed(); geoLayer.changed(); ptLayer.changed(); layerMgr?.redraw();
611
755
  const m = selLayer ? undefined : markers.find((x) => x.id === selected);
612
756
  const f: any = m || selected === undefined ? undefined : selLayer ? selLayer.getSource()?.getFeatureById(selected) : geoSrc.getFeatureById(selected) ?? ptSrc.getFeatureById(selected) ?? aggSrc.getFeatureById(selected);
613
757
  const g = f?.getGeometry();
@@ -641,7 +785,7 @@
641
785
  if (target === undefined) return;
642
786
  }
643
787
  if (target === undefined) {
644
- for (const src of [markerSrc, geoSrc, ...map.getAllLayers().filter((l: any) => !own(l) && interactive(l)).map((l: any) => l.getSource())]) extend(ext, src.getExtent()!);
788
+ for (const src of [markerSrc, geoSrc, ...map.getAllLayers().filter((l: any) => !own(l) && (interactive(l) || (layerMgr!.owns(l) && l.getVisible()))).map((l: any) => l.getSource())]) extend(ext, src.getExtent()!);
645
789
  const pe = storeExtent(store);
646
790
  if (pe) extend(ext, pe);
647
791
  } else {
@@ -664,11 +808,12 @@
664
808
  }),
665
809
  updateSize: () => map.updateSize(),
666
810
  select: (layer, id) => {
667
- if (id === null || id === undefined) { clicked = undefined; selLayer = undefined; selected = mine = undefined; sync!.select(); return true; }
811
+ if (id === null || id === undefined) { x303?.selChange(); clicked = undefined; selLayer = undefined; selected = mine = undefined; sync!.select(); return true; }
668
812
  const l: any = layer === null ? undefined : map.getAllLayers().find((x: any) => layerIdOf(x) === layer && typeof x.getSource()?.getFeatureById === 'function');
669
813
  if (layer !== null && !l) return false;
670
814
  const k = String(id);
671
815
  if (!(l ? l.getSource().getFeatureById(k) : markerSrc.getFeatureById(k) ?? geoSrc.getFeatureById(k) ?? ptSrc.getFeatureById(k) ?? aggSrc.getFeatureById(k))) return false;
816
+ x303?.selChange();
672
817
  clicked = undefined; selLayer = l; selected = mine = k; sync!.select();
673
818
  return true;
674
819
  }
@@ -690,7 +835,7 @@
690
835
  refreshView();
691
836
  emitView();
692
837
  });
693
- const clear = () => { selLayer = undefined; selected = mine = undefined; sync!.select(); onselect?.(null); };
838
+ const clear = () => { x303?.selChange(); selLayer = undefined; selected = mine = undefined; sync!.select(); onselect?.(null); };
694
839
  /**
695
840
  * Select a feature (marker, GeoJSON feature, point, or a feature of a `trussInteractive` layer `l`) as a click or the keyboard would;
696
841
  * `at` anchors the popup for shapes. A feature without an id, or one that cannot be found again, clears the selection instead.
@@ -698,6 +843,7 @@
698
843
  const choose = (f: any, l: any, at?: number[]) => {
699
844
  const raw = f.getId();
700
845
  if (raw === undefined) { clear(); return; }
846
+ x303?.selChange();
701
847
  selLayer = own(l) ? undefined : l;
702
848
  const id = String(raw);
703
849
  clicked = at ? { id, at } : undefined;
@@ -723,11 +869,13 @@
723
869
  choose(next.f, next.l);
724
870
  };
725
871
  const onkey = (e: KeyboardEvent) => {
872
+ if (key303(e)) return;
726
873
  if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); cycle(e.shiftKey ? -1 : 1); }
727
874
  else if (e.key === 'Escape') { hideTip(); if (selected !== undefined) clear(); }
728
875
  };
729
876
  el.addEventListener('keydown', onkey);
730
877
  map.on('singleclick', (e) => {
878
+ if (click303()) return;
731
879
  const hit = map.forEachFeatureAtPixel(e.pixel, (f, l) => ({ f, l }), { hitTolerance: 6, layerFilter: hittable });
732
880
  const cl = hit?.f.get('_cluster');
733
881
  if (cl) {
@@ -756,8 +904,186 @@
756
904
  el.addEventListener('pointerleave', hideTip);
757
905
  map.on('movestart', hideTip);
758
906
 
907
+ // ---- #303: the app popup, drawing and editing, the locate control, the context menu
908
+ // The app popup: its own overlay and element, styled like the selection popup, which it hides while it shows.
909
+ const appOverlay = new Overlay({ element: appEl, positioning: 'bottom-center', offset: [0, -16], stopEvent: true });
910
+ map.addOverlay(appOverlay);
911
+ /** Where focus goes back to when the app popup closes (what had it when the popup opened). */
912
+ let returnTo: HTMLElement | null = null;
913
+ const closeApp = (restore = true) => {
914
+ const a = app;
915
+ if (!a) return;
916
+ const active = document.activeElement;
917
+ const inside = appEl.contains(active) || active === document.body;
918
+ app = null;
919
+ appOverlay.setPosition(undefined);
920
+ a.onclose?.();
921
+ if (restore && inside) (returnTo?.isConnected ? returnTo : el).focus({ preventScroll: true });
922
+ returnTo = null;
923
+ };
924
+ const FOCUSABLE = 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
925
+ const openApp = async (lonLat: [number, number], o: MapPopupOptions) => {
926
+ if (!validLonLat(lonLat[0], lonLat[1])) return;
927
+ const active = document.activeElement as HTMLElement | null;
928
+ // a popup replacing another keeps the first one's way back
929
+ const back = app ? returnTo : active && active !== document.body ? active : null;
930
+ closeApp(false);
931
+ returnTo = back;
932
+ hideTip();
933
+ app = o; hush = true;
934
+ appOverlay.setPosition(fromLonLat(lonLat));
935
+ await tick();
936
+ if (app !== o) return;
937
+ const card = appEl.querySelector<HTMLElement>('.card')!;
938
+ (card.querySelector<HTMLElement>(`.body :is(${FOCUSABLE})`) ?? card).focus({ preventScroll: true });
939
+ if (o.autoPan !== false) appOverlay.panIntoView({ animation: { duration: moveMs(250) }, margin: 24 });
940
+ };
941
+ // 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)
942
+ const popKey = (e: KeyboardEvent) => {
943
+ if (e.key !== 'Escape') return;
944
+ e.stopPropagation();
945
+ if (e.currentTarget === appEl) closeApp();
946
+ else { el.focus({ preventScroll: true }); clear(); }
947
+ };
948
+ appEl.addEventListener('keydown', popKey);
949
+ popupEl.addEventListener('keydown', popKey);
950
+
951
+ // Drawing and editing (edit.ts): ol/interaction/* load when a drawMode is first set.
952
+ let sketchKey = '', sketchStyle: any;
953
+ const sketch = () => {
954
+ const k = `${T.primary}|${T.surface}`;
955
+ if (k !== sketchKey) {
956
+ sketchKey = k;
957
+ sketchStyle = new Style({
958
+ image: new CircleStyle({ radius: 6, fill: new Fill({ color: T.primary }), stroke: new Stroke({ color: T.surface, width: 2 }) }),
959
+ stroke: new Stroke({ color: T.primary, width: 2.5, lineDash: [6, 4] }),
960
+ fill: new Fill({ color: rgba(T.primary, 0.15) })
961
+ });
962
+ }
963
+ return sketchStyle;
964
+ };
965
+ const gj = new GeoJSON();
966
+ const editor = createEditor({
967
+ map, own: geoLayer, style: sketch,
968
+ find: (id) => map.getAllLayers().find((l: any) => layerIdOf(l) === id && typeof l.getSource?.()?.getFeatures === 'function'),
969
+ toGeoJSON: (f) => gj.writeFeatureObject(f, { featureProjection: 'EPSG:3857', dataProjection: 'EPSG:4326' }) as any,
970
+ events: () => ({ drawend: ondrawend, modifyend: onmodifyend, moveend: onmoveend })
971
+ });
972
+ let lastMode: MapDrawMode | null = null;
973
+
974
+ // 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.
975
+ let stopWatch: (() => void) | undefined;
976
+ let locSrc: any, locLayer: any, circular: any, lastFix: MapLocation | undefined;
977
+ /** The reader moved the map since we last centred it: `follow` pauses, and the button re-centres instead of turning off. */
978
+ let panned = false;
979
+ const locStyle = (f: any) => f.get('acc')
980
+ ? new Style({ fill: new Fill({ color: rgba(T.primary, 0.12) }), stroke: new Stroke({ color: rgba(T.primary, 0.5), width: 1 }) })
981
+ : [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 }) }) })];
982
+ const centreOn = (l: MapLocation, zoomTo?: number) => view.animate({ center: fromLonLat(l.lonLat), ...(zoomTo !== undefined && { zoom: Math.max(view.getZoom()!, zoomTo) }), duration: moveMs(400) });
983
+ const stopLocate = () => { stopWatch?.(); stopWatch = undefined; tracking = false; locSrc?.clear(); lastFix = undefined; };
984
+ const startLocate = async () => {
985
+ notice = undefined; tracking = true; panned = false;
986
+ if (!locSrc) {
987
+ circular = (await import('ol/geom/Polygon.js')).circular;
988
+ locSrc = new VectorSource();
989
+ map.addLayer(locLayer = new VectorLayer({ source: locSrc, style: locStyle, zIndex: 30 }));
990
+ }
991
+ if (!tracking) return; // turned off (or unmounted) while loading
992
+ let first = true;
993
+ const o = locOpts!;
994
+ stopWatch = watchLocation(o, (l) => {
995
+ lastFix = l;
996
+ locSrc.clear(true);
997
+ 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)))]);
998
+ if (first || (o.follow && !panned)) centreOn(l, first ? o.zoom : undefined);
999
+ if (first) announce = L.located(l.accuracy);
1000
+ first = false;
1001
+ onlocate?.(l);
1002
+ }, (code) => {
1003
+ stopLocate();
1004
+ const message = code === 'denied' ? L.locateDenied : code === 'unsupported' ? L.locateUnsupported : L.locateUnavailable;
1005
+ notice = message;
1006
+ onlocateerror?.({ code, message });
1007
+ });
1008
+ };
1009
+ map.on('pointerdrag', () => { panned = true; });
1010
+
1011
+ // The context menu (contextmenu.ts): right-click and touch long-press; the keyboard is in key303.
1012
+ let ctxWire: ReturnType<typeof wireContextMenu> | undefined;
1013
+ /** A long-press just reported itself: the click OpenLayers makes of its lift must not select or clear. */
1014
+ let pressed = false;
1015
+ const onDown = () => { pressed = false; };
1016
+ el.addEventListener('pointerdown', onDown, true);
1017
+ const infoOf = (f: any, l: any, at: number[]): MapFeatureInfo => {
1018
+ const g = f.getGeometry(), { geometry, ...properties } = f.getProperties(), layer = own(l) ? undefined : layerIdOf(l);
1019
+ return { id: String(f.getId()), properties, geometryType: g.getType(), lonLat: toLonLat(g.getType() === 'Point' ? g.getCoordinates() : at) as [number, number], ...(layer !== undefined && { layer }) };
1020
+ };
1021
+ const fireCtx = (pixel: number[], source: MapContextMenuEvent['source'], feature?: MapFeatureInfo) => {
1022
+ const r = el.getBoundingClientRect();
1023
+ const ll = toLonLat(map.getCoordinateFromPixel(pixel));
1024
+ oncontextmenu?.({ lonLat: [ll[0], ll[1]], pixel: [pixel[0], pixel[1]], x: r.left + pixel[0], y: r.top + pixel[1], ...(feature && { feature }), source });
1025
+ };
1026
+ const ctxAt = (x: number, y: number, source: 'mouse' | 'touch') => {
1027
+ const r = el.getBoundingClientRect(), px = [x - r.left, y - r.top];
1028
+ if (source === 'touch') pressed = true;
1029
+ const hit = map.forEachFeatureAtPixel(px, (f, l) => ({ f, l }), { hitTolerance: 6, layerFilter: hittable });
1030
+ fireCtx(px, source, hit && !hit.f.get('_cluster') && hit.f.getId() !== undefined ? infoOf(hit.f, hit.l, map.getCoordinateFromPixel(px)) : undefined);
1031
+ };
1032
+ /** The keyboard: at the selected feature (where its popup points), else the map centre. */
1033
+ const ctxKey = () => {
1034
+ ctxWire?.keyboard();
1035
+ const m: any = sel ? markerSrc.getFeatureById(sel.id) : undefined;
1036
+ const at = fsel ? fromLonLat(fsel.lonLat) : m ? m.getGeometry().getCoordinates() : view.getCenter()!;
1037
+ fireCtx(map.getPixelFromCoordinate(at), 'keyboard', fsel ?? (m ? infoOf(m, markerLayer, at) : undefined));
1038
+ };
1039
+
1040
+ /** 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. */
1041
+ function key303(e: KeyboardEvent): boolean {
1042
+ const t = e.target as Node;
1043
+ if (t !== el) return true; // a key in a popup or on an OpenLayers control (the attribution button) is theirs
1044
+ if (e.key.startsWith('Arrow')) panned = true;
1045
+ if (editor.key(e, view.getCenter()!)) return true;
1046
+ if (oncontextmenu && (e.key === 'ContextMenu' || (e.key === 'F10' && e.shiftKey))) { e.preventDefault(); ctxKey(); return true; }
1047
+ return false;
1048
+ }
1049
+ /** Whether OpenLayers' click is not a selection: the lift of a long-press, or a click that adds a vertex. */
1050
+ function click303(): boolean {
1051
+ if (pressed) { pressed = false; return true; }
1052
+ return editor.drawing;
1053
+ }
1054
+ /** The theme changed: the location layer and the sketch redraw with the new tokens. */
1055
+ function restyle303() { locLayer?.changed(); editor.restyle(); }
1056
+
1057
+ x303 = {
1058
+ open: (at, o) => void openApp(at, o),
1059
+ close: () => closeApp(),
1060
+ selChange: () => { hush = false; closeApp(); },
1061
+ finish: editor.finish, abort: editor.abort, undo: editor.undo,
1062
+ edit: () => {
1063
+ void editor.set(drawMode, editLayer, snap);
1064
+ // announced once the effects of this change have run (a selection sync resets the live region)
1065
+ const m = drawMode;
1066
+ if (m !== lastMode && m) void tick().then(() => { if (drawMode === m) announce = L.drawing(m); });
1067
+ lastMode = m;
1068
+ },
1069
+ ctx: () => {
1070
+ if (oncontextmenu && !ctxWire) ctxWire = wireContextMenu(el, ctxAt, () => !editor.drawing);
1071
+ else if (!oncontextmenu && ctxWire) { ctxWire.dispose(); ctxWire = undefined; }
1072
+ },
1073
+ pressLocate: () => {
1074
+ if (!tracking) void startLocate();
1075
+ else if (panned && lastFix) { panned = false; centreOn(lastFix); }
1076
+ else stopLocate();
1077
+ },
1078
+ stopLocate
1079
+ };
1080
+ const dispose303 = () => {
1081
+ editor.dispose(); stopLocate(); ctxWire?.dispose();
1082
+ appEl.removeEventListener('keydown', popKey); popupEl.removeEventListener('keydown', popKey); el.removeEventListener('pointerdown', onDown, true);
1083
+ };
1084
+
759
1085
  // ---- follow theme (data-theme or data-truss-theme on the map or any ancestor, or the OS preference)
760
- const restyle = () => sync?.style();
1086
+ const restyle = () => { sync?.style(); restyle303(); };
761
1087
  const unwatch = onThemeChange(el, restyle);
762
1088
 
763
1089
  // 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
@@ -776,18 +1102,23 @@
776
1102
  const attrRo = new ResizeObserver(() => root.style.setProperty('--trm-attribution-h', `${attrEl.offsetHeight}px`));
777
1103
  attrRo.observe(attrEl);
778
1104
 
779
- sync.base(); sync.markers(); sync.geo(); sync.points();
1105
+ sync.base(); sync.markers(); sync.geo(); sync.points(); sync.layers();
780
1106
  applyStart();
781
1107
  emitView(true); // the starting view: `bind:extent` gets it, `onviewchange` only hears of a move
782
1108
  if (fitPending && el.clientWidth && el.clientHeight) { fitPending = false; ctl.fit(undefined, { duration: 0 }); }
783
1109
  ready = true;
784
1110
  emitView();
785
- onready?.({ map, fit: ctl.fit, setView: ctl.setView, getView: ctl.getView, updateSize: ctl.updateSize, select: ctl.select });
786
-
1111
+ // set before onready runs: an app callback that throws must not leave the observers behind
787
1112
  dispose = () => {
788
- unwatch(); el.removeEventListener('keydown', onkey); ro.disconnect(); attrRo.disconnect();
1113
+ unwatch(); layerMgr?.destroy(); el.removeEventListener('keydown', onkey); ro.disconnect(); attrRo.disconnect(); dispose303();
789
1114
  map.setTarget(undefined);
790
1115
  };
1116
+ x303.edit(); x303.ctx();
1117
+ onready?.({
1118
+ map, fit: ctl.fit, setView: ctl.setView, getView: ctl.getView, updateSize: ctl.updateSize, select: ctl.select,
1119
+ openPopup, closePopup, finishDrawing, abortDrawing, undoLastPoint,
1120
+ layer: (id) => layerMgr?.layer(id), reloadLayer: (id) => layerMgr?.reload(id)
1121
+ });
791
1122
  })().catch((e) => (failed = e instanceof Error ? e.message : String(e)));
792
1123
 
793
1124
  return () => { dead = true; dispose(); };
@@ -806,19 +1137,31 @@
806
1137
  $effect(() => { featureStyle; declutter; labelMinZoom; if (ready) sync?.style(); });
807
1138
  $effect(() => { minZoom; maxZoom; if (ready) sync?.limits(); });
808
1139
  $effect(() => { style; if (ready) sync?.style(); });
809
- $effect(() => { basemap; if (ready) sync?.base(); });
1140
+ $effect(() => { basemap; activeBasemap; if (ready) sync?.base(); });
1141
+ // #302: each layer's own fields are read here, so a change to one (even inside a `$state` list) resyncs; the sync itself is untracked
1142
+ $effect(() => {
1143
+ for (const l of layers ?? []) { l.id; l.geojson; l.source; l.loader; l.onload; l.style; l.simplestyle; l.visible; l.zIndex; l.interactive; l.label; l.opacity; l.declutter; }
1144
+ if (ready) untrack(() => { sync?.layers(); refit(); });
1145
+ });
810
1146
  // a `selected` the consumer set (not one a click, the keyboard or `select()` set) names one of the map's own features
811
1147
  $effect(() => { if (selected !== mine) selLayer = undefined; if (ready) sync?.select(); });
812
1148
  $effect(() => { center; zoom; if (ready) sync?.view(); });
813
1149
  $effect(() => { attribution; L.attributions; if (ready) sync?.attribution(); });
1150
+ // #303
1151
+ $effect(() => { drawMode; editLayer; snap; if (ready) untrack(() => x303?.edit()); });
1152
+ $effect(() => { oncontextmenu; if (ready) untrack(() => x303?.ctx()); });
1153
+ $effect(() => { if (!locOpts && ready) untrack(() => x303?.stopLocate()); });
1154
+ /** A `selected` the consumer set closes the app popup and lets the selection popup show again (the map's own changes do this themselves). */
1155
+ let seenSel: string | undefined;
1156
+ $effect(() => { const s = selected; untrack(() => { if (s !== seenSel) { seenSel = s; if (s !== mine) x303?.selChange(); } }); });
814
1157
  </script>
815
1158
 
816
1159
  <SsrStyle {uid} rules={{ '': `height:${cssHeight}` }} />
817
- <div class="trm" class:bare={variant === 'bare'} data-sv={uid} bind:this={root} {@attach cssvars(() => ({ 'height': cssHeight }))}>
1160
+ <div class="trm" class:bare={variant === 'bare'} class:drawing={sketchMode} data-sv={uid} bind:this={root} {@attach cssvars(() => ({ 'height': cssHeight }))}>
818
1161
  <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
819
1162
  <div class="map" bind:this={el} tabindex="0" role="application" aria-label={L.map}></div>
820
1163
 
821
- <div class="popup" bind:this={popupEl} hidden={!sel && !fsel}>
1164
+ <div class="popup" bind:this={popupEl} hidden={!!app || hush || (!sel && !fsel)}>
822
1165
  {#if sel}
823
1166
  <div class="card" role="dialog" aria-label={sel.label ?? L.location}>
824
1167
  <button type="button" class="x" aria-label={L.close} onclick={() => { selected = undefined; onselect?.(null); }}>×</button>
@@ -840,18 +1183,32 @@
840
1183
  </div>
841
1184
  {/if}
842
1185
  </div>
1186
+ <!-- #303: the popup openPopup() opens, in the selection popup's card -->
1187
+ <div class="popup" bind:this={appEl} hidden={!app}>
1188
+ {#if app}
1189
+ <div class="card app" class:nox={app.closeButton === false} role="dialog" aria-label={app.label ?? L.details} tabindex="-1">
1190
+ {#if app.closeButton !== false}<button type="button" class="x" aria-label={L.close} onclick={() => x303?.close()}>×</button>{/if}
1191
+ <div class="body">
1192
+ {#if typeof app.content === 'function'}{@render app.content()}{:else}<div class="adopt" {@attach adopt(app.content)}></div>{/if}
1193
+ </div>
1194
+ </div>
1195
+ {/if}
1196
+ </div>
843
1197
  <div class="tip" bind:this={tipEl} id={tipId} role="tooltip" hidden={!tip || (!featureTooltip && !tipText)}>
844
1198
  {#if tip}{#if featureTooltip}{@render featureTooltip(tip)}{:else}{tipText}{/if}{/if}
845
1199
  </div>
846
1200
  <div class="sr" aria-live="polite">{announce}</div>
847
1201
 
848
- {#if showZoom || showFit || toolbar}
1202
+ {#if showZoom || showFit || showBasemap || locOpts || toolbar}
849
1203
  <div class="controls" role="toolbar" aria-label={L.controls}>
850
1204
  {#if showZoom}
851
1205
  <Button variant="minimal" intent="neutral" size="sm" icon="plus" aria-label={L.zoomIn} onclick={() => ctl?.zoomBy(1)} />
852
1206
  <Button variant="minimal" intent="neutral" size="sm" icon="minus" aria-label={L.zoomOut} onclick={() => ctl?.zoomBy(-1)} />
853
1207
  {/if}
854
1208
  {#if showFit}<Button variant="minimal" intent="neutral" size="sm" icon="expand" aria-label={L.fitToData} onclick={() => (onfit ? onfit() : ctl?.fit())} />{/if}
1209
+ {#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}
1210
+ <!-- #302: the basemap switcher (a menu of checkable entries: Menu's keyboard, focus return and Escape) -->
1211
+ {#if showBasemap}<MenuButton label={L.basemap} icon="layers" iconOnly variant="minimal" intent="neutral" size="sm" items={basemapItems} />{/if}
855
1212
  {#if toolbar}{@render toolbar()}{/if}
856
1213
  </div>
857
1214
  {/if}
@@ -880,6 +1237,9 @@
880
1237
  {/each}
881
1238
  </div>
882
1239
  {/if}
1240
+ {#if notice}
1241
+ <div class="notice" role="alert">{notice}<button type="button" class="x" aria-label={L.close} onclick={() => (notice = undefined)}>×</button></div>
1242
+ {/if}
883
1243
  {#if failed}<div class="err" role="alert">{L.loadFailed(failed)}</div>{/if}
884
1244
  </div>
885
1245
 
@@ -915,12 +1275,18 @@
915
1275
  .lcat { list-style: none; margin: 4px 0 0; padding: 0; display: grid; gap: 2px; }
916
1276
  .lcat li { display: flex; align-items: center; gap: 6px; }
917
1277
  .lcat i { display: block; width: 10px; height: 10px; border-radius: 50%; }
1278
+ /* #303: the app popup (a dialog that takes focus itself when its content has nothing focusable), the keyboard crosshair while drawing, the locate notice */
1279
+ .card.app { outline: none; }
1280
+ .card.app.nox { padding-right: 12px; }
1281
+ .adopt { display: contents; }
1282
+ .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; }
1283
+ .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
1284
  .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
1285
 
920
- /* Dark mode: tint raster tiles to the theme */
921
- :global(:root[data-theme='dark'] .tr-basemap) { filter: invert(1) hue-rotate(180deg) brightness(0.92) contrast(0.9) saturate(0.7); }
1286
+ /* Dark mode: tint themed raster tiles to the theme (OSM by default); `themed: false` layers (`tr-basemap-plain`: imagery, topo, overlays) keep their colours (#302) */
1287
+ :global(:root[data-theme='dark'] .tr-basemap:not(.tr-basemap-plain)) { filter: invert(1) hue-rotate(180deg) brightness(0.92) contrast(0.9) saturate(0.7); }
922
1288
  @media (prefers-color-scheme: dark) {
923
- :global(:root:not([data-theme='light']) .tr-basemap) { filter: invert(1) hue-rotate(180deg) brightness(0.92) contrast(0.9) saturate(0.7); }
1289
+ :global(:root:not([data-theme='light']) .tr-basemap:not(.tr-basemap-plain)) { filter: invert(1) hue-rotate(180deg) brightness(0.92) contrast(0.9) saturate(0.7); }
924
1290
  }
925
1291
  /*
926
1292
  * Restyle OpenLayers' built-in controls with design tokens. ol.css loads after these rules, and some of its selectors weigh as much as