@ruckc/truss-ol 1.28.0 → 1.29.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
@@ -2,7 +2,13 @@
2
2
  import { onMount, type Snippet } from 'svelte';
3
3
  import { Button } from '@ruckc/truss-ui';
4
4
  import 'ol/ol.css';
5
- import type { Basemap, MapMarker, MapSelection } from './types.js';
5
+ import type OLMap from 'ol/Map.js';
6
+ import type { Basemap, FitOptions, FitTarget, MapApi, MapFeatureInfo, MapMarker, MapSelection, MapViewState } from './types.js';
7
+ import {
8
+ DEFAULT_PALETTES, EMPTY_STORE, NATIVE_CLUSTER_MAX, aggregate, autoMode, clusterRadius, compactCount, compileStyle, featureTitle, formatNumber,
9
+ lonLatExtent, popupEntries, propertyStyle, storeExtent, toStore, validLonLat, weightsOf, withAlpha,
10
+ type Compiled, type FeatureStyle, type HeatmapOptions, type LegendInfo, type MapStyle, type Palettes, type PointStore, type PointsInput, type PointsMode, type Props
11
+ } from './util.js';
6
12
 
7
13
  let {
8
14
  center = $bindable([0, 20]),
@@ -10,12 +16,25 @@
10
16
  basemap = 'osm',
11
17
  markers = [],
12
18
  geojson,
19
+ featureStyle,
20
+ featurePopup,
21
+ fitOnDataChange = false,
22
+ refitOnResize = false,
23
+ minZoom = 1,
24
+ maxZoom = 19,
25
+ points,
26
+ pointsMode = 'auto',
27
+ clusterDistance = 40,
28
+ heatmap,
29
+ style,
30
+ legend = false,
13
31
  selected = $bindable(),
14
32
  height = 420,
15
33
  fitOnLoad = true,
16
34
  popup,
17
35
  toolbar,
18
- onselect
36
+ onselect,
37
+ onready
19
38
  }: {
20
39
  /** [lon, lat] */
21
40
  center?: [number, number];
@@ -24,24 +43,79 @@
24
43
  markers?: MapMarker[];
25
44
  /** GeoJSON FeatureCollection/Feature. Optional `properties.kind` picks the intent color. */
26
45
  geojson?: object;
27
- /** Selected marker id. */
46
+ /**
47
+ * A (large) point set: an array of `{ lon, lat, ...properties }` or a GeoJSON FeatureCollection of `Point`/`MultiPoint` features.
48
+ * Points with an invalid coordinate are skipped. Held in typed arrays, so 10^6 points are fine; pass a plain array
49
+ * (or `$state.raw`), not a deeply reactive `$state` proxy.
50
+ */
51
+ points?: PointsInput;
52
+ /**
53
+ * How `points` are drawn: `points` (every point, up to 100,000), `cluster` (circles with counts that split as you zoom in),
54
+ * `heatmap` (density), or `auto` (`points` up to 2,000, `cluster` beyond). Clusters of up to 20,000 points use OpenLayers'
55
+ * `Cluster` source; larger sets use an equivalent grid pass over typed arrays that stays fast at 10^6+ points.
56
+ */
57
+ pointsMode?: PointsMode;
58
+ /** Cluster cell size in px: points closer than this merge. Default 40. */
59
+ clusterDistance?: number;
60
+ /** Heatmap options: `radius`, `blur`, `weightBy` (a numeric property, summed per area) and `gradient`. */
61
+ heatmap?: HeatmapOptions;
62
+ /**
63
+ * Data-driven styling for `points` and `geojson` features. `size` maps a numeric property to a radius
64
+ * (`{ by, range, domain, scale }`) and `color` maps a property to the chart palette (`{ by, scale: 'sequential' | 'diverging' | 'categorical', domain, midpoint, categories, stops }`);
65
+ * either may be a constant or a function of the feature's properties. Ramps come from `--trc-seq-*`, `--trc-div-*` and `--trc-s*` (import the charts stylesheet for the exact palettes).
66
+ */
67
+ style?: MapStyle;
68
+ /** Show a legend for the `size` and `color` scales of `style`. */
69
+ legend?: boolean;
70
+ /**
71
+ * Per-feature GeoJSON styling by function: receives the feature's properties and returns any of `fill`, `opacity`, `stroke`,
72
+ * `strokeWidth`, `radius`, `label` (all optional). It wins over what the feature carries itself (a `style` property object or the
73
+ * simplestyle keys `fill`, `fill-opacity`, `stroke`, `stroke-width`, `marker-size`, `title`), which wins over `style` and `kind`.
74
+ */
75
+ featureStyle?: (properties: Props, feature: { id: string | number | undefined; type: string }) => FeatureStyle | undefined;
76
+ /** Id of the selected marker, GeoJSON feature (its `id`, `properties.id`, or `geo:<n>`) or point. Bindable; set it to select, `undefined` to clear. */
28
77
  selected?: string;
78
+ /** Map height: px, or any CSS length. Default 420. */
29
79
  height?: number | string;
30
- /** Fit the view to markers/features on first load. */
80
+ /** Fit the view to markers/features/points on first load (once the container has a size). */
31
81
  fitOnLoad?: boolean;
82
+ /** Fit the view again whenever `markers`, `geojson` or `points` change. Default false. */
83
+ fitOnDataChange?: boolean;
84
+ /** Re-measure the map when its container resizes (always), and also refit to the data. Default false. */
85
+ refitOnResize?: boolean;
86
+ /** Lowest zoom level the view allows. Default 1. */
87
+ minZoom?: number;
88
+ /** Highest zoom level the view allows (zoom buttons, wheel, clusters and `fit` all respect it). Default 19. */
89
+ maxZoom?: number;
32
90
  /** Custom popup body for the selected marker. */
33
91
  popup?: Snippet<[marker: MapMarker]>;
92
+ /** Custom popup body for a selected GeoJSON feature or point; without it the popup lists the feature's properties. */
93
+ featurePopup?: Snippet<[feature: MapFeatureInfo]>;
34
94
  /** Extra controls appended to the toolbar. */
35
95
  toolbar?: Snippet;
36
96
  onselect?: (s: MapSelection | null) => void;
97
+ /** Called once the map exists, with the imperative API (`map`, `fit`, `setView`, `getView`, `updateSize`). */
98
+ onready?: (api: MapApi) => void;
37
99
  } = $props();
38
100
 
39
101
  let el: HTMLDivElement;
40
102
  let popupEl: HTMLDivElement;
41
103
  let ready = $state(false);
42
- let ctl: { zoomBy(d: number): void; fit(): void } | undefined;
43
- let sync: { markers(): void; geo(): void; base(): void; style(): void; select(): void; view(): void } | undefined;
104
+ 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;
105
+ let fsel = $state.raw<MapFeatureInfo | null>(null);
106
+ let announce = $state('');
107
+
108
+ /** Fit the view to a lon/lat extent, `{ lon, lat }` points, GeoJSON, or (no argument) everything on the map. */
109
+ export function fit(target?: FitTarget, options?: FitOptions) { ctl?.fit(target, options); }
110
+ /** Move the view: `center` is `[lon, lat]`; with `duration` (ms) it animates. */
111
+ export function setView(v: Partial<Pick<MapViewState, 'center' | 'zoom'>> & { duration?: number }) { ctl?.setView(v); }
112
+ /** The current centre `[lon, lat]`, zoom and visible lon/lat extent. */
113
+ export function getView(): MapViewState | undefined { return ctl?.getView(); }
114
+ /** Re-measure the container (the map does this by itself when its container resizes). */
115
+ export function updateSize() { ctl?.updateSize(); }
116
+ let sync: { limits(): void; markers(): void; geo(): void; points(): void; base(): void; style(): void; select(): void; view(): void } | undefined;
44
117
  let failed = $state<string>();
118
+ let legendInfo = $state.raw<LegendInfo>({});
45
119
 
46
120
  const sel = $derived(markers.find((m) => m.id === selected));
47
121
 
@@ -53,34 +127,56 @@
53
127
  const [
54
128
  { default: OLMap }, { default: View }, { default: TileLayer }, { default: VectorLayer }, { default: VectorSource },
55
129
  { default: OSM }, { default: XYZ }, { default: Overlay }, { default: Feature }, { default: Point }, { default: GeoJSON },
56
- { Style, Circle: CircleStyle, Fill, Stroke, Text }, { fromLonLat, toLonLat }, { default: Attribution }, { default: ScaleLine },
57
- { default: Graticule }, { createEmpty, extend, isEmpty }
130
+ { Style, Circle: CircleStyle, Fill, Stroke, Text }, { fromLonLat, toLonLat, transformExtent }, { default: Attribution }, { default: ScaleLine },
131
+ { default: Graticule }, { createEmpty, extend, isEmpty, boundingExtent, getCenter, intersects }, { default: Cluster }, { default: Heatmap }
58
132
  ] = await Promise.all([
59
133
  import('ol/Map.js'), import('ol/View.js'), import('ol/layer/Tile.js'), import('ol/layer/Vector.js'), import('ol/source/Vector.js'),
60
134
  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'),
61
135
  import('ol/style.js'), import('ol/proj.js'), import('ol/control/Attribution.js'), import('ol/control/ScaleLine.js'),
62
- import('ol/layer/Graticule.js'), import('ol/extent.js')
136
+ import('ol/layer/Graticule.js'), import('ol/extent.js'), import('ol/source/Cluster.js'), import('ol/layer/Heatmap.js')
63
137
  ]);
64
138
  if (dead) return;
65
139
 
66
140
  // ---- design tokens → concrete colors for canvas styles
67
141
  let T: Record<string, string> = {};
142
+ const P: Palettes = { ...DEFAULT_PALETTES };
68
143
  const read = () => {
69
144
  const cs = getComputedStyle(document.documentElement);
145
+ const tok = (name: string, fallback: string) => cs.getPropertyValue(name).trim() || fallback;
70
146
  for (const n of ['primary', 'success', 'warning', 'danger', 'outline', 'surface', 'on-surface', 'surface-container-high', 'outline-variant'])
71
- T[n] = cs.getPropertyValue(`--tr-${n}`).trim() || '#888888';
72
- };
73
- const rgba = (hex: string, a: number) => {
74
- const h = hex.replace('#', '');
75
- const f = h.length === 3 ? h.replace(/./g, '$&$&') : h.slice(0, 6);
76
- const n = parseInt(f, 16);
77
- return `rgba(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255},${a})`;
147
+ T[n] = tok(`--tr-${n}`, '#888888');
148
+ T['on-primary'] = tok('--tr-on-primary', '#ffffff');
149
+ // palettes: the chart tokens (charts.css), else the built-in light values
150
+ P.sequential = DEFAULT_PALETTES.sequential.map((d, i) => tok(`--trc-seq-${i + 1}`, d));
151
+ P.diverging = DEFAULT_PALETTES.diverging.map((d, i) => tok(`--trc-div-${i + 1}`, d));
152
+ P.categorical = DEFAULT_PALETTES.categorical.map((d, i) => tok(`--trc-s${i + 1}`, d));
153
+ P.other = T.outline;
78
154
  };
155
+ const rgba = withAlpha;
79
156
  const tone = (kind?: string) => (kind && kind !== 'neutral' ? T[kind] ?? T.primary : kind === 'neutral' ? T.outline : T.primary);
80
157
  read();
81
158
 
82
159
  const markerSrc = new VectorSource();
83
160
  const geoSrc = new VectorSource();
161
+ const ptSrc = new VectorSource(); // individual points (and the input of the native cluster source)
162
+ const aggSrc = new VectorSource(); // viewport-aggregated clusters / singles for large sets
163
+ const heatSrc = new VectorSource(); // viewport-aggregated density bins
164
+ let store: PointStore = EMPTY_STORE;
165
+ let mode: Exclude<PointsMode, 'auto'> = 'points';
166
+ let compiled: Compiled = compileStyle(undefined, []);
167
+ const recompile = () => {
168
+ compiled = compileStyle(style, [...geoSrc.getFeatures().map((f: any) => f.getProperties()), ...store.props], P);
169
+ legendInfo = compiled.legend;
170
+ };
171
+ const clusterStyles = new Map<number, any>();
172
+ const clusterStyle = (n: number) => {
173
+ let st = clusterStyles.get(n);
174
+ if (!st) clusterStyles.set(n, st = new Style({
175
+ image: new CircleStyle({ radius: clusterRadius(n), fill: new Fill({ color: rgba(T.primary, 0.88) }), stroke: new Stroke({ color: T.surface, width: 2 }) }),
176
+ text: new Text({ text: compactCount(n), font: '700 12px Inter Variable, system-ui, sans-serif', fill: new Fill({ color: T['on-primary'] }) })
177
+ }));
178
+ return st;
179
+ };
84
180
 
85
181
  const markerStyle = (f: any) => {
86
182
  const on = f.getId() === selected;
@@ -95,45 +191,113 @@
95
191
  })
96
192
  ];
97
193
  };
194
+ const isSel = (f: any) => selected !== undefined && String(f.getId()) === selected;
195
+ const labelText = (text: string | undefined, offsetY: number) => text === undefined ? undefined
196
+ : 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 }) });
197
+ /**
198
+ * GeoJSON features and individual points. Precedence: `featureStyle` function, the feature's own `style`/simplestyle
199
+ * properties, the data-driven `style`, then the `kind` tone. A selected feature gets a heavier outline (shapes) or a halo (points).
200
+ */
98
201
  const geoStyle = (f: any) => {
99
- const c = tone(f.get('kind'));
202
+ const p: Props = f.getProperties();
100
203
  const t = f.getGeometry()?.getType();
101
- if (t === 'Point' || t === 'MultiPoint') return new Style({ image: new CircleStyle({ radius: 5, fill: new Fill({ color: c }), stroke: new Stroke({ color: T.surface, width: 2 }) }) });
102
- return new Style({ stroke: new Stroke({ color: c, width: 2.5, lineCap: 'round', lineJoin: 'round' }), fill: new Fill({ color: rgba(c, 0.14) }) });
204
+ const o: FeatureStyle = { ...propertyStyle(p), ...featureStyle?.(p, { id: f.getId(), type: t }) };
205
+ const base = compiled.color?.(p) ?? tone(f.get('kind'));
206
+ const fillC = o.fill ?? base, op = o.opacity ?? compiled.opacity, on = isSel(f);
207
+ if (t === 'Point' || t === 'MultiPoint') {
208
+ const r = o.radius ?? compiled.size?.(p) ?? 5;
209
+ const dot = new Style({
210
+ image: new CircleStyle({ radius: on ? r + 2 : r, fill: new Fill({ color: op === undefined ? fillC : rgba(fillC, op) }), stroke: new Stroke({ color: o.stroke ?? T.surface, width: o.strokeWidth ?? 1.5 }) }),
211
+ text: labelText(o.label, r + 12)
212
+ });
213
+ return on ? [new Style({ image: new CircleStyle({ radius: r + 8, fill: new Fill({ color: rgba(fillC, 0.25) }) }) }), dot] : dot;
214
+ }
215
+ return new Style({
216
+ stroke: new Stroke({ color: o.stroke ?? base, width: (o.strokeWidth ?? 2.5) + (on ? 1.5 : 0), lineCap: 'round', lineJoin: 'round' }),
217
+ fill: new Fill({ color: rgba(fillC, Math.min(1, (op ?? 0.14) + (on ? 0.14 : 0))) }),
218
+ text: labelText(o.label, 0)
219
+ });
220
+ };
221
+ const pointStyle = (f: any) => {
222
+ const cl = f.get('_cluster');
223
+ return cl ? clusterStyle(cl.count) : geoStyle(f);
103
224
  };
104
225
 
105
226
  const markerLayer = new VectorLayer({ source: markerSrc, style: markerStyle, zIndex: 20 });
106
227
  const geoLayer = new VectorLayer({ source: geoSrc, style: geoStyle, zIndex: 10 });
228
+ const clusterSrc = new Cluster({
229
+ source: ptSrc,
230
+ distance: clusterDistance,
231
+ // a lone point stays the original feature; a group becomes a cluster feature carrying its count and extent
232
+ createCluster: (point: any, members: any[]) => members.length === 1 ? members[0] : new Feature({
233
+ geometry: point,
234
+ _cluster: { count: members.length, bbox: boundingExtent(members.map((m) => m.getGeometry().getCoordinates())) }
235
+ })
236
+ });
237
+ const ptLayer = new VectorLayer({ source: ptSrc, style: pointStyle, zIndex: 15 });
238
+ const heatLayer = new Heatmap({ source: heatSrc, weight: 'w', visible: false, zIndex: 8 });
107
239
 
108
240
  let baseLayers: any[] = [];
109
- const view = new View({ center: fromLonLat(center), zoom, minZoom: 1, maxZoom: 19 });
241
+ const view = new View({ center: fromLonLat(center), zoom, minZoom, maxZoom });
110
242
  const map = new OLMap({
111
243
  target: el,
112
244
  view,
113
- layers: [markerLayer, geoLayer],
114
- controls: [new Attribution({ collapsible: true }), new ScaleLine({ units: 'metric', minWidth: 64 })],
245
+ layers: [heatLayer, geoLayer, ptLayer, markerLayer],
246
+ controls: [new Attribution({ collapsible: true, collapsed: false }), new ScaleLine({ units: 'metric', minWidth: 64 })],
115
247
  keyboardEventTarget: el
116
248
  });
117
249
 
118
250
  const overlay = new Overlay({ element: popupEl, positioning: 'bottom-center', offset: [0, -16], stopEvent: true });
119
251
  map.addOverlay(overlay);
120
252
 
253
+ // ---- point sets: typed arrays + viewport aggregation
254
+ const viewExtent = (grow = 0.25) => {
255
+ const e = view.calculateExtent(map.getSize());
256
+ const w = (e[2] - e[0]) * grow, h = (e[3] - e[1]) * grow;
257
+ return [e[0] - w, e[1] - h, e[2] + w, e[3] + h] as [number, number, number, number];
258
+ };
259
+ const pointFeature = (i: number) => {
260
+ const f = new Feature({ ...store.props[i], geometry: new Point([store.x[i], store.y[i]]) });
261
+ f.setId(String(store.props[i].id ?? `pt:${i}`));
262
+ return f;
263
+ };
264
+ const refreshAgg = () => {
265
+ const res = view.getResolution()!;
266
+ const cells = aggregate(store, viewExtent(), clusterDistance * res);
267
+ aggSrc.clear(true);
268
+ aggSrc.addFeatures(cells.map((c) => c.count === 1 ? pointFeature(c.index) : new Feature({ geometry: new Point([c.x, c.y]), _cluster: { count: c.count, bbox: c.bbox } })));
269
+ };
270
+ const refreshHeat = () => {
271
+ const cells = aggregate(store, viewExtent(), 4 * view.getResolution()!, weightsOf(store, heatmap?.weightBy));
272
+ const peak = Math.max(...cells.map((c) => c.weight), 1e-9);
273
+ heatSrc.clear(true);
274
+ heatSrc.addFeatures(cells.map((c) => new Feature({ geometry: new Point([c.x, c.y]), w: c.weight / peak })));
275
+ };
276
+ const refreshView = () => { if (mode === 'heatmap') refreshHeat(); else if (mode === 'cluster' && store.n > NATIVE_CLUSTER_MAX) refreshAgg(); };
277
+ const heatGradient = () => {
278
+ const s = heatmap?.gradient ?? P.sequential.slice(1);
279
+ return [withAlpha(s[0], 0), ...s];
280
+ };
281
+
282
+ let clicked: { id: string; at: number[] } | undefined; // where a click landed, to anchor the popup of a shape
283
+
121
284
  // ---- sync functions (called from effects)
122
285
  sync = {
123
286
  base() {
124
287
  for (const l of baseLayers) map.removeLayer(l);
125
288
  baseLayers = [];
126
- if (basemap === 'osm') baseLayers = [new TileLayer({ source: new OSM(), className: 'tr-basemap', zIndex: 0 })];
289
+ const osm = basemap === 'osm' ? ({} as { attribution?: string; maxZoom?: number }) : typeof basemap === 'object' && 'osm' in basemap ? basemap : undefined;
290
+ if (osm) baseLayers = [new TileLayer({ source: new OSM({ attributions: osm.attribution, maxZoom: osm.maxZoom ?? 19 }), className: 'tr-basemap', zIndex: 0 })];
127
291
  else if (basemap === 'none') {
128
292
  baseLayers = [new Graticule({ strokeStyle: new Stroke({ color: rgba(T.outline, 0.45), width: 1 }), showLabels: true, wrapX: true, zIndex: 0,
129
293
  latLabelStyle: new Text({ font: '11px Inter Variable, system-ui', fill: new Fill({ color: T.outline }) }),
130
294
  lonLabelStyle: new Text({ font: '11px Inter Variable, system-ui', fill: new Fill({ color: T.outline }) }) })];
131
- } else baseLayers = [new TileLayer({ source: new XYZ({ url: basemap.url, attributions: basemap.attribution, maxZoom: basemap.maxZoom ?? 19 }), className: 'tr-basemap', zIndex: 0 })];
295
+ } 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 })];
132
296
  for (const l of baseLayers) map.addLayer(l);
133
297
  },
134
298
  markers() {
135
299
  markerSrc.clear();
136
- markerSrc.addFeatures(markers.map((m) => {
300
+ markerSrc.addFeatures(markers.filter((m) => validLonLat(m.lon, m.lat)).map((m) => {
137
301
  const f = new Feature({ geometry: new Point(fromLonLat([m.lon, m.lat])), label: m.label, kind: m.kind });
138
302
  f.setId(m.id);
139
303
  return f;
@@ -142,49 +306,135 @@
142
306
  geo() {
143
307
  geoSrc.clear();
144
308
  if (geojson) geoSrc.addFeatures(new GeoJSON().readFeatures(geojson, { featureProjection: 'EPSG:3857' }));
309
+ // every feature gets a stable id so it can be selected: its GeoJSON id, properties.id, or its position
310
+ geoSrc.getFeatures().forEach((f: any, i: number) => { if (f.getId() === undefined) f.setId(String(f.get('id') ?? `geo:${i}`)); });
311
+ recompile();
312
+ geoLayer.changed();
145
313
  },
146
- style() { read(); markerLayer.changed(); geoLayer.changed(); this.base(); },
314
+ points() {
315
+ store = toStore(points);
316
+ mode = autoMode(store.n, pointsMode);
317
+ ptSrc.clear(true); aggSrc.clear(true); heatSrc.clear(true);
318
+ const native = mode === 'points' || (mode === 'cluster' && store.n <= NATIVE_CLUSTER_MAX);
319
+ if (native) { const fs = []; for (let i = 0; i < store.n; i++) fs.push(pointFeature(i)); ptSrc.addFeatures(fs); }
320
+ clusterSrc.setDistance(clusterDistance);
321
+ ptLayer.setSource(mode === 'cluster' ? (native ? clusterSrc : aggSrc) : ptSrc);
322
+ ptLayer.setVisible(mode !== 'heatmap');
323
+ heatLayer.setVisible(mode === 'heatmap');
324
+ heatLayer.setRadius(heatmap?.radius ?? 8);
325
+ heatLayer.setBlur(heatmap?.blur ?? 12);
326
+ heatLayer.setGradient(heatGradient());
327
+ clusterStyles.clear();
328
+ refreshView();
329
+ recompile();
330
+ ptLayer.changed();
331
+ },
332
+ style() { read(); clusterStyles.clear(); recompile(); heatLayer.setGradient(heatGradient()); markerLayer.changed(); geoLayer.changed(); ptLayer.changed(); this.base(); },
333
+ limits() { view.setMinZoom(minZoom); view.setMaxZoom(maxZoom); },
147
334
  select() {
148
- markerLayer.changed();
335
+ markerLayer.changed(); geoLayer.changed(); ptLayer.changed();
149
336
  const m = markers.find((x) => x.id === selected);
150
- overlay.setPosition(m ? fromLonLat([m.lon, m.lat]) : undefined);
337
+ const f: any = m || selected === undefined ? undefined : geoSrc.getFeatureById(selected) ?? ptSrc.getFeatureById(selected) ?? aggSrc.getFeatureById(selected);
338
+ if (f) {
339
+ const g = f.getGeometry();
340
+ const pos = clicked && clicked.id === selected ? clicked.at : g.getType() === 'Point' ? g.getCoordinates() : getCenter(g.getExtent());
341
+ const { geometry, ...properties } = f.getProperties();
342
+ fsel = { id: selected!, properties, lonLat: toLonLat(pos) as [number, number] };
343
+ announce = featureTitle(properties);
344
+ overlay.setPosition(pos);
345
+ } else {
346
+ fsel = null;
347
+ announce = m?.label ?? '';
348
+ overlay.setPosition(m ? fromLonLat([m.lon, m.lat]) : undefined);
349
+ }
151
350
  },
152
351
  view() {
153
352
  const c = toLonLat(view.getCenter()!);
154
- if (Math.abs(c[0] - center[0]) > 1e-6 || Math.abs(c[1] - center[1]) > 1e-6) view.animate({ center: fromLonLat(center), duration: 250 });
155
- if (Math.abs((view.getZoom() ?? 0) - zoom) > 1e-6) view.animate({ zoom, duration: 250 });
353
+ // tolerances match the rounding moveend applies (5 and 2 decimals), so the view's own echo never re-animates it
354
+ if (Math.abs(c[0] - center[0]) > 1e-5 || Math.abs(c[1] - center[1]) > 1e-5) view.animate({ center: fromLonLat(center), duration: 250 });
355
+ if (Math.abs((view.getZoom() ?? 0) - zoom) > 0.01) view.animate({ zoom, duration: 250 });
156
356
  }
157
357
  };
158
358
  ctl = {
159
- zoomBy: (d) => view.animate({ zoom: (view.getZoom() ?? 0) + d, duration: 200 }),
160
- fit: () => {
161
- const ext = createEmpty();
162
- for (const src of [markerSrc, geoSrc]) { const e = src.getExtent(); if (e) extend(ext, e); }
163
- if (!isEmpty(ext)) view.fit(ext, { padding: [56, 56, 56, 56], maxZoom: 12, duration: 300 });
164
- }
359
+ zoomBy: (d) => view.animate({ zoom: Math.min(Math.max((view.getZoom() ?? 0) + d, view.getMinZoom()), view.getMaxZoom()), duration: 200 }),
360
+ fit: (target, o = {}) => {
361
+ let ext = createEmpty();
362
+ if (target === undefined) {
363
+ for (const src of [markerSrc, geoSrc]) extend(ext, src.getExtent()!);
364
+ const pe = storeExtent(store);
365
+ if (pe) extend(ext, pe);
366
+ } else {
367
+ const ll = lonLatExtent(target);
368
+ if (ll) ext = transformExtent(ll, 'EPSG:4326', 'EPSG:3857');
369
+ }
370
+ if (isEmpty(ext)) return;
371
+ const pad = typeof o.padding === 'number' ? [o.padding, o.padding, o.padding, o.padding] : o.padding ?? [56, 56, 56, 56];
372
+ view.fit(ext, { padding: pad, maxZoom: o.maxZoom ?? 12, duration: o.duration ?? 300 });
373
+ },
374
+ setView: (v) => {
375
+ const to = { ...(v.center && { center: fromLonLat(v.center) }), ...(v.zoom !== undefined && { zoom: v.zoom }) };
376
+ if (v.duration) view.animate({ ...to, duration: v.duration });
377
+ else { if (to.center) view.setCenter(to.center); if (to.zoom !== undefined) view.setZoom(to.zoom); }
378
+ },
379
+ getView: () => ({
380
+ center: toLonLat(view.getCenter()!) as [number, number],
381
+ zoom: view.getZoom() ?? 0,
382
+ extent: transformExtent(view.calculateExtent(map.getSize()), 'EPSG:3857', 'EPSG:4326') as [number, number, number, number]
383
+ }),
384
+ updateSize: () => map.updateSize()
165
385
  };
166
386
 
167
387
  // ---- user interaction
388
+ /** Only data layers take part in hit tests: not the basemap (graticule lines are features) nor the heatmap. */
389
+ const hittable = (l: any) => l !== heatLayer && !baseLayers.includes(l);
168
390
  map.on('moveend', () => {
169
391
  const c = toLonLat(view.getCenter()!);
170
392
  center = [Number(c[0].toFixed(5)), Number(c[1].toFixed(5))];
171
393
  zoom = Number((view.getZoom() ?? 0).toFixed(2));
394
+ refreshView();
172
395
  });
396
+ /** Select a feature (marker, GeoJSON feature or point) as a click or the keyboard would; `at` anchors the popup for shapes. */
397
+ const choose = (f: any, at?: number[]) => {
398
+ const id = String(f.getId());
399
+ clicked = at ? { id, at } : undefined;
400
+ selected = id;
401
+ sync!.select();
402
+ if (markerSrc.getFeatureById(id)) onselect?.({ type: 'marker', marker: markers.find((x) => x.id === id)! });
403
+ else onselect?.({ type: 'feature', id: f.getId(), properties: fsel!.properties });
404
+ };
405
+ const clear = () => { selected = undefined; sync!.select(); onselect?.(null); };
406
+ /** Features shown inside the current view, in a stable order, for keyboard selection. */
407
+ const visible = () => {
408
+ const ext = view.calculateExtent(map.getSize());
409
+ const out: any[] = [];
410
+ 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);
411
+ return out;
412
+ };
413
+ const cycle = (dir: number) => {
414
+ const list = visible();
415
+ if (!list.length) return;
416
+ const at = list.findIndex((f) => String(f.getId()) === selected);
417
+ choose(list[at < 0 ? (dir > 0 ? 0 : list.length - 1) : (at + dir + list.length) % list.length]);
418
+ };
419
+ const onkey = (e: KeyboardEvent) => {
420
+ if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); cycle(e.shiftKey ? -1 : 1); }
421
+ else if (e.key === 'Escape' && selected !== undefined) clear();
422
+ };
423
+ el.addEventListener('keydown', onkey);
173
424
  map.on('singleclick', (e) => {
174
- const hit = map.forEachFeatureAtPixel(e.pixel, (f, l) => ({ f, l }), { hitTolerance: 6 });
175
- if (hit && hit.l === markerLayer) {
176
- selected = String(hit.f.getId());
177
- const m = markers.find((x) => x.id === selected)!;
178
- onselect?.({ type: 'marker', marker: m });
179
- } else if (hit) {
180
- selected = undefined;
181
- const { geometry, ...properties } = hit.f.getProperties();
182
- onselect?.({ type: 'feature', id: hit.f.getId(), properties });
183
- } else { selected = undefined; onselect?.(null); }
425
+ const hit = map.forEachFeatureAtPixel(e.pixel, (f, l) => ({ f, l }), { hitTolerance: 6, layerFilter: hittable });
426
+ const cl = hit?.f.get('_cluster');
427
+ if (cl) {
428
+ // a cluster zooms in on its members (or two levels when they all sit on one spot)
429
+ const [x0, y0, x1, y1] = cl.bbox;
430
+ if (x1 - x0 < 1 && y1 - y0 < 1) view.animate({ center: [x0, y0], zoom: Math.min((view.getZoom() ?? 0) + 2, view.getMaxZoom()), duration: 300 });
431
+ else view.fit(cl.bbox, { padding: [60, 60, 60, 60], duration: 300, maxZoom: view.getMaxZoom() });
432
+ } else if (hit) choose(hit.f, e.coordinate);
433
+ else clear();
184
434
  });
185
435
  map.on('pointermove', (e) => {
186
436
  if (e.dragging) return;
187
- el.style.cursor = map.hasFeatureAtPixel(e.pixel, { hitTolerance: 6 }) ? 'pointer' : '';
437
+ el.style.cursor = map.hasFeatureAtPixel(e.pixel, { hitTolerance: 6, layerFilter: hittable }) ? 'pointer' : '';
188
438
  });
189
439
 
190
440
  // ---- follow theme (data-theme toggle or OS preference)
@@ -194,12 +444,22 @@
194
444
  const mq = matchMedia('(prefers-color-scheme: dark)');
195
445
  mq.addEventListener('change', restyle);
196
446
 
197
- sync.base(); sync.markers(); sync.geo();
198
- if (fitOnLoad && (markers.length || geojson)) ctl.fit();
447
+ // 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
448
+ let fitPending = fitOnLoad;
449
+ const ro = new ResizeObserver(() => {
450
+ map.updateSize();
451
+ if (!el.clientWidth || !el.clientHeight) return;
452
+ if (fitPending || refitOnResize) { fitPending = false; ctl!.fit(undefined, { duration: 0 }); }
453
+ });
454
+ ro.observe(el);
455
+
456
+ sync.base(); sync.markers(); sync.geo(); sync.points();
457
+ if (fitPending && el.clientWidth && el.clientHeight) { fitPending = false; ctl.fit(undefined, { duration: 0 }); }
199
458
  ready = true;
459
+ onready?.({ map, fit: ctl.fit, setView: ctl.setView, getView: ctl.getView, updateSize: ctl.updateSize });
200
460
 
201
461
  dispose = () => {
202
- mo.disconnect(); mq.removeEventListener('change', restyle);
462
+ mo.disconnect(); mq.removeEventListener('change', restyle); el.removeEventListener('keydown', onkey); ro.disconnect();
203
463
  map.setTarget(undefined);
204
464
  };
205
465
  })().catch((e) => (failed = e instanceof Error ? e.message : String(e)));
@@ -207,8 +467,19 @@
207
467
  return () => { dead = true; dispose(); };
208
468
  });
209
469
 
210
- $effect(() => { markers; if (ready) { sync?.markers(); sync?.select(); } });
211
- $effect(() => { geojson; if (ready) sync?.geo(); });
470
+ // data changes: resync, then (opt-in) refit once per batch of changes
471
+ let refitQueued = false;
472
+ const refit = () => {
473
+ if (!fitOnDataChange || refitQueued) return;
474
+ refitQueued = true;
475
+ queueMicrotask(() => { refitQueued = false; ctl?.fit(); });
476
+ };
477
+ $effect(() => { markers; if (ready) { sync?.markers(); sync?.select(); refit(); } });
478
+ $effect(() => { geojson; if (ready) { sync?.geo(); sync?.select(); refit(); } });
479
+ $effect(() => { points; pointsMode; clusterDistance; heatmap; if (ready) { sync?.points(); refit(); } });
480
+ $effect(() => { featureStyle; if (ready) sync?.style(); });
481
+ $effect(() => { minZoom; maxZoom; if (ready) sync?.limits(); });
482
+ $effect(() => { style; if (ready) sync?.style(); });
212
483
  $effect(() => { basemap; if (ready) sync?.base(); });
213
484
  $effect(() => { selected; if (ready) sync?.select(); });
214
485
  $effect(() => { center; zoom; if (ready) sync?.view(); });
@@ -218,7 +489,7 @@
218
489
  <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
219
490
  <div class="map" bind:this={el} tabindex="0" role="application" aria-label="Map. Arrow keys pan, plus and minus zoom."></div>
220
491
 
221
- <div class="popup" bind:this={popupEl} hidden={!sel}>
492
+ <div class="popup" bind:this={popupEl} hidden={!sel && !fsel}>
222
493
  {#if sel}
223
494
  <div class="card" role="dialog" aria-label={sel.label ?? 'Location'}>
224
495
  <button type="button" class="x" aria-label="Close" onclick={() => { selected = undefined; onselect?.(null); }}>×</button>
@@ -228,8 +499,19 @@
228
499
  <div class="c">{sel.lat.toFixed(4)}, {sel.lon.toFixed(4)}</div>
229
500
  {/if}
230
501
  </div>
502
+ {:else if fsel}
503
+ <div class="card" role="dialog" aria-label={featureTitle(fsel.properties)}>
504
+ <button type="button" class="x" aria-label="Close" onclick={() => { selected = undefined; onselect?.(null); }}>×</button>
505
+ {#if featurePopup}{@render featurePopup(fsel)}{:else}
506
+ <div class="t">{featureTitle(fsel.properties)}</div>
507
+ <dl class="kv">
508
+ {#each popupEntries(fsel.properties) as [k, v] (k)}<dt>{k}</dt><dd>{v}</dd>{/each}
509
+ </dl>
510
+ {/if}
511
+ </div>
231
512
  {/if}
232
513
  </div>
514
+ <div class="sr" aria-live="polite">{announce}</div>
233
515
 
234
516
  <div class="controls" role="toolbar" aria-label="Map controls">
235
517
  <Button variant="minimal" intent="neutral" size="sm" icon="plus" aria-label="Zoom in" onclick={() => ctl?.zoomBy(1)} />
@@ -237,6 +519,28 @@
237
519
  <Button variant="minimal" intent="neutral" size="sm" icon="expand" aria-label="Fit to data" onclick={() => ctl?.fit()} />
238
520
  {#if toolbar}{@render toolbar()}{/if}
239
521
  </div>
522
+ {#if legend && (legendInfo.size || legendInfo.color)}
523
+ {@const lg = legendInfo}
524
+ <div class="legend" role="group" aria-label="Legend">
525
+ {#if lg.size}
526
+ <div class="lt">{lg.size.by}</div>
527
+ <div class="lsz">
528
+ {#each lg.size.steps as st (st.value)}
529
+ <span class="ls"><i style:width="{st.radius * 2}px" style:height="{st.radius * 2}px"></i>{formatNumber(st.value)}</span>
530
+ {/each}
531
+ </div>
532
+ {/if}
533
+ {#if lg.color}
534
+ <div class="lt">{lg.color.by}</div>
535
+ {#if lg.color.gradient}
536
+ <div class="lbar" style:background={lg.color.gradient} role="img" aria-label="{lg.color.by}: {formatNumber(lg.color.domain![0])} to {formatNumber(lg.color.domain![1])}"></div>
537
+ <div class="lends"><span>{formatNumber(lg.color.domain![0])}</span><span>{formatNumber(lg.color.domain![1])}</span></div>
538
+ {:else}
539
+ <ul class="lcat">{#each lg.color.categories! as c (c.label)}<li><i style:background={c.color}></i>{c.label}</li>{/each}</ul>
540
+ {/if}
541
+ {/if}
542
+ </div>
543
+ {/if}
240
544
  {#if failed}<div class="err" role="alert">Map failed to load: {failed}</div>{/if}
241
545
  </div>
242
546
 
@@ -251,8 +555,23 @@
251
555
  .t { font-weight: 700; }
252
556
  .d { color: var(--tr-on-surface-variant); font-size: var(--tr-text-sm); margin-top: 2px; }
253
557
  .c { margin-top: 6px; color: var(--tr-on-surface-variant); font: var(--tr-text-xs) var(--tr-font-mono); }
558
+ .kv { display: grid; grid-template-columns: auto 1fr; gap: 2px 10px; margin: 6px 0 0; font-size: var(--tr-text-sm); }
559
+ .kv dt { color: var(--tr-on-surface-variant); }
560
+ .kv dd { margin: 0; overflow-wrap: anywhere; }
561
+ .sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
254
562
  .x { position: absolute; top: 4px; right: 4px; width: 22px; height: 22px; border: 0; border-radius: var(--tr-radius-sm); background: none; color: var(--tr-on-surface-variant); font-size: 16px; line-height: 1; cursor: pointer; }
255
563
  .x:hover { background: var(--tr-surface-container-highest); }
564
+ .legend { position: absolute; z-index: 3; left: 8px; bottom: 8px; max-width: 220px; padding: 8px 10px; background: var(--tr-surface-container-highest); border: 1px solid var(--tr-outline-variant); border-radius: var(--tr-radius-md); color: var(--tr-on-surface-variant); font: var(--tr-text-xs) var(--tr-font-sans); }
565
+ .lt { color: var(--tr-on-surface); font-weight: 600; margin-top: 2px; }
566
+ .lt:not(:first-child) { margin-top: 8px; }
567
+ .lsz { display: flex; align-items: flex-end; gap: 10px; margin-top: 4px; }
568
+ .ls { display: flex; flex-direction: column; align-items: center; gap: 2px; }
569
+ .ls i { display: block; border-radius: 50%; border: 1.5px solid var(--tr-on-surface-variant); }
570
+ .lbar { height: 8px; margin-top: 4px; border-radius: var(--tr-radius-pill); width: 160px; }
571
+ .lends { display: flex; justify-content: space-between; width: 160px; margin-top: 2px; }
572
+ .lcat { list-style: none; margin: 4px 0 0; padding: 0; display: grid; gap: 2px; }
573
+ .lcat li { display: flex; align-items: center; gap: 6px; }
574
+ .lcat i { display: block; width: 10px; height: 10px; border-radius: 50%; }
256
575
  .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); }
257
576
 
258
577
  /* Dark mode: tint raster tiles to the theme */