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