@ruckc/truss-ol 1.29.0 → 1.31.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 +18 -6
- package/dist/Map.svelte +165 -51
- package/dist/Map.svelte.d.ts +27 -2
- package/dist/index.d.ts +1 -1
- package/dist/points.d.ts +11 -2
- package/dist/points.js +33 -2
- package/dist/style.d.ts +106 -21
- package/dist/style.js +85 -4
- package/dist/types.d.ts +5 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -28,8 +28,17 @@ npm install @ruckc/truss-ol @ruckc/truss-ui ol
|
|
|
28
28
|
<Map points={quakes} pointsMode="cluster" legend
|
|
29
29
|
style={{ size: { by: 'mag', range: [2, 18] }, color: { by: 'depth', scale: 'sequential' } }} />
|
|
30
30
|
|
|
31
|
-
<!--
|
|
32
|
-
<Map points={quakes} pointsMode="
|
|
31
|
+
<!-- clusters sized by count and coloured by their strongest quake, with a legend -->
|
|
32
|
+
<Map points={quakes} pointsMode="cluster" legend
|
|
33
|
+
clusterStyle={{ size: { by: 'count' }, color: { by: { agg: 'max', prop: 'mag' }, title: 'Peak magnitude', format: (v) => `M${v.toFixed(1)}` } }} />
|
|
34
|
+
|
|
35
|
+
<!-- labels that never overlap, a hover tooltip and stable ids -->
|
|
36
|
+
<Map points={quakes} declutter labelMinZoom={4} idBy="code"
|
|
37
|
+
featureStyle={(p) => (p.mag >= 6 ? { label: `M${p.mag}` } : undefined)}
|
|
38
|
+
tooltip={(f) => `${f.properties.place} · M${f.properties.mag}`} />
|
|
39
|
+
|
|
40
|
+
<!-- density heatmap weighted by magnitude, with a legend -->
|
|
41
|
+
<Map points={quakes} pointsMode="heatmap" legend heatmap={{ weightBy: 'mag', radius: 8, blur: 12, title: 'Energy' }} />
|
|
33
42
|
```
|
|
34
43
|
|
|
35
44
|
## Props
|
|
@@ -42,12 +51,15 @@ npm install @ruckc/truss-ol @ruckc/truss-ui ol
|
|
|
42
51
|
| `geojson` | A GeoJSON Feature or FeatureCollection. |
|
|
43
52
|
| `points` | A large point set: `{ lon, lat, ...properties }[]` or a GeoJSON FeatureCollection of points. |
|
|
44
53
|
| `pointsMode` | `'auto'` (points up to 2,000, clusters beyond), `'points'`, `'cluster'`, `'heatmap'`. |
|
|
45
|
-
| `clusterDistance`, `heatmap` | Cluster cell size in px; heatmap `radius`, `blur`, `weightBy`, `gradient`. |
|
|
46
|
-
| `style`, `legend` | Data-driven size and colour from feature properties (spec or function); `legend` draws the key. |
|
|
54
|
+
| `clusterDistance`, `heatmap` | Cluster cell size in px; heatmap `radius`, `blur`, `weightBy`, `gradient`, `title`. |
|
|
55
|
+
| `style`, `clusterStyle`, `legend` | Data-driven size and colour from feature properties (spec or function); clusters size and colour from aggregates (`by: 'count'` or `{ agg: 'sum' \| 'mean' \| 'min' \| 'max', prop }`). Every spec takes `title` and `format` for the legend; `legend` draws the key, including a heatmap ramp. |
|
|
56
|
+
| `declutter`, `labelMinZoom` | Labels on their own decluttered layer (the points always show); labels only from a zoom level. |
|
|
57
|
+
| `tooltip`, `featureTooltip` | Hover tooltip for points and features: `true` (the name), a `(feature) => string` formatter, or a snippet. A `role="tooltip"` the map points `aria-describedby` at; `Escape` hides it. |
|
|
58
|
+
| `idBy` | Stable ids for points and GeoJSON features: a property name or `(properties, index) => id`, instead of `pt:n` / `geo:n`. |
|
|
47
59
|
| `featureStyle` | Per-feature GeoJSON styling by function. Features may also carry `style` / simplestyle properties. |
|
|
48
|
-
| `selected` (bindable), `onselect` | Selection of a marker, GeoJSON feature or point, by click or keyboard. |
|
|
60
|
+
| `selected` (bindable), `onselect` | Selection of a marker, GeoJSON feature or point, by click or keyboard. `onselect` and `featurePopup` receive the `geometryType` (`Point`, `Polygon`, ...). |
|
|
49
61
|
| `popup`, `featurePopup`, `toolbar` | Snippets: marker popup body, feature popup body, extra toolbar controls. |
|
|
50
|
-
| `fitOnLoad`, `fitOnDataChange`, `refitOnResize` | When the view fits the data. |
|
|
62
|
+
| `fitOnLoad`, `fitOnDataChange`, `refitOnResize` | When the view fits the data. `center` and `zoom` are applied only when you change them, so their defaults never undo a fit. |
|
|
51
63
|
| `height`, `onready` | Map height; `onready(api)` receives `{ map, fit, setView, getView, updateSize }`. |
|
|
52
64
|
|
|
53
65
|
Methods (via `bind:this`): `fit(target?, { padding, duration, maxZoom })`, `setView({ center, zoom, duration })`, `getView()`, `updateSize()`.
|
package/dist/Map.svelte
CHANGED
|
@@ -5,9 +5,9 @@
|
|
|
5
5
|
import type OLMap from 'ol/Map.js';
|
|
6
6
|
import type { Basemap, FitOptions, FitTarget, MapApi, MapFeatureInfo, MapMarker, MapSelection, MapViewState } from './types.js';
|
|
7
7
|
import {
|
|
8
|
-
DEFAULT_PALETTES, EMPTY_STORE, NATIVE_CLUSTER_MAX, aggregate, autoMode, clusterRadius, compactCount, compileStyle,
|
|
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
|
|
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
11
|
} from './util.js';
|
|
12
12
|
|
|
13
13
|
let {
|
|
@@ -27,6 +27,12 @@
|
|
|
27
27
|
clusterDistance = 40,
|
|
28
28
|
heatmap,
|
|
29
29
|
style,
|
|
30
|
+
clusterStyle,
|
|
31
|
+
idBy,
|
|
32
|
+
declutter = false,
|
|
33
|
+
labelMinZoom,
|
|
34
|
+
tooltip = false,
|
|
35
|
+
featureTooltip,
|
|
30
36
|
legend = false,
|
|
31
37
|
selected = $bindable(),
|
|
32
38
|
height = 420,
|
|
@@ -65,7 +71,32 @@
|
|
|
65
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).
|
|
66
72
|
*/
|
|
67
73
|
style?: MapStyle;
|
|
68
|
-
/**
|
|
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`. */
|
|
69
100
|
legend?: boolean;
|
|
70
101
|
/**
|
|
71
102
|
* Per-feature GeoJSON styling by function: receives the feature's properties and returns any of `fill`, `opacity`, `stroke`,
|
|
@@ -103,6 +134,14 @@
|
|
|
103
134
|
let ready = $state(false);
|
|
104
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;
|
|
105
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;
|
|
106
145
|
let announce = $state('');
|
|
107
146
|
|
|
108
147
|
/** Fit the view to a lon/lat extent, `{ lon, lat }` points, GeoJSON, or (no argument) everything on the map. */
|
|
@@ -164,19 +203,40 @@
|
|
|
164
203
|
let store: PointStore = EMPTY_STORE;
|
|
165
204
|
let mode: Exclude<PointsMode, 'auto'> = 'points';
|
|
166
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
|
+
};
|
|
167
213
|
const recompile = () => {
|
|
168
214
|
compiled = compileStyle(style, [...geoSrc.getFeatures().map((f: any) => f.getProperties()), ...store.props], P);
|
|
169
|
-
|
|
215
|
+
ccompiled = mode === 'cluster' ? compileCluster(clusterStyle, store.props, P) : compileCluster(undefined, []);
|
|
216
|
+
legendInfo = { ...compiled.legend, ...ccompiled.legend, ...(mode === 'heatmap' && store.n ? { heatmap: heatLegend() } : {}) };
|
|
170
217
|
};
|
|
171
|
-
const clusterStyles = new Map<
|
|
172
|
-
const
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
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'] }) })
|
|
177
227
|
}));
|
|
178
228
|
return st;
|
|
179
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
|
+
};
|
|
180
240
|
|
|
181
241
|
const markerStyle = (f: any) => {
|
|
182
242
|
const on = f.getId() === selected;
|
|
@@ -192,7 +252,8 @@
|
|
|
192
252
|
];
|
|
193
253
|
};
|
|
194
254
|
const isSel = (f: any) => selected !== undefined && String(f.getId()) === selected;
|
|
195
|
-
const
|
|
255
|
+
const zoomOk = () => labelMinZoom === undefined || (view.getZoom() ?? 0) >= labelMinZoom;
|
|
256
|
+
const labelText = (text: string | undefined, offsetY: number) => text === undefined || declutter || !zoomOk() ? undefined
|
|
196
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 }) });
|
|
197
258
|
/**
|
|
198
259
|
* GeoJSON features and individual points. Precedence: `featureStyle` function, the feature's own `style`/simplestyle
|
|
@@ -220,7 +281,18 @@
|
|
|
220
281
|
};
|
|
221
282
|
const pointStyle = (f: any) => {
|
|
222
283
|
const cl = f.get('_cluster');
|
|
223
|
-
return cl ?
|
|
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 }) }) });
|
|
224
296
|
};
|
|
225
297
|
|
|
226
298
|
const markerLayer = new VectorLayer({ source: markerSrc, style: markerStyle, zIndex: 20 });
|
|
@@ -228,27 +300,39 @@
|
|
|
228
300
|
const clusterSrc = new Cluster({
|
|
229
301
|
source: ptSrc,
|
|
230
302
|
distance: clusterDistance,
|
|
231
|
-
// a lone point stays the original feature; a group becomes a cluster feature carrying its count and
|
|
303
|
+
// a lone point stays the original feature; a group becomes a cluster feature carrying its count, extent and aggregates
|
|
232
304
|
createCluster: (point: any, members: any[]) => members.length === 1 ? members[0] : new Feature({
|
|
233
305
|
geometry: point,
|
|
234
|
-
_cluster: { count: members.length, bbox: boundingExtent(members.map((m) => m.getGeometry().getCoordinates())) }
|
|
306
|
+
_cluster: { count: members.length, bbox: boundingExtent(members.map((m) => m.getGeometry().getCoordinates())), stats: statsOf(members) }
|
|
235
307
|
})
|
|
236
308
|
});
|
|
237
309
|
const ptLayer = new VectorLayer({ source: ptSrc, style: pointStyle, zIndex: 15 });
|
|
238
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 });
|
|
239
313
|
|
|
240
314
|
let baseLayers: any[] = [];
|
|
315
|
+
seenC = [...center]; seenZ = zoom;
|
|
241
316
|
const view = new View({ center: fromLonLat(center), zoom, minZoom, maxZoom });
|
|
242
317
|
const map = new OLMap({
|
|
243
318
|
target: el,
|
|
244
319
|
view,
|
|
245
|
-
layers: [heatLayer, geoLayer, ptLayer, markerLayer],
|
|
320
|
+
layers: [heatLayer, geoLayer, ptLayer, markerLayer, labelGeoLayer, labelPtLayer],
|
|
246
321
|
controls: [new Attribution({ collapsible: true, collapsed: false }), new ScaleLine({ units: 'metric', minWidth: 64 })],
|
|
247
322
|
keyboardEventTarget: el
|
|
248
323
|
});
|
|
249
324
|
|
|
250
325
|
const overlay = new Overlay({ element: popupEl, positioning: 'bottom-center', offset: [0, -16], stopEvent: true });
|
|
251
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
|
+
};
|
|
252
336
|
|
|
253
337
|
// ---- point sets: typed arrays + viewport aggregation
|
|
254
338
|
const viewExtent = (grow = 0.25) => {
|
|
@@ -258,14 +342,14 @@
|
|
|
258
342
|
};
|
|
259
343
|
const pointFeature = (i: number) => {
|
|
260
344
|
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}`));
|
|
345
|
+
f.setId(idOf(store.props[i], i) ?? String(store.props[i].id ?? `pt:${i}`));
|
|
262
346
|
return f;
|
|
263
347
|
};
|
|
264
348
|
const refreshAgg = () => {
|
|
265
349
|
const res = view.getResolution()!;
|
|
266
|
-
const cells = aggregate(store, viewExtent(), clusterDistance * res);
|
|
350
|
+
const cells = aggregate(store, viewExtent(), clusterDistance * res, undefined, cprops.length ? colValues : undefined);
|
|
267
351
|
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 } })));
|
|
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 } })));
|
|
269
353
|
};
|
|
270
354
|
const refreshHeat = () => {
|
|
271
355
|
const cells = aggregate(store, viewExtent(), 4 * view.getResolution()!, weightsOf(store, heatmap?.weightBy));
|
|
@@ -307,18 +391,21 @@
|
|
|
307
391
|
geoSrc.clear();
|
|
308
392
|
if (geojson) geoSrc.addFeatures(new GeoJSON().readFeatures(geojson, { featureProjection: 'EPSG:3857' }));
|
|
309
393
|
// 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}`)); });
|
|
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}`)); });
|
|
311
395
|
recompile();
|
|
312
396
|
geoLayer.changed();
|
|
313
397
|
},
|
|
314
398
|
points() {
|
|
315
399
|
store = toStore(points);
|
|
316
400
|
mode = autoMode(store.n, pointsMode);
|
|
401
|
+
cprops = clusterProps(clusterStyle);
|
|
402
|
+
colValues = Object.fromEntries(cprops.map((k) => [k, numbersOf(store, k)]));
|
|
317
403
|
ptSrc.clear(true); aggSrc.clear(true); heatSrc.clear(true);
|
|
318
404
|
const native = mode === 'points' || (mode === 'cluster' && store.n <= NATIVE_CLUSTER_MAX);
|
|
319
405
|
if (native) { const fs = []; for (let i = 0; i < store.n; i++) fs.push(pointFeature(i)); ptSrc.addFeatures(fs); }
|
|
320
406
|
clusterSrc.setDistance(clusterDistance);
|
|
321
407
|
ptLayer.setSource(mode === 'cluster' ? (native ? clusterSrc : aggSrc) : ptSrc);
|
|
408
|
+
labelPtLayer.setSource(ptLayer.getSource()!);
|
|
322
409
|
ptLayer.setVisible(mode !== 'heatmap');
|
|
323
410
|
heatLayer.setVisible(mode === 'heatmap');
|
|
324
411
|
heatLayer.setRadius(heatmap?.radius ?? 8);
|
|
@@ -329,7 +416,11 @@
|
|
|
329
416
|
recompile();
|
|
330
417
|
ptLayer.changed();
|
|
331
418
|
},
|
|
332
|
-
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
|
+
},
|
|
333
424
|
limits() { view.setMinZoom(minZoom); view.setMaxZoom(maxZoom); },
|
|
334
425
|
select() {
|
|
335
426
|
markerLayer.changed(); geoLayer.changed(); ptLayer.changed();
|
|
@@ -339,7 +430,7 @@
|
|
|
339
430
|
const g = f.getGeometry();
|
|
340
431
|
const pos = clicked && clicked.id === selected ? clicked.at : g.getType() === 'Point' ? g.getCoordinates() : getCenter(g.getExtent());
|
|
341
432
|
const { geometry, ...properties } = f.getProperties();
|
|
342
|
-
fsel = { id: selected!, properties, lonLat: toLonLat(pos) as [number, number] };
|
|
433
|
+
fsel = { id: selected!, properties, geometryType: g.getType(), lonLat: toLonLat(pos) as [number, number] };
|
|
343
434
|
announce = featureTitle(properties);
|
|
344
435
|
overlay.setPosition(pos);
|
|
345
436
|
} else {
|
|
@@ -349,10 +440,11 @@
|
|
|
349
440
|
}
|
|
350
441
|
},
|
|
351
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
|
|
352
444
|
const c = toLonLat(view.getCenter()!);
|
|
353
|
-
|
|
354
|
-
if (Math.abs(
|
|
355
|
-
|
|
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;
|
|
356
448
|
}
|
|
357
449
|
};
|
|
358
450
|
ctl = {
|
|
@@ -386,11 +478,12 @@
|
|
|
386
478
|
|
|
387
479
|
// ---- user interaction
|
|
388
480
|
/** 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);
|
|
481
|
+
const hittable = (l: any) => l !== heatLayer && l !== labelGeoLayer && l !== labelPtLayer && !baseLayers.includes(l);
|
|
390
482
|
map.on('moveend', () => {
|
|
391
483
|
const c = toLonLat(view.getCenter()!);
|
|
392
484
|
center = [Number(c[0].toFixed(5)), Number(c[1].toFixed(5))];
|
|
393
485
|
zoom = Number((view.getZoom() ?? 0).toFixed(2));
|
|
486
|
+
seenC = [center[0], center[1]]; seenZ = zoom;
|
|
394
487
|
refreshView();
|
|
395
488
|
});
|
|
396
489
|
/** Select a feature (marker, GeoJSON feature or point) as a click or the keyboard would; `at` anchors the popup for shapes. */
|
|
@@ -400,7 +493,7 @@
|
|
|
400
493
|
selected = id;
|
|
401
494
|
sync!.select();
|
|
402
495
|
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 });
|
|
496
|
+
else onselect?.({ type: 'feature', id: f.getId(), properties: fsel!.properties, geometryType: fsel!.geometryType });
|
|
404
497
|
};
|
|
405
498
|
const clear = () => { selected = undefined; sync!.select(); onselect?.(null); };
|
|
406
499
|
/** Features shown inside the current view, in a stable order, for keyboard selection. */
|
|
@@ -418,7 +511,7 @@
|
|
|
418
511
|
};
|
|
419
512
|
const onkey = (e: KeyboardEvent) => {
|
|
420
513
|
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); cycle(e.shiftKey ? -1 : 1); }
|
|
421
|
-
else if (e.key === 'Escape'
|
|
514
|
+
else if (e.key === 'Escape') { hideTip(); if (selected !== undefined) clear(); }
|
|
422
515
|
};
|
|
423
516
|
el.addEventListener('keydown', onkey);
|
|
424
517
|
map.on('singleclick', (e) => {
|
|
@@ -433,9 +526,22 @@
|
|
|
433
526
|
else clear();
|
|
434
527
|
});
|
|
435
528
|
map.on('pointermove', (e) => {
|
|
436
|
-
if (e.dragging) return;
|
|
437
|
-
|
|
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);
|
|
438
542
|
});
|
|
543
|
+
el.addEventListener('pointerleave', hideTip);
|
|
544
|
+
map.on('movestart', hideTip);
|
|
439
545
|
|
|
440
546
|
// ---- follow theme (data-theme toggle or OS preference)
|
|
441
547
|
const restyle = () => sync?.style();
|
|
@@ -475,9 +581,9 @@
|
|
|
475
581
|
queueMicrotask(() => { refitQueued = false; ctl?.fit(); });
|
|
476
582
|
};
|
|
477
583
|
$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(); });
|
|
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(); });
|
|
481
587
|
$effect(() => { minZoom; maxZoom; if (ready) sync?.limits(); });
|
|
482
588
|
$effect(() => { style; if (ready) sync?.style(); });
|
|
483
589
|
$effect(() => { basemap; if (ready) sync?.base(); });
|
|
@@ -511,6 +617,9 @@
|
|
|
511
617
|
</div>
|
|
512
618
|
{/if}
|
|
513
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>
|
|
514
623
|
<div class="sr" aria-live="polite">{announce}</div>
|
|
515
624
|
|
|
516
625
|
<div class="controls" role="toolbar" aria-label="Map controls">
|
|
@@ -519,26 +628,29 @@
|
|
|
519
628
|
<Button variant="minimal" intent="neutral" size="sm" icon="expand" aria-label="Fit to data" onclick={() => ctl?.fit()} />
|
|
520
629
|
{#if toolbar}{@render toolbar()}{/if}
|
|
521
630
|
</div>
|
|
522
|
-
{#if legend && (legendInfo.size || legendInfo.color)}
|
|
523
|
-
{@const lg = legendInfo}
|
|
631
|
+
{#if legend && (legendInfo.size || legendInfo.color || legendInfo.clusterSize || legendInfo.clusterColor || legendInfo.heatmap)}
|
|
524
632
|
<div class="legend" role="group" aria-label="Legend">
|
|
525
|
-
{#
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
<div class="
|
|
538
|
-
|
|
539
|
-
|
|
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}
|
|
540
652
|
{/if}
|
|
541
|
-
{/
|
|
653
|
+
{/each}
|
|
542
654
|
</div>
|
|
543
655
|
{/if}
|
|
544
656
|
{#if failed}<div class="err" role="alert">Map failed to load: {failed}</div>{/if}
|
|
@@ -558,6 +670,8 @@
|
|
|
558
670
|
.kv { display: grid; grid-template-columns: auto 1fr; gap: 2px 10px; margin: 6px 0 0; font-size: var(--tr-text-sm); }
|
|
559
671
|
.kv dt { color: var(--tr-on-surface-variant); }
|
|
560
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; }
|
|
561
675
|
.sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
|
|
562
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; }
|
|
563
677
|
.x:hover { background: var(--tr-surface-container-highest); }
|
package/dist/Map.svelte.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { type Snippet } from 'svelte';
|
|
2
2
|
import 'ol/ol.css';
|
|
3
3
|
import type { Basemap, FitOptions, FitTarget, MapApi, MapFeatureInfo, MapMarker, MapSelection, MapViewState } from './types.js';
|
|
4
|
-
import { type FeatureStyle, type HeatmapOptions, type MapStyle, type PointsInput, type PointsMode, type Props } from './util.js';
|
|
4
|
+
import { type ClusterStyle, type FeatureStyle, type HeatmapOptions, type MapStyle, type PointsInput, type PointsMode, type Props } from './util.js';
|
|
5
5
|
type $$ComponentProps = {
|
|
6
6
|
/** [lon, lat] */
|
|
7
7
|
center?: [number, number];
|
|
@@ -32,7 +32,32 @@ type $$ComponentProps = {
|
|
|
32
32
|
* 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).
|
|
33
33
|
*/
|
|
34
34
|
style?: MapStyle;
|
|
35
|
-
/**
|
|
35
|
+
/**
|
|
36
|
+
* Style the clusters of `pointsMode: 'cluster'` from aggregates of their members: `size` and `color` each take `{ by, range, domain, scale, stops, title, format }`
|
|
37
|
+
* 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.
|
|
38
|
+
* Without it clusters grow with the log of their count in the primary colour.
|
|
39
|
+
*/
|
|
40
|
+
clusterStyle?: ClusterStyle;
|
|
41
|
+
/**
|
|
42
|
+
* 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.
|
|
43
|
+
* Wins over `properties.id`. Ids must be unique. Without it ids are `id`/`properties.id`, else `pt:<n>` / `geo:<n>`.
|
|
44
|
+
*/
|
|
45
|
+
idBy?: string | ((properties: Props, index: number) => string | number | undefined);
|
|
46
|
+
/**
|
|
47
|
+
* Draw labels (`featureStyle`'s `label`, `title`) with OpenLayers' decluttering: where labels would overlap only the first is drawn, while the points themselves always show.
|
|
48
|
+
* Default false.
|
|
49
|
+
*/
|
|
50
|
+
declutter?: boolean;
|
|
51
|
+
/** Draw labels only from this zoom level up. */
|
|
52
|
+
labelMinZoom?: number;
|
|
53
|
+
/**
|
|
54
|
+
* 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.
|
|
55
|
+
* 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.
|
|
56
|
+
*/
|
|
57
|
+
tooltip?: boolean | ((feature: MapFeatureInfo) => string | undefined);
|
|
58
|
+
/** Custom tooltip content (implies `tooltip`). */
|
|
59
|
+
featureTooltip?: Snippet<[feature: MapFeatureInfo]>;
|
|
60
|
+
/** 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`. */
|
|
36
61
|
legend?: boolean;
|
|
37
62
|
/**
|
|
38
63
|
* Per-feature GeoJSON styling by function: receives the feature's properties and returns any of `fill`, `opacity`, `stroke`,
|
package/dist/index.d.ts
CHANGED
|
@@ -4,6 +4,6 @@ export { default as Compass } from './Compass.svelte';
|
|
|
4
4
|
export { default as ScaleBar } from './ScaleBar.svelte';
|
|
5
5
|
export { default as Attribution } from './Attribution.svelte';
|
|
6
6
|
export type { MapMarker, MarkerKind, Basemap, MapSelection, MapFeatureInfo, MapViewState, FitOptions, FitTarget, MapApi } from './types.js';
|
|
7
|
-
export type { MapStyle, SizeSpec, ColorSpec, FeatureStyle, LegendInfo } from './style.js';
|
|
7
|
+
export type { MapStyle, SizeSpec, ColorSpec, FeatureStyle, LegendInfo, ClusterStyle, ClusterSizeSpec, ClusterColorSpec, ClusterBy, ClusterAgg, ClusterInfo } from './style.js';
|
|
8
8
|
export type { PointsInput, PointInput, PointsMode, HeatmapOptions } from './points.js';
|
|
9
9
|
export type { ControlPosition, ScaleUnit, HeadingStatus } from './util.js';
|
package/dist/points.d.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* clusters and the heatmap. Points live in typed arrays (no per-point OpenLayers objects), so a million points cost
|
|
4
4
|
* a few tens of MB and one pass over the arrays per view change.
|
|
5
5
|
*/
|
|
6
|
-
import type { Props } from './style.js';
|
|
6
|
+
import type { ClusterStat, Props } from './style.js';
|
|
7
7
|
export type PointInput = {
|
|
8
8
|
lon: number;
|
|
9
9
|
lat: number;
|
|
@@ -33,6 +33,8 @@ export type HeatmapOptions = {
|
|
|
33
33
|
weightBy?: string;
|
|
34
34
|
/** Colours low to high. Default: the sequential chart ramp. */
|
|
35
35
|
gradient?: string[];
|
|
36
|
+
/** Legend heading. Default: `weightBy`, else `Density`. */
|
|
37
|
+
title?: string;
|
|
36
38
|
};
|
|
37
39
|
/** Extent in EPSG:3857 metres, `[minX, minY, maxX, maxY]`. */
|
|
38
40
|
export type Extent = [number, number, number, number];
|
|
@@ -78,12 +80,19 @@ export type Cell = {
|
|
|
78
80
|
index: number;
|
|
79
81
|
/** Extent of the members. */
|
|
80
82
|
bbox: Extent;
|
|
83
|
+
/** Stats of the requested numeric properties over the members (see `aggregate`'s `values`). */
|
|
84
|
+
stats?: Record<string, ClusterStat>;
|
|
81
85
|
};
|
|
86
|
+
/** A property's numeric value per point (`NaN` where it isn't a number), for cluster aggregates. */
|
|
87
|
+
export declare function numbersOf(store: PointStore, by: string): Float64Array;
|
|
88
|
+
export declare const newStat: () => ClusterStat;
|
|
89
|
+
/** Folds a value into running stats; non-finite values are ignored. */
|
|
90
|
+
export declare function addStat(s: ClusterStat, v: number): void;
|
|
82
91
|
/**
|
|
83
92
|
* Bins the points inside `extent` into square cells of `cell` metres, aligned to a global grid so cells stay put while
|
|
84
93
|
* panning. Returns one {@link Cell} per occupied bin. If the extent would need more than {@link MAX_CELLS} cells the cell size doubles until it fits.
|
|
85
94
|
*/
|
|
86
|
-
export declare function aggregate(store: PointStore, extent: Extent, cell: number, weights?: Float64Array): Cell[];
|
|
95
|
+
export declare function aggregate(store: PointStore, extent: Extent, cell: number, weights?: Float64Array, values?: Record<string, Float64Array>): Cell[];
|
|
87
96
|
/** Radius (px) of a cluster circle for `count` members: grows with the logarithm of the count, capped. */
|
|
88
97
|
export declare function clusterRadius(count: number): number;
|
|
89
98
|
/** `count` as a short label: `42`, `1.2k`, `35k`, `1.2M`. */
|
package/dist/points.js
CHANGED
|
@@ -85,11 +85,32 @@ export function weightsOf(store, by) {
|
|
|
85
85
|
}
|
|
86
86
|
return w;
|
|
87
87
|
}
|
|
88
|
+
/** A property's numeric value per point (`NaN` where it isn't a number), for cluster aggregates. */
|
|
89
|
+
export function numbersOf(store, by) {
|
|
90
|
+
const w = new Float64Array(store.n);
|
|
91
|
+
for (let i = 0; i < store.n; i++) {
|
|
92
|
+
const v = store.props[i][by];
|
|
93
|
+
w[i] = typeof v === 'number' || (typeof v === 'string' && v.trim() !== '') ? Number(v) : NaN;
|
|
94
|
+
}
|
|
95
|
+
return w;
|
|
96
|
+
}
|
|
97
|
+
export const newStat = () => ({ sum: 0, min: Infinity, max: -Infinity, n: 0 });
|
|
98
|
+
/** Folds a value into running stats; non-finite values are ignored. */
|
|
99
|
+
export function addStat(s, v) {
|
|
100
|
+
if (!Number.isFinite(v))
|
|
101
|
+
return;
|
|
102
|
+
s.sum += v;
|
|
103
|
+
s.n++;
|
|
104
|
+
if (v < s.min)
|
|
105
|
+
s.min = v;
|
|
106
|
+
if (v > s.max)
|
|
107
|
+
s.max = v;
|
|
108
|
+
}
|
|
88
109
|
/**
|
|
89
110
|
* Bins the points inside `extent` into square cells of `cell` metres, aligned to a global grid so cells stay put while
|
|
90
111
|
* panning. Returns one {@link Cell} per occupied bin. If the extent would need more than {@link MAX_CELLS} cells the cell size doubles until it fits.
|
|
91
112
|
*/
|
|
92
|
-
export function aggregate(store, extent, cell, weights) {
|
|
113
|
+
export function aggregate(store, extent, cell, weights, values) {
|
|
93
114
|
let size = cell;
|
|
94
115
|
const dims = () => {
|
|
95
116
|
const x0 = Math.floor(extent[0] / size), y0 = Math.floor(extent[1] / size);
|
|
@@ -102,6 +123,7 @@ export function aggregate(store, extent, cell, weights) {
|
|
|
102
123
|
}
|
|
103
124
|
const grid = new Int32Array(d.w * d.h);
|
|
104
125
|
const cells = [];
|
|
126
|
+
const keys = values ? Object.keys(values) : [];
|
|
105
127
|
const { x, y } = store;
|
|
106
128
|
for (let i = 0; i < store.n; i++) {
|
|
107
129
|
const px = x[i], py = y[i];
|
|
@@ -110,7 +132,13 @@ export function aggregate(store, extent, cell, weights) {
|
|
|
110
132
|
const g = (Math.floor(py / size) - d.y0) * d.w + Math.floor(px / size) - d.x0;
|
|
111
133
|
const k = grid[g], wt = weights ? weights[i] : 1;
|
|
112
134
|
if (k === 0) {
|
|
113
|
-
|
|
135
|
+
const cell = { x: px, y: py, count: 1, weight: wt, index: i, bbox: [px, py, px, py] };
|
|
136
|
+
if (keys.length) {
|
|
137
|
+
cell.stats = {};
|
|
138
|
+
for (const k of keys)
|
|
139
|
+
addStat(cell.stats[k] = newStat(), values[k][i]);
|
|
140
|
+
}
|
|
141
|
+
cells.push(cell);
|
|
114
142
|
grid[g] = cells.length;
|
|
115
143
|
}
|
|
116
144
|
else {
|
|
@@ -119,6 +147,9 @@ export function aggregate(store, extent, cell, weights) {
|
|
|
119
147
|
c.y += py;
|
|
120
148
|
c.count++;
|
|
121
149
|
c.weight += wt;
|
|
150
|
+
if (c.stats)
|
|
151
|
+
for (const k of keys)
|
|
152
|
+
addStat(c.stats[k], values[k][i]);
|
|
122
153
|
if (px < b[0])
|
|
123
154
|
b[0] = px;
|
|
124
155
|
else if (px > b[2])
|
package/dist/style.d.ts
CHANGED
|
@@ -17,7 +17,11 @@ export type SizeSpec = {
|
|
|
17
17
|
/** Input values mapped to the ends of `range`. Default: the data's min and max. Values outside are clamped. */
|
|
18
18
|
domain?: [number, number];
|
|
19
19
|
/** `sqrt` makes the marker's area, not its radius, proportional to the value. Default `linear`. */
|
|
20
|
-
scale?: 'linear' | 'sqrt';
|
|
20
|
+
scale?: 'linear' | 'sqrt' | 'log';
|
|
21
|
+
/** Legend heading. Default: the property name. */
|
|
22
|
+
title?: string;
|
|
23
|
+
/** Legend value formatter, e.g. `(v) => v.toFixed(1)`. Default: a short plain number. */
|
|
24
|
+
format?: (value: number) => string;
|
|
21
25
|
};
|
|
22
26
|
/** Colour from a property: a numeric ramp from the chart palette, or categories in the chart's series colours. */
|
|
23
27
|
export type ColorSpec = {
|
|
@@ -33,6 +37,56 @@ export type ColorSpec = {
|
|
|
33
37
|
categories?: string[];
|
|
34
38
|
/** Your own colours, low to high (numeric scales) or one per category, replacing the chart palette. Any CSS hex colour. */
|
|
35
39
|
stops?: string[];
|
|
40
|
+
/** Legend heading. Default: the property name. */
|
|
41
|
+
title?: string;
|
|
42
|
+
/** Legend value formatter for numeric scales (the ends of the ramp). Default: a short plain number. */
|
|
43
|
+
format?: (value: number) => string;
|
|
44
|
+
};
|
|
45
|
+
/** An aggregate over a cluster's members: their `count`, or the `sum`, `mean`, `min` or `max` of a numeric property. */
|
|
46
|
+
export type ClusterAgg = 'count' | 'sum' | 'mean' | 'min' | 'max';
|
|
47
|
+
/** What a cluster is sized or coloured by: `'count'` (or `{ agg: 'count' }`), or `{ agg, prop }` over a numeric property. */
|
|
48
|
+
export type ClusterBy = 'count' | {
|
|
49
|
+
agg: ClusterAgg;
|
|
50
|
+
prop?: string;
|
|
51
|
+
};
|
|
52
|
+
export type ClusterSizeSpec = {
|
|
53
|
+
by: ClusterBy;
|
|
54
|
+
/** Output radii `[min, max]` in px. Default `[10, 32]`. */
|
|
55
|
+
range?: [number, number];
|
|
56
|
+
/** Aggregate values mapped to the ends of `range`. Default: derived from the whole data set, so sizes stay put while panning. */
|
|
57
|
+
domain?: [number, number];
|
|
58
|
+
/** Default `log` for `count` and `sum` (they span orders of magnitude), `linear` otherwise. */
|
|
59
|
+
scale?: 'linear' | 'sqrt' | 'log';
|
|
60
|
+
title?: string;
|
|
61
|
+
format?: (value: number) => string;
|
|
62
|
+
};
|
|
63
|
+
export type ClusterColorSpec = {
|
|
64
|
+
by: ClusterBy;
|
|
65
|
+
/** Colours low to high. Default: the sequential chart ramp. */
|
|
66
|
+
stops?: string[];
|
|
67
|
+
domain?: [number, number];
|
|
68
|
+
/** Default `log` for `count` and `sum`, `linear` otherwise. */
|
|
69
|
+
scale?: 'linear' | 'sqrt' | 'log';
|
|
70
|
+
title?: string;
|
|
71
|
+
format?: (value: number) => string;
|
|
72
|
+
};
|
|
73
|
+
/** Styling of clusters (`pointsMode: 'cluster'`) from aggregates of their members. Without it clusters grow with the log of their count in the primary colour. */
|
|
74
|
+
export type ClusterStyle = {
|
|
75
|
+
size?: ClusterSizeSpec | number;
|
|
76
|
+
color?: ClusterColorSpec | string;
|
|
77
|
+
opacity?: number;
|
|
78
|
+
};
|
|
79
|
+
/** Sum, min, max and number of numeric values of one property over a cluster's members. */
|
|
80
|
+
export type ClusterStat = {
|
|
81
|
+
sum: number;
|
|
82
|
+
min: number;
|
|
83
|
+
max: number;
|
|
84
|
+
n: number;
|
|
85
|
+
};
|
|
86
|
+
/** What a cluster knows about its members: how many, and the stats of the properties the cluster style needs. */
|
|
87
|
+
export type ClusterInfo = {
|
|
88
|
+
count: number;
|
|
89
|
+
stats?: Record<string, ClusterStat>;
|
|
36
90
|
};
|
|
37
91
|
/** Data-driven styling for points and GeoJSON features. Each of `size` and `color` takes a spec, a constant, or a function of the feature's properties. */
|
|
38
92
|
export type MapStyle = {
|
|
@@ -41,26 +95,37 @@ export type MapStyle = {
|
|
|
41
95
|
/** Fill opacity 0 to 1. Default 0.85 for points, 0.14 for shapes. */
|
|
42
96
|
opacity?: number;
|
|
43
97
|
};
|
|
98
|
+
export type LegendSize = {
|
|
99
|
+
by: string;
|
|
100
|
+
title: string;
|
|
101
|
+
domain: [number, number];
|
|
102
|
+
range: [number, number];
|
|
103
|
+
steps: {
|
|
104
|
+
value: number;
|
|
105
|
+
radius: number;
|
|
106
|
+
label: string;
|
|
107
|
+
}[];
|
|
108
|
+
};
|
|
109
|
+
export type LegendColor = {
|
|
110
|
+
by: string;
|
|
111
|
+
title: string;
|
|
112
|
+
scale: 'sequential' | 'diverging' | 'categorical';
|
|
113
|
+
domain?: [number, number];
|
|
114
|
+
labels?: [string, string];
|
|
115
|
+
gradient?: string;
|
|
116
|
+
categories?: {
|
|
117
|
+
label: string;
|
|
118
|
+
color: string;
|
|
119
|
+
}[];
|
|
120
|
+
};
|
|
44
121
|
export type LegendInfo = {
|
|
45
|
-
size?:
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
}[];
|
|
53
|
-
};
|
|
54
|
-
color?: {
|
|
55
|
-
by: string;
|
|
56
|
-
scale: 'sequential' | 'diverging' | 'categorical';
|
|
57
|
-
domain?: [number, number];
|
|
58
|
-
gradient?: string;
|
|
59
|
-
categories?: {
|
|
60
|
-
label: string;
|
|
61
|
-
color: string;
|
|
62
|
-
}[];
|
|
63
|
-
};
|
|
122
|
+
size?: LegendSize;
|
|
123
|
+
color?: LegendColor;
|
|
124
|
+
/** Legend for cluster size / colour (aggregates). */
|
|
125
|
+
clusterSize?: LegendSize;
|
|
126
|
+
clusterColor?: LegendColor;
|
|
127
|
+
/** Heatmap ramp, low to high density. */
|
|
128
|
+
heatmap?: LegendColor;
|
|
64
129
|
};
|
|
65
130
|
/** The ramps used when the chart tokens are not defined; they match `charts.css` in light mode. */
|
|
66
131
|
export declare const DEFAULT_PALETTES: Palettes;
|
|
@@ -77,7 +142,7 @@ export declare function cssGradient(stops: string[]): string;
|
|
|
77
142
|
/** `[min, max]` of the finite numbers among `values` (numeric strings count), or `undefined` when there are none. */
|
|
78
143
|
export declare function extentOf(values: Iterable<unknown>): [number, number] | undefined;
|
|
79
144
|
/** A function from a value to `range`: linear, or `sqrt` for area-proportional symbols. Clamped to the domain; a flat domain maps to the middle of the range; `NaN` maps to the low end. */
|
|
80
|
-
export declare function scaleOf(domain: [number, number], range: [number, number], kind?: 'linear' | 'sqrt'): (v: number) => number;
|
|
145
|
+
export declare function scaleOf(domain: [number, number], range: [number, number], kind?: 'linear' | 'sqrt' | 'log'): (v: number) => number;
|
|
81
146
|
/** Distinct values of `by` in order of appearance. */
|
|
82
147
|
export declare function categoriesOf(rows: Iterable<Props>, by: string): string[];
|
|
83
148
|
export type Compiled = {
|
|
@@ -117,3 +182,23 @@ export declare function propertyStyle(p: Props): FeatureStyle;
|
|
|
117
182
|
export declare function featureTitle(p: Props): string;
|
|
118
183
|
/** The properties a default popup lists: at most `max` entries, without styling keys, empty values and internals; objects as JSON. */
|
|
119
184
|
export declare function popupEntries(p: Props, max?: number): [string, string][];
|
|
185
|
+
/** The value of a cluster aggregate: its member count, or the sum/mean/min/max of `prop` over its numeric members (`NaN` when it has none). */
|
|
186
|
+
export declare function clusterValue(by: ClusterBy, c: ClusterInfo): number;
|
|
187
|
+
/** Properties whose stats a cluster style needs (so clusters collect only those). */
|
|
188
|
+
export declare function clusterProps(cs: ClusterStyle | undefined): string[];
|
|
189
|
+
export type CompiledCluster = {
|
|
190
|
+
/** Radius in px for a cluster, or `undefined` for the default (grows with the log of the count). */
|
|
191
|
+
size?: (c: ClusterInfo) => number;
|
|
192
|
+
/** Fill colour for a cluster, or `undefined` for the primary colour. */
|
|
193
|
+
color?: (c: ClusterInfo) => string;
|
|
194
|
+
opacity?: number;
|
|
195
|
+
legend: Pick<LegendInfo, 'clusterSize' | 'clusterColor'>;
|
|
196
|
+
};
|
|
197
|
+
/**
|
|
198
|
+
* Compiles a cluster style. `rows` are the point set's property objects, read once to find the default domains
|
|
199
|
+
* (the data's own extent of the aggregated property, `[2, n]` for count, `[min, total]` for sum), so a cluster keeps its
|
|
200
|
+
* size and colour while you pan and zoom.
|
|
201
|
+
*/
|
|
202
|
+
export declare function compileCluster(cs: ClusterStyle | undefined, rows: Props[], palettes?: Palettes): CompiledCluster;
|
|
203
|
+
/** Whether `color` is light enough that dark text reads on it. Colours that can't be parsed count as dark. */
|
|
204
|
+
export declare function isLight(color: string): boolean;
|
package/dist/style.js
CHANGED
|
@@ -61,7 +61,7 @@ export function scaleOf(domain, range, kind = 'linear') {
|
|
|
61
61
|
if (d1 === d0)
|
|
62
62
|
return (r0 + r1) / 2;
|
|
63
63
|
const t = Math.min(Math.max((v - d0) / (d1 - d0) || 0, 0), 1);
|
|
64
|
-
return r0 + (r1 - r0) * (kind === 'sqrt' ? Math.sqrt(t) : t);
|
|
64
|
+
return r0 + (r1 - r0) * (kind === 'sqrt' ? Math.sqrt(t) : kind === 'log' ? Math.log1p(t * (Math.E ** 4 - 1)) / 4 : t);
|
|
65
65
|
};
|
|
66
66
|
}
|
|
67
67
|
/** Distinct values of `by` in order of appearance. */
|
|
@@ -95,7 +95,8 @@ export function compileStyle(style, rows, palettes = DEFAULT_PALETTES) {
|
|
|
95
95
|
out.size = (p) => f(Number(p[sz.by]));
|
|
96
96
|
const mid = (domain[0] + domain[1]) / 2;
|
|
97
97
|
const values = domain[0] === domain[1] ? [domain[0]] : [domain[0], mid, domain[1]];
|
|
98
|
-
|
|
98
|
+
const fmt = sz.format ?? formatNumber;
|
|
99
|
+
out.legend.size = { by: sz.by, title: sz.title ?? sz.by, domain, range, steps: values.map((value) => ({ value, radius: f(value), label: fmt(value) })) };
|
|
99
100
|
}
|
|
100
101
|
const co = style.color;
|
|
101
102
|
if (typeof co === 'function')
|
|
@@ -109,7 +110,7 @@ export function compileStyle(style, rows, palettes = DEFAULT_PALETTES) {
|
|
|
109
110
|
const pal = co.stops ?? palettes.categorical;
|
|
110
111
|
const colorOf = (c) => { const i = cats.indexOf(c); return i < 0 || i >= pal.length ? palettes.other : pal[i]; };
|
|
111
112
|
out.color = (p) => colorOf(String(p[co.by]));
|
|
112
|
-
out.legend.color = { by: co.by, scale, categories: cats.map((label) => ({ label, color: colorOf(label) })) };
|
|
113
|
+
out.legend.color = { by: co.by, title: co.title ?? co.by, scale, categories: cats.map((label) => ({ label, color: colorOf(label) })) };
|
|
113
114
|
}
|
|
114
115
|
else {
|
|
115
116
|
const stops = co.stops && co.stops.length > 1 ? co.stops : scale === 'diverging' ? palettes.diverging : palettes.sequential;
|
|
@@ -124,7 +125,8 @@ export function compileStyle(style, rows, palettes = DEFAULT_PALETTES) {
|
|
|
124
125
|
return v < mid ? (0.5 * (v - domain[0])) / (mid - domain[0]) : domain[1] === mid ? 0.5 : 0.5 + (0.5 * (v - mid)) / (domain[1] - mid);
|
|
125
126
|
};
|
|
126
127
|
out.color = (p) => rampColor(stops, t(Number(p[co.by])));
|
|
127
|
-
|
|
128
|
+
const fmt = co.format ?? formatNumber;
|
|
129
|
+
out.legend.color = { by: co.by, title: co.title ?? co.by, scale, domain, labels: [fmt(domain[0]), fmt(domain[1])], gradient: cssGradient(stops) };
|
|
128
130
|
}
|
|
129
131
|
}
|
|
130
132
|
return out;
|
|
@@ -162,3 +164,82 @@ export function popupEntries(p, max = 8) {
|
|
|
162
164
|
}
|
|
163
165
|
return out;
|
|
164
166
|
}
|
|
167
|
+
/** The value of a cluster aggregate: its member count, or the sum/mean/min/max of `prop` over its numeric members (`NaN` when it has none). */
|
|
168
|
+
export function clusterValue(by, c) {
|
|
169
|
+
const agg = by === 'count' ? 'count' : by.agg;
|
|
170
|
+
if (agg === 'count')
|
|
171
|
+
return c.count;
|
|
172
|
+
const st = c.stats?.[by.prop ?? ''];
|
|
173
|
+
if (!st || !st.n)
|
|
174
|
+
return NaN;
|
|
175
|
+
return agg === 'sum' ? st.sum : agg === 'mean' ? st.sum / st.n : agg === 'min' ? st.min : st.max;
|
|
176
|
+
}
|
|
177
|
+
const byProp = (by) => (by === 'count' ? undefined : by.agg === 'count' ? undefined : by.prop);
|
|
178
|
+
const byLabel = (by) => (by === 'count' || by.agg === 'count' ? 'Count' : `${by.agg[0].toUpperCase()}${by.agg.slice(1)} ${by.prop}`);
|
|
179
|
+
/** Properties whose stats a cluster style needs (so clusters collect only those). */
|
|
180
|
+
export function clusterProps(cs) {
|
|
181
|
+
const out = new Set();
|
|
182
|
+
for (const s of [cs?.size, cs?.color])
|
|
183
|
+
if (s && typeof s === 'object') {
|
|
184
|
+
const p = byProp(s.by);
|
|
185
|
+
if (p)
|
|
186
|
+
out.add(p);
|
|
187
|
+
}
|
|
188
|
+
return [...out];
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Compiles a cluster style. `rows` are the point set's property objects, read once to find the default domains
|
|
192
|
+
* (the data's own extent of the aggregated property, `[2, n]` for count, `[min, total]` for sum), so a cluster keeps its
|
|
193
|
+
* size and colour while you pan and zoom.
|
|
194
|
+
*/
|
|
195
|
+
export function compileCluster(cs, rows, palettes = DEFAULT_PALETTES) {
|
|
196
|
+
const out = { opacity: cs?.opacity, legend: {} };
|
|
197
|
+
if (!cs)
|
|
198
|
+
return out;
|
|
199
|
+
const domainOf = (by, given) => {
|
|
200
|
+
if (given)
|
|
201
|
+
return given;
|
|
202
|
+
const prop = byProp(by);
|
|
203
|
+
if (!prop)
|
|
204
|
+
return [2, Math.max(rows.length, 3)];
|
|
205
|
+
const e = extentOf(rows.map((r) => r[prop])) ?? [0, 1];
|
|
206
|
+
if (by !== 'count' && by.agg === 'sum') {
|
|
207
|
+
let t = 0;
|
|
208
|
+
for (const r of rows) {
|
|
209
|
+
const v = Number(r[prop]);
|
|
210
|
+
if (Number.isFinite(v))
|
|
211
|
+
t += v;
|
|
212
|
+
}
|
|
213
|
+
return [Math.min(e[0], t), t];
|
|
214
|
+
}
|
|
215
|
+
return e;
|
|
216
|
+
};
|
|
217
|
+
const kindOf = (by, k) => k ?? (by === 'count' || by.agg === 'count' || by.agg === 'sum' ? 'log' : 'linear');
|
|
218
|
+
const sz = cs.size;
|
|
219
|
+
if (typeof sz === 'number')
|
|
220
|
+
out.size = () => sz;
|
|
221
|
+
else if (sz) {
|
|
222
|
+
const range = sz.range ?? [10, 32], domain = domainOf(sz.by, sz.domain), kind = kindOf(sz.by, sz.scale), f = scaleOf(domain, range, kind);
|
|
223
|
+
out.size = (c) => f(clusterValue(sz.by, c));
|
|
224
|
+
const mid = kind === 'log' ? domain[0] + (domain[1] - domain[0]) * 0.1 : (domain[0] + domain[1]) / 2;
|
|
225
|
+
const fmt = sz.format ?? formatNumber;
|
|
226
|
+
const values = domain[0] === domain[1] ? [domain[0]] : [domain[0], mid, domain[1]];
|
|
227
|
+
out.legend.clusterSize = { by: byLabel(sz.by), title: sz.title ?? byLabel(sz.by), domain, range, steps: values.map((value) => ({ value, radius: f(value), label: fmt(value) })) };
|
|
228
|
+
}
|
|
229
|
+
const co = cs.color;
|
|
230
|
+
if (typeof co === 'string')
|
|
231
|
+
out.color = () => co;
|
|
232
|
+
else if (co) {
|
|
233
|
+
const stops = co.stops && co.stops.length > 1 ? co.stops : palettes.sequential;
|
|
234
|
+
const domain = domainOf(co.by, co.domain), f = scaleOf(domain, [0, 1], kindOf(co.by, co.scale));
|
|
235
|
+
out.color = (c) => { const v = clusterValue(co.by, c); return rampColor(stops, Number.isFinite(v) ? f(v) : 0); };
|
|
236
|
+
const fmt = co.format ?? formatNumber;
|
|
237
|
+
out.legend.clusterColor = { by: byLabel(co.by), title: co.title ?? byLabel(co.by), scale: 'sequential', domain, labels: [fmt(domain[0]), fmt(domain[1])], gradient: cssGradient(stops) };
|
|
238
|
+
}
|
|
239
|
+
return out;
|
|
240
|
+
}
|
|
241
|
+
/** Whether `color` is light enough that dark text reads on it. Colours that can't be parsed count as dark. */
|
|
242
|
+
export function isLight(color) {
|
|
243
|
+
const c = parseColor(color);
|
|
244
|
+
return !!c && 0.299 * c[0] + 0.587 * c[1] + 0.114 * c[2] > 160;
|
|
245
|
+
}
|
package/dist/types.d.ts
CHANGED
|
@@ -27,13 +27,16 @@ export type MapSelection = {
|
|
|
27
27
|
} | {
|
|
28
28
|
type: 'feature';
|
|
29
29
|
id?: string | number;
|
|
30
|
-
properties: Record<string, unknown>;
|
|
30
|
+
properties: Record<string, unknown>; /** `Point`, `LineString`, `Polygon`, `MultiPolygon`, ... */
|
|
31
|
+
geometryType: string;
|
|
31
32
|
};
|
|
32
33
|
/** A GeoJSON or point feature as the popup and selection report it. */
|
|
33
34
|
export type MapFeatureInfo = {
|
|
34
|
-
/** The feature's `id` (GeoJSON `id`, `properties.id`, or a generated `geo:<n>` / `pt:<n>`). Selecting by it works through `selected`. */
|
|
35
|
+
/** The feature's `id` (GeoJSON `id`, `properties.id`, or what `idBy` returns, or a generated `geo:<n>` / `pt:<n>`). Selecting by it works through `selected`. */
|
|
35
36
|
id: string;
|
|
36
37
|
properties: Record<string, unknown>;
|
|
38
|
+
/** The GeoJSON geometry type: `Point` (all `points`), `MultiPoint`, `LineString`, `Polygon`, ... */
|
|
39
|
+
geometryType: string;
|
|
37
40
|
/** Where the popup is anchored. */
|
|
38
41
|
lonLat: [number, number];
|
|
39
42
|
};
|