@ruckc/truss-ol 1.28.0 → 1.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,7 @@
1
1
  import { type Snippet } from 'svelte';
2
2
  import 'ol/ol.css';
3
- import type { Basemap, MapMarker, MapSelection } from './types.js';
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
5
  type $$ComponentProps = {
5
6
  /** [lon, lat] */
6
7
  center?: [number, number];
@@ -9,17 +10,70 @@ type $$ComponentProps = {
9
10
  markers?: MapMarker[];
10
11
  /** GeoJSON FeatureCollection/Feature. Optional `properties.kind` picks the intent color. */
11
12
  geojson?: object;
12
- /** Selected marker id. */
13
+ /**
14
+ * A (large) point set: an array of `{ lon, lat, ...properties }` or a GeoJSON FeatureCollection of `Point`/`MultiPoint` features.
15
+ * Points with an invalid coordinate are skipped. Held in typed arrays, so 10^6 points are fine; pass a plain array
16
+ * (or `$state.raw`), not a deeply reactive `$state` proxy.
17
+ */
18
+ points?: PointsInput;
19
+ /**
20
+ * How `points` are drawn: `points` (every point, up to 100,000), `cluster` (circles with counts that split as you zoom in),
21
+ * `heatmap` (density), or `auto` (`points` up to 2,000, `cluster` beyond). Clusters of up to 20,000 points use OpenLayers'
22
+ * `Cluster` source; larger sets use an equivalent grid pass over typed arrays that stays fast at 10^6+ points.
23
+ */
24
+ pointsMode?: PointsMode;
25
+ /** Cluster cell size in px: points closer than this merge. Default 40. */
26
+ clusterDistance?: number;
27
+ /** Heatmap options: `radius`, `blur`, `weightBy` (a numeric property, summed per area) and `gradient`. */
28
+ heatmap?: HeatmapOptions;
29
+ /**
30
+ * Data-driven styling for `points` and `geojson` features. `size` maps a numeric property to a radius
31
+ * (`{ by, range, domain, scale }`) and `color` maps a property to the chart palette (`{ by, scale: 'sequential' | 'diverging' | 'categorical', domain, midpoint, categories, stops }`);
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
+ */
34
+ style?: MapStyle;
35
+ /** Show a legend for the `size` and `color` scales of `style`. */
36
+ legend?: boolean;
37
+ /**
38
+ * Per-feature GeoJSON styling by function: receives the feature's properties and returns any of `fill`, `opacity`, `stroke`,
39
+ * `strokeWidth`, `radius`, `label` (all optional). It wins over what the feature carries itself (a `style` property object or the
40
+ * simplestyle keys `fill`, `fill-opacity`, `stroke`, `stroke-width`, `marker-size`, `title`), which wins over `style` and `kind`.
41
+ */
42
+ featureStyle?: (properties: Props, feature: {
43
+ id: string | number | undefined;
44
+ type: string;
45
+ }) => FeatureStyle | undefined;
46
+ /** Id of the selected marker, GeoJSON feature (its `id`, `properties.id`, or `geo:<n>`) or point. Bindable; set it to select, `undefined` to clear. */
13
47
  selected?: string;
48
+ /** Map height: px, or any CSS length. Default 420. */
14
49
  height?: number | string;
15
- /** Fit the view to markers/features on first load. */
50
+ /** Fit the view to markers/features/points on first load (once the container has a size). */
16
51
  fitOnLoad?: boolean;
52
+ /** Fit the view again whenever `markers`, `geojson` or `points` change. Default false. */
53
+ fitOnDataChange?: boolean;
54
+ /** Re-measure the map when its container resizes (always), and also refit to the data. Default false. */
55
+ refitOnResize?: boolean;
56
+ /** Lowest zoom level the view allows. Default 1. */
57
+ minZoom?: number;
58
+ /** Highest zoom level the view allows (zoom buttons, wheel, clusters and `fit` all respect it). Default 19. */
59
+ maxZoom?: number;
17
60
  /** Custom popup body for the selected marker. */
18
61
  popup?: Snippet<[marker: MapMarker]>;
62
+ /** Custom popup body for a selected GeoJSON feature or point; without it the popup lists the feature's properties. */
63
+ featurePopup?: Snippet<[feature: MapFeatureInfo]>;
19
64
  /** Extra controls appended to the toolbar. */
20
65
  toolbar?: Snippet;
21
66
  onselect?: (s: MapSelection | null) => void;
67
+ /** Called once the map exists, with the imperative API (`map`, `fit`, `setView`, `getView`, `updateSize`). */
68
+ onready?: (api: MapApi) => void;
22
69
  };
23
- declare const Map: import("svelte").Component<$$ComponentProps, {}, "selected" | "center" | "zoom">;
70
+ declare const Map: import("svelte").Component<$$ComponentProps, {
71
+ fit: (target?: FitTarget, options?: FitOptions) => void;
72
+ setView: (v: Partial<Pick<MapViewState, "center" | "zoom">> & {
73
+ duration?: number;
74
+ }) => void;
75
+ getView: () => MapViewState | undefined;
76
+ updateSize: () => void;
77
+ }, "selected" | "center" | "zoom">;
24
78
  type Map = ReturnType<typeof Map>;
25
79
  export default Map;
package/dist/index.d.ts CHANGED
@@ -3,5 +3,7 @@ export { default as ZoomControl } from './ZoomControl.svelte';
3
3
  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
- export type { MapMarker, MarkerKind, Basemap, MapSelection } from './types.js';
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';
8
+ export type { PointsInput, PointInput, PointsMode, HeatmapOptions } from './points.js';
7
9
  export type { ControlPosition, ScaleUnit, HeadingStatus } from './util.js';
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Pure helpers for large point sets: input normalisation, validation, projection, and the grid aggregation behind
3
+ * clusters and the heatmap. Points live in typed arrays (no per-point OpenLayers objects), so a million points cost
4
+ * a few tens of MB and one pass over the arrays per view change.
5
+ */
6
+ import type { Props } from './style.js';
7
+ export type PointInput = {
8
+ lon: number;
9
+ lat: number;
10
+ [property: string]: unknown;
11
+ };
12
+ export type PointsGeoJSON = {
13
+ type: 'FeatureCollection';
14
+ features: {
15
+ type?: 'Feature';
16
+ properties?: Props | null;
17
+ geometry?: {
18
+ type: string;
19
+ coordinates?: unknown;
20
+ } | null;
21
+ }[];
22
+ };
23
+ /** A point set: an array of `{ lon, lat, ...properties }` or a GeoJSON FeatureCollection (`Point` and `MultiPoint` features are used). */
24
+ export type PointsInput = PointInput[] | PointsGeoJSON;
25
+ /** How a point set is drawn: individual points, clusters with counts, or a density heatmap. `auto` picks `points` up to {@link AUTO_CLUSTER_ABOVE} points and `cluster` beyond. */
26
+ export type PointsMode = 'auto' | 'points' | 'cluster' | 'heatmap';
27
+ export type HeatmapOptions = {
28
+ /** Blob radius in px. Default 8. */
29
+ radius?: number;
30
+ /** Blur in px. Default 12. */
31
+ blur?: number;
32
+ /** Property whose (non-negative) numeric value weights each point; every point weighs 1 when unset. */
33
+ weightBy?: string;
34
+ /** Colours low to high. Default: the sequential chart ramp. */
35
+ gradient?: string[];
36
+ };
37
+ /** Extent in EPSG:3857 metres, `[minX, minY, maxX, maxY]`. */
38
+ export type Extent = [number, number, number, number];
39
+ /** Point sets up to this size are drawn as individual points in `auto` mode. */
40
+ export declare const AUTO_CLUSTER_ABOVE = 2000;
41
+ /** `pointsMode="points"` draws at most this many points individually; larger sets cluster instead. */
42
+ export declare const POINTS_MAX = 100000;
43
+ /** Point sets up to this size are clustered by OpenLayers' own `Cluster` source; larger ones by the typed-array grid. */
44
+ export declare const NATIVE_CLUSTER_MAX = 20000;
45
+ /** Ceiling on the number of cells in a grid (memory bound for the aggregation). */
46
+ export declare const MAX_CELLS = 4000000;
47
+ export declare function validLonLat(lon: unknown, lat: unknown): boolean;
48
+ /** Web Mercator (EPSG:3857) metres for a lon/lat; latitude is clamped to the projection's limit. */
49
+ export declare function project(lon: number, lat: number): [number, number];
50
+ export declare function unproject(x: number, y: number): [number, number];
51
+ export type PointStore = {
52
+ n: number;
53
+ /** Projected coordinates. */
54
+ x: Float64Array;
55
+ y: Float64Array;
56
+ /** Property object per point (for plain arrays, the input objects themselves). */
57
+ props: Props[];
58
+ /** Input points dropped for having a coordinate outside lon -180..180 / lat -90..90 or not a number. */
59
+ skipped: number;
60
+ };
61
+ export declare const EMPTY_STORE: PointStore;
62
+ /** Reads a point set into typed arrays, dropping invalid coordinates. */
63
+ export declare function toStore(input: PointsInput | undefined | null): PointStore;
64
+ /** Extent of all points (EPSG:3857), or `undefined` for an empty set. */
65
+ export declare function storeExtent(store: PointStore): Extent | undefined;
66
+ /** The mode to draw `n` points in: `auto` resolves by size, and `points` falls back to `cluster` above {@link POINTS_MAX}. */
67
+ export declare function autoMode(n: number, mode?: PointsMode): Exclude<PointsMode, 'auto'>;
68
+ /** Non-negative numeric weight per point from a property (non-numbers weigh 0). Without `by`, `undefined`: every point weighs 1. */
69
+ export declare function weightsOf(store: PointStore, by?: string): Float64Array | undefined;
70
+ export type Cell = {
71
+ /** Mean position of the members (EPSG:3857). */
72
+ x: number;
73
+ y: number;
74
+ count: number;
75
+ /** Sum of the members' weights. */
76
+ weight: number;
77
+ /** Index of the first member (the only one when `count` is 1). */
78
+ index: number;
79
+ /** Extent of the members. */
80
+ bbox: Extent;
81
+ };
82
+ /**
83
+ * Bins the points inside `extent` into square cells of `cell` metres, aligned to a global grid so cells stay put while
84
+ * 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
+ */
86
+ export declare function aggregate(store: PointStore, extent: Extent, cell: number, weights?: Float64Array): Cell[];
87
+ /** Radius (px) of a cluster circle for `count` members: grows with the logarithm of the count, capped. */
88
+ export declare function clusterRadius(count: number): number;
89
+ /** `count` as a short label: `42`, `1.2k`, `35k`, `1.2M`. */
90
+ export declare function compactCount(count: number): string;
91
+ /** Lon/lat extent `[west, south, east, north]` of what `fit` accepts: an extent, `{ lon, lat }` points, or GeoJSON. `undefined` when it holds no valid position. */
92
+ export declare function lonLatExtent(target: unknown): [number, number, number, number] | undefined;
package/dist/points.js ADDED
@@ -0,0 +1,191 @@
1
+ /** Point sets up to this size are drawn as individual points in `auto` mode. */
2
+ export const AUTO_CLUSTER_ABOVE = 2000;
3
+ /** `pointsMode="points"` draws at most this many points individually; larger sets cluster instead. */
4
+ export const POINTS_MAX = 100_000;
5
+ /** Point sets up to this size are clustered by OpenLayers' own `Cluster` source; larger ones by the typed-array grid. */
6
+ export const NATIVE_CLUSTER_MAX = 20000;
7
+ /** Ceiling on the number of cells in a grid (memory bound for the aggregation). */
8
+ export const MAX_CELLS = 4_000_000;
9
+ const R = 6378137;
10
+ const MAX_LAT = 85.0511287798;
11
+ export function validLonLat(lon, lat) {
12
+ return typeof lon === 'number' && typeof lat === 'number' && lon >= -180 && lon <= 180 && lat >= -90 && lat <= 90;
13
+ }
14
+ /** Web Mercator (EPSG:3857) metres for a lon/lat; latitude is clamped to the projection's limit. */
15
+ export function project(lon, lat) {
16
+ const la = Math.min(Math.max(lat, -MAX_LAT), MAX_LAT) * (Math.PI / 180);
17
+ return [(lon * Math.PI * R) / 180, R * Math.log(Math.tan(Math.PI / 4 + la / 2))];
18
+ }
19
+ export function unproject(x, y) {
20
+ return [(x / R) * (180 / Math.PI), (2 * Math.atan(Math.exp(y / R)) - Math.PI / 2) * (180 / Math.PI)];
21
+ }
22
+ export const EMPTY_STORE = { n: 0, x: new Float64Array(0), y: new Float64Array(0), props: [], skipped: 0 };
23
+ /** Reads a point set into typed arrays, dropping invalid coordinates. */
24
+ export function toStore(input) {
25
+ if (!input)
26
+ return EMPTY_STORE;
27
+ const x = [], y = [], props = [];
28
+ let skipped = 0;
29
+ const add = (lon, lat, p) => {
30
+ if (!validLonLat(lon, lat)) {
31
+ skipped++;
32
+ return;
33
+ }
34
+ const [px, py] = project(lon, lat);
35
+ x.push(px);
36
+ y.push(py);
37
+ props.push(p);
38
+ };
39
+ if (Array.isArray(input))
40
+ for (const p of input)
41
+ add(p.lon, p.lat, p);
42
+ else
43
+ for (const f of input.features ?? []) {
44
+ const g = f.geometry, p = f.properties ?? {};
45
+ if (g?.type === 'Point')
46
+ add(g.coordinates[0], g.coordinates[1], p);
47
+ else if (g?.type === 'MultiPoint')
48
+ for (const c of g.coordinates)
49
+ add(c[0], c[1], p);
50
+ }
51
+ return { n: x.length, x: Float64Array.from(x), y: Float64Array.from(y), props, skipped };
52
+ }
53
+ /** Extent of all points (EPSG:3857), or `undefined` for an empty set. */
54
+ export function storeExtent(store) {
55
+ if (!store.n)
56
+ return undefined;
57
+ const e = [Infinity, Infinity, -Infinity, -Infinity];
58
+ for (let i = 0; i < store.n; i++) {
59
+ const x = store.x[i], y = store.y[i];
60
+ if (x < e[0])
61
+ e[0] = x;
62
+ if (x > e[2])
63
+ e[2] = x;
64
+ if (y < e[1])
65
+ e[1] = y;
66
+ if (y > e[3])
67
+ e[3] = y;
68
+ }
69
+ return e;
70
+ }
71
+ /** The mode to draw `n` points in: `auto` resolves by size, and `points` falls back to `cluster` above {@link POINTS_MAX}. */
72
+ export function autoMode(n, mode = 'auto') {
73
+ if (mode === 'auto')
74
+ return n > AUTO_CLUSTER_ABOVE ? 'cluster' : 'points';
75
+ return mode === 'points' && n > POINTS_MAX ? 'cluster' : mode;
76
+ }
77
+ /** Non-negative numeric weight per point from a property (non-numbers weigh 0). Without `by`, `undefined`: every point weighs 1. */
78
+ export function weightsOf(store, by) {
79
+ if (!by)
80
+ return undefined;
81
+ const w = new Float64Array(store.n);
82
+ for (let i = 0; i < store.n; i++) {
83
+ const v = Number(store.props[i][by]);
84
+ w[i] = v > 0 && isFinite(v) ? v : 0;
85
+ }
86
+ return w;
87
+ }
88
+ /**
89
+ * Bins the points inside `extent` into square cells of `cell` metres, aligned to a global grid so cells stay put while
90
+ * 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
+ */
92
+ export function aggregate(store, extent, cell, weights) {
93
+ let size = cell;
94
+ const dims = () => {
95
+ const x0 = Math.floor(extent[0] / size), y0 = Math.floor(extent[1] / size);
96
+ return { x0, y0, w: Math.floor(extent[2] / size) - x0 + 1, h: Math.floor(extent[3] / size) - y0 + 1 };
97
+ };
98
+ let d = dims();
99
+ while (d.w * d.h > MAX_CELLS) {
100
+ size *= 2;
101
+ d = dims();
102
+ }
103
+ const grid = new Int32Array(d.w * d.h);
104
+ const cells = [];
105
+ const { x, y } = store;
106
+ for (let i = 0; i < store.n; i++) {
107
+ const px = x[i], py = y[i];
108
+ if (px < extent[0] || px > extent[2] || py < extent[1] || py > extent[3])
109
+ continue;
110
+ const g = (Math.floor(py / size) - d.y0) * d.w + Math.floor(px / size) - d.x0;
111
+ const k = grid[g], wt = weights ? weights[i] : 1;
112
+ if (k === 0) {
113
+ cells.push({ x: px, y: py, count: 1, weight: wt, index: i, bbox: [px, py, px, py] });
114
+ grid[g] = cells.length;
115
+ }
116
+ else {
117
+ const c = cells[k - 1], b = c.bbox;
118
+ c.x += px;
119
+ c.y += py;
120
+ c.count++;
121
+ c.weight += wt;
122
+ if (px < b[0])
123
+ b[0] = px;
124
+ else if (px > b[2])
125
+ b[2] = px;
126
+ if (py < b[1])
127
+ b[1] = py;
128
+ else if (py > b[3])
129
+ b[3] = py;
130
+ }
131
+ }
132
+ for (const c of cells)
133
+ if (c.count > 1) {
134
+ c.x /= c.count;
135
+ c.y /= c.count;
136
+ }
137
+ return cells;
138
+ }
139
+ /** Radius (px) of a cluster circle for `count` members: grows with the logarithm of the count, capped. */
140
+ export function clusterRadius(count) {
141
+ return Math.min(10 + 7 * Math.log10(Math.max(count, 1)), 32);
142
+ }
143
+ /** `count` as a short label: `42`, `1.2k`, `35k`, `1.2M`. */
144
+ export function compactCount(count) {
145
+ if (count < 1000)
146
+ return String(count);
147
+ const [v, u] = count < 1e6 ? [count / 1e3, 'k'] : [count / 1e6, 'M'];
148
+ return `${v < 10 ? Math.round(v * 10) / 10 : Math.round(v)}${u}`;
149
+ }
150
+ /** Lon/lat extent `[west, south, east, north]` of what `fit` accepts: an extent, `{ lon, lat }` points, or GeoJSON. `undefined` when it holds no valid position. */
151
+ export function lonLatExtent(target) {
152
+ const out = [Infinity, Infinity, -Infinity, -Infinity];
153
+ const add = (lon, lat) => {
154
+ if (!validLonLat(lon, lat))
155
+ return;
156
+ out[0] = Math.min(out[0], lon);
157
+ out[1] = Math.min(out[1], lat);
158
+ out[2] = Math.max(out[2], lon);
159
+ out[3] = Math.max(out[3], lat);
160
+ };
161
+ const walk = (c) => { if (Array.isArray(c) && typeof c[0] === 'number')
162
+ add(c[0], c[1]);
163
+ else if (Array.isArray(c))
164
+ c.forEach(walk); };
165
+ const geo = (g) => {
166
+ if (!g)
167
+ return;
168
+ if (g.type === 'FeatureCollection')
169
+ g.features?.forEach(geo);
170
+ else if (g.type === 'Feature')
171
+ geo(g.geometry);
172
+ else if (g.type === 'GeometryCollection')
173
+ g.geometries?.forEach(geo);
174
+ else
175
+ walk(g.coordinates);
176
+ };
177
+ if (Array.isArray(target) && target.length === 4 && target.every((v) => typeof v === 'number')) {
178
+ add(target[0], target[1]);
179
+ add(target[2], target[3]);
180
+ }
181
+ else if (Array.isArray(target))
182
+ for (const p of target) {
183
+ if (p && 'lon' in p)
184
+ add(p.lon, p.lat);
185
+ else
186
+ geo(p);
187
+ }
188
+ else
189
+ geo(target);
190
+ return out[0] <= out[2] ? out : undefined;
191
+ }
@@ -0,0 +1,119 @@
1
+ /** Pure helpers for data-driven map styling: colour maths, scales, domains and the compiled style a layer calls per feature. */
2
+ export type Props = Record<string, unknown>;
3
+ export type Rgb = [number, number, number];
4
+ /** Palettes for colour scales, resolved from the truss chart tokens (`--trc-seq-*`, `--trc-div-*`, `--trc-s*`). */
5
+ export type Palettes = {
6
+ sequential: string[];
7
+ diverging: string[];
8
+ categorical: string[];
9
+ other: string;
10
+ };
11
+ /** Marker or point radius (px) from a numeric property. */
12
+ export type SizeSpec = {
13
+ /** Property name. */
14
+ by: string;
15
+ /** Output radii `[min, max]` in px. Default `[3, 14]`. */
16
+ range?: [number, number];
17
+ /** Input values mapped to the ends of `range`. Default: the data's min and max. Values outside are clamped. */
18
+ domain?: [number, number];
19
+ /** `sqrt` makes the marker's area, not its radius, proportional to the value. Default `linear`. */
20
+ scale?: 'linear' | 'sqrt';
21
+ };
22
+ /** Colour from a property: a numeric ramp from the chart palette, or categories in the chart's series colours. */
23
+ export type ColorSpec = {
24
+ /** Property name. */
25
+ by: string;
26
+ /** `sequential` (low to high), `diverging` (two poles around `midpoint`), or `categorical` (distinct values, series palette). Default: `sequential` for a numeric property, `categorical` otherwise. */
27
+ scale?: 'sequential' | 'diverging' | 'categorical';
28
+ /** Numeric scales: values mapped to the ends of the ramp. Default: the data's min and max. */
29
+ domain?: [number, number];
30
+ /** Diverging only: the value at the neutral centre. Default: the middle of `domain`. */
31
+ midpoint?: number;
32
+ /** Categorical only: the categories in palette order. Default: the distinct values in order of appearance. The ninth and later categories are neutral grey. */
33
+ categories?: string[];
34
+ /** Your own colours, low to high (numeric scales) or one per category, replacing the chart palette. Any CSS hex colour. */
35
+ stops?: string[];
36
+ };
37
+ /** 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
+ export type MapStyle = {
39
+ size?: SizeSpec | number | ((properties: Props) => number);
40
+ color?: ColorSpec | string | ((properties: Props) => string);
41
+ /** Fill opacity 0 to 1. Default 0.85 for points, 0.14 for shapes. */
42
+ opacity?: number;
43
+ };
44
+ export type LegendInfo = {
45
+ size?: {
46
+ by: string;
47
+ domain: [number, number];
48
+ range: [number, number];
49
+ steps: {
50
+ value: number;
51
+ radius: number;
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
+ };
64
+ };
65
+ /** The ramps used when the chart tokens are not defined; they match `charts.css` in light mode. */
66
+ export declare const DEFAULT_PALETTES: Palettes;
67
+ /** `#rgb`, `#rrggbb` or `rgb[a](r, g, b…)` to [r, g, b]; `undefined` for anything else (named colours, `var()`). */
68
+ export declare function parseColor(s: string): Rgb | undefined;
69
+ /** `color` with an alpha channel. A colour that can't be parsed is returned unchanged. */
70
+ export declare function withAlpha(color: string, a: number): string;
71
+ /** The colour at `t` (0 to 1, clamped) along evenly spaced `stops`, linearly interpolated in sRGB, as `#rrggbb`. */
72
+ export declare function rampColor(stops: string[], t: number): string;
73
+ /** A number for a legend: whole numbers and values from 100 up as is, others to 3 significant figures. */
74
+ export declare function formatNumber(v: number): string;
75
+ /** A CSS `linear-gradient` over `stops`, left to right. */
76
+ export declare function cssGradient(stops: string[]): string;
77
+ /** `[min, max]` of the finite numbers among `values` (numeric strings count), or `undefined` when there are none. */
78
+ export declare function extentOf(values: Iterable<unknown>): [number, number] | undefined;
79
+ /** 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;
81
+ /** Distinct values of `by` in order of appearance. */
82
+ export declare function categoriesOf(rows: Iterable<Props>, by: string): string[];
83
+ export type Compiled = {
84
+ /** Radius in px for a feature's properties, or `undefined` when no size is configured. */
85
+ size?: (p: Props) => number;
86
+ /** Colour for a feature's properties, or `undefined` when no colour is configured. */
87
+ color?: (p: Props) => string;
88
+ opacity?: number;
89
+ legend: LegendInfo;
90
+ };
91
+ /**
92
+ * Turns a style into per-feature functions. `rows` are the features' property objects, read once to find each
93
+ * spec's domain or categories (not when given, nor for function and constant forms).
94
+ */
95
+ export declare function compileStyle(style: MapStyle | undefined, rows: Iterable<Props>, palettes?: Palettes): Compiled;
96
+ /** Per-feature drawing overrides. Any field left out keeps the feature's default (or data-driven) look. */
97
+ export type FeatureStyle = {
98
+ /** Fill colour of polygons and points. */
99
+ fill?: string;
100
+ /** Fill opacity 0 to 1. */
101
+ opacity?: number;
102
+ /** Outline / line colour. */
103
+ stroke?: string;
104
+ /** Outline / line width in px. */
105
+ strokeWidth?: number;
106
+ /** Point radius in px. */
107
+ radius?: number;
108
+ /** Text drawn next to the feature. */
109
+ label?: string;
110
+ };
111
+ /**
112
+ * The style a GeoJSON feature carries in its own properties: a `style` object (`{ fill, opacity, stroke, strokeWidth, radius, label }`)
113
+ * and/or the simplestyle keys `fill`, `fill-opacity`, `stroke`, `stroke-width`, `marker-size` (a radius in px here) and `title`. A `style` object wins over simplestyle keys.
114
+ */
115
+ export declare function propertyStyle(p: Props): FeatureStyle;
116
+ /** A feature's heading for a popup: its `name`, `title`, `label`, or `id` property, else `Feature`. */
117
+ export declare function featureTitle(p: Props): string;
118
+ /** The properties a default popup lists: at most `max` entries, without styling keys, empty values and internals; objects as JSON. */
119
+ export declare function popupEntries(p: Props, max?: number): [string, string][];
package/dist/style.js ADDED
@@ -0,0 +1,164 @@
1
+ /** Pure helpers for data-driven map styling: colour maths, scales, domains and the compiled style a layer calls per feature. */
2
+ /** The ramps used when the chart tokens are not defined; they match `charts.css` in light mode. */
3
+ export const DEFAULT_PALETTES = {
4
+ sequential: ['#eaf3fe', '#c5ddfc', '#97c1f7', '#64a1ee', '#3a81d7', '#1d60ad', '#10427b'],
5
+ diverging: ['#11458c', '#3c79d1', '#94b9f1', '#f0eeeb', '#ebaf86', '#d26c28', '#993e02'],
6
+ categorical: ['#2a78d6', '#eb6834', '#1baf7a', '#eda100', '#e87ba4', '#008300', '#6250d6', '#e34948'],
7
+ other: '#888888'
8
+ };
9
+ /** `#rgb`, `#rrggbb` or `rgb[a](r, g, b…)` to [r, g, b]; `undefined` for anything else (named colours, `var()`). */
10
+ export function parseColor(s) {
11
+ const hex = /^#([0-9a-f]{6}|[0-9a-f]{3})(?![0-9a-f])/i.exec(s.trim());
12
+ if (hex) {
13
+ const h = hex[1].length === 3 ? hex[1].replace(/./g, '$&$&') : hex[1];
14
+ const n = parseInt(h, 16);
15
+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
16
+ }
17
+ const m = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/i.exec(s.trim());
18
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : undefined;
19
+ }
20
+ /** `color` with an alpha channel. A colour that can't be parsed is returned unchanged. */
21
+ export function withAlpha(color, a) {
22
+ const c = parseColor(color);
23
+ return c ? `rgba(${c[0]},${c[1]},${c[2]},${a})` : color;
24
+ }
25
+ /** The colour at `t` (0 to 1, clamped) along evenly spaced `stops`, linearly interpolated in sRGB, as `#rrggbb`. */
26
+ export function rampColor(stops, t) {
27
+ const rgb = stops.map((s) => parseColor(s) ?? [136, 136, 136]);
28
+ if (rgb.length === 1)
29
+ return toHex(rgb[0]);
30
+ const pos = Math.min(Math.max(Number.isFinite(t) ? t : 0, 0), 1) * (rgb.length - 1);
31
+ const i = Math.min(Math.floor(pos), rgb.length - 2), f = pos - i;
32
+ return toHex(rgb[i].map((v, k) => v + (rgb[i + 1][k] - v) * f));
33
+ }
34
+ const toHex = (c) => '#' + c.map((v) => Math.round(v).toString(16).padStart(2, '0')).join('');
35
+ /** A number for a legend: whole numbers and values from 100 up as is, others to 3 significant figures. */
36
+ export function formatNumber(v) {
37
+ return Number.isInteger(v) || Math.abs(v) >= 100 ? String(Math.round(v * 100) / 100) : String(Number(v.toPrecision(3)));
38
+ }
39
+ /** A CSS `linear-gradient` over `stops`, left to right. */
40
+ export function cssGradient(stops) {
41
+ return `linear-gradient(to right, ${stops.join(', ')})`;
42
+ }
43
+ /** `[min, max]` of the finite numbers among `values` (numeric strings count), or `undefined` when there are none. */
44
+ export function extentOf(values) {
45
+ let lo = Infinity, hi = -Infinity;
46
+ for (const v of values) {
47
+ const n = typeof v === 'number' ? v : typeof v === 'string' && v.trim() !== '' ? Number(v) : NaN;
48
+ if (!Number.isFinite(n))
49
+ continue;
50
+ if (n < lo)
51
+ lo = n;
52
+ if (n > hi)
53
+ hi = n;
54
+ }
55
+ return lo <= hi ? [lo, hi] : undefined;
56
+ }
57
+ /** 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. */
58
+ export function scaleOf(domain, range, kind = 'linear') {
59
+ const [d0, d1] = domain, [r0, r1] = range;
60
+ return (v) => {
61
+ if (d1 === d0)
62
+ return (r0 + r1) / 2;
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);
65
+ };
66
+ }
67
+ /** Distinct values of `by` in order of appearance. */
68
+ export function categoriesOf(rows, by) {
69
+ const seen = new Set();
70
+ for (const r of rows) {
71
+ const v = r[by];
72
+ if (v !== undefined && v !== null)
73
+ seen.add(String(v));
74
+ }
75
+ return [...seen];
76
+ }
77
+ /**
78
+ * Turns a style into per-feature functions. `rows` are the features' property objects, read once to find each
79
+ * spec's domain or categories (not when given, nor for function and constant forms).
80
+ */
81
+ export function compileStyle(style, rows, palettes = DEFAULT_PALETTES) {
82
+ const out = { opacity: style?.opacity, legend: {} };
83
+ if (!style)
84
+ return out;
85
+ const list = [...rows];
86
+ const sz = style.size;
87
+ if (typeof sz === 'function')
88
+ out.size = sz;
89
+ else if (typeof sz === 'number')
90
+ out.size = () => sz;
91
+ else if (sz) {
92
+ const range = sz.range ?? [3, 14];
93
+ const domain = sz.domain ?? extentOf(list.map((r) => r[sz.by])) ?? [0, 1];
94
+ const f = scaleOf(domain, range, sz.scale);
95
+ out.size = (p) => f(Number(p[sz.by]));
96
+ const mid = (domain[0] + domain[1]) / 2;
97
+ const values = domain[0] === domain[1] ? [domain[0]] : [domain[0], mid, domain[1]];
98
+ out.legend.size = { by: sz.by, domain, range, steps: values.map((value) => ({ value, radius: f(value) })) };
99
+ }
100
+ const co = style.color;
101
+ if (typeof co === 'function')
102
+ out.color = co;
103
+ else if (typeof co === 'string')
104
+ out.color = () => co;
105
+ else if (co) {
106
+ const scale = co.scale ?? (extentOf(list.map((r) => r[co.by])) ? 'sequential' : 'categorical');
107
+ if (scale === 'categorical') {
108
+ const cats = co.categories ?? categoriesOf(list, co.by);
109
+ const pal = co.stops ?? palettes.categorical;
110
+ const colorOf = (c) => { const i = cats.indexOf(c); return i < 0 || i >= pal.length ? palettes.other : pal[i]; };
111
+ 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
+ }
114
+ else {
115
+ const stops = co.stops && co.stops.length > 1 ? co.stops : scale === 'diverging' ? palettes.diverging : palettes.sequential;
116
+ const domain = co.domain ?? extentOf(list.map((r) => r[co.by])) ?? [0, 1];
117
+ const mid = co.midpoint ?? (domain[0] + domain[1]) / 2;
118
+ // a diverging scale spends half the ramp on each side of the midpoint; a flat side collapses onto the centre
119
+ const t = (v) => {
120
+ if (isNaN(v))
121
+ return 0;
122
+ if (scale === 'sequential')
123
+ return domain[1] === domain[0] ? 0.5 : (v - domain[0]) / (domain[1] - domain[0]);
124
+ 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
+ out.color = (p) => rampColor(stops, t(Number(p[co.by])));
127
+ out.legend.color = { by: co.by, scale, domain, gradient: cssGradient(stops) };
128
+ }
129
+ }
130
+ return out;
131
+ }
132
+ const SIMPLE = { fill: 'fill', 'fill-opacity': 'opacity', stroke: 'stroke', 'stroke-width': 'strokeWidth', 'marker-size': 'radius', title: 'label' };
133
+ /**
134
+ * The style a GeoJSON feature carries in its own properties: a `style` object (`{ fill, opacity, stroke, strokeWidth, radius, label }`)
135
+ * and/or the simplestyle keys `fill`, `fill-opacity`, `stroke`, `stroke-width`, `marker-size` (a radius in px here) and `title`. A `style` object wins over simplestyle keys.
136
+ */
137
+ export function propertyStyle(p) {
138
+ const out = {};
139
+ for (const [k, to] of Object.entries(SIMPLE))
140
+ if (p[k] !== undefined && p[k] !== null)
141
+ out[to] = p[k];
142
+ const s = p.style;
143
+ return s && typeof s === 'object' ? { ...out, ...s } : out;
144
+ }
145
+ /** A feature's heading for a popup: its `name`, `title`, `label`, or `id` property, else `Feature`. */
146
+ export function featureTitle(p) {
147
+ for (const k of ['name', 'title', 'label', 'id'])
148
+ if (p[k] !== undefined && p[k] !== null && p[k] !== '')
149
+ return String(p[k]);
150
+ return 'Feature';
151
+ }
152
+ /** The properties a default popup lists: at most `max` entries, without styling keys, empty values and internals; objects as JSON. */
153
+ export function popupEntries(p, max = 8) {
154
+ const skip = new Set(['geometry', 'style', 'kind', ...Object.keys(SIMPLE), '_cluster']);
155
+ const out = [];
156
+ for (const [k, v] of Object.entries(p)) {
157
+ if (skip.has(k) || v === undefined || v === null || v === '')
158
+ continue;
159
+ out.push([k, typeof v === 'object' ? JSON.stringify(v) : String(v)]);
160
+ if (out.length === max)
161
+ break;
162
+ }
163
+ return out;
164
+ }