@ruckc/truss-ol 1.57.0 → 1.58.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +69 -4
- package/dist/Map.svelte +96 -45
- package/dist/Map.svelte.d.ts +28 -1
- package/dist/basemaps.d.ts +106 -0
- package/dist/basemaps.js +50 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +2 -0
- package/dist/layers-ol.d.ts +47 -0
- package/dist/layers-ol.js +185 -0
- package/dist/ol-style.d.ts +71 -0
- package/dist/ol-style.js +107 -0
- package/dist/style.d.ts +27 -4
- package/dist/style.js +36 -7
- package/dist/types.d.ts +65 -10
- package/dist/util.d.ts +1 -0
- package/dist/util.js +1 -0
- package/package.json +7 -2
package/dist/basemaps.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/** Basemap descriptions (pure data, no OpenLayers): the `basemap` and `basemaps` props, their normalisation, and the Esri presets. */
|
|
2
|
+
const tile = (l, themed) => {
|
|
3
|
+
const osm = 'osm' in l && l.osm === true;
|
|
4
|
+
const t = l;
|
|
5
|
+
return { osm, url: osm ? undefined : t.url, attribution: l.attribution, maxZoom: l.maxZoom ?? 19, minZoom: osm ? undefined : t.minZoom, opacity: l.opacity, themed: l.themed ?? themed ?? osm };
|
|
6
|
+
};
|
|
7
|
+
/** The tile layers a basemap (or a `basemaps` entry) draws, bottom to top, or `'none'` for the graticule. Anything unrecognised draws nothing. */
|
|
8
|
+
export function basemapTiles(b) {
|
|
9
|
+
if (b === 'none' || (typeof b === 'object' && 'none' in b && b.none))
|
|
10
|
+
return 'none';
|
|
11
|
+
if (b === 'osm')
|
|
12
|
+
return [tile({ osm: true })];
|
|
13
|
+
if (!b || typeof b !== 'object')
|
|
14
|
+
return [];
|
|
15
|
+
if ('layers' in b)
|
|
16
|
+
return b.layers.map((l) => tile(l, b.themed));
|
|
17
|
+
if ('url' in b || 'osm' in b)
|
|
18
|
+
return [tile(b)];
|
|
19
|
+
return [];
|
|
20
|
+
}
|
|
21
|
+
/** The `basemaps` entry `id` names, else the first; `undefined` for an empty list. */
|
|
22
|
+
export function pickBasemap(list, id) {
|
|
23
|
+
return list?.find((b) => b.id === id) ?? list?.[0];
|
|
24
|
+
}
|
|
25
|
+
const ARC = 'https://server.arcgisonline.com/ArcGIS/rest/services';
|
|
26
|
+
const tiles = (service) => `${ARC}/${service}/MapServer/tile/{z}/{y}/{x}`;
|
|
27
|
+
const POWERED = 'Powered by <a href="https://www.esri.com" target="_blank" rel="noopener">Esri</a>';
|
|
28
|
+
// The credits are each service's own `copyrightText` (its REST endpoint, `?f=json`), as Esri asks them to be shown.
|
|
29
|
+
const IMAGERY = `${POWERED} | Source: Esri, Vantor, Earthstar Geographics, and the GIS User Community`;
|
|
30
|
+
const STREETS = `${POWERED} | Sources: Esri, HERE, Garmin, USGS, Intermap, INCREMENT P, NRCan, Esri Japan, METI, Esri China (Hong Kong), Esri Korea, Esri (Thailand), NGCC, © OpenStreetMap contributors, and the GIS User Community`;
|
|
31
|
+
const TOPO = `${POWERED} | Sources: Esri, HERE, Garmin, Intermap, increment P Corp., GEBCO, USGS, FAO, NPS, NRCAN, GeoBase, IGN, Kadaster NL, Ordnance Survey, Esri Japan, METI, Esri China (Hong Kong), © OpenStreetMap contributors, and the GIS User Community`;
|
|
32
|
+
const PLACES = `${POWERED} | Esri, HERE, Garmin, © OpenStreetMap contributors, and the GIS user community`;
|
|
33
|
+
/** Esri's place-name and boundary overlay (Reference/World_Boundaries_and_Places), to stack over imagery. */
|
|
34
|
+
export const esriLabels = { url: tiles('Reference/World_Boundaries_and_Places'), attribution: PLACES, maxZoom: 19 };
|
|
35
|
+
/**
|
|
36
|
+
* Esri ArcGIS Online basemaps as `basemaps` entries (each also works as `basemap`): World_Imagery, World_Street_Map, World_Topo_Map, and
|
|
37
|
+
* World_Imagery with the World_Boundaries_and_Places labels on top. Each carries the attribution Esri's service publishes. None is themed,
|
|
38
|
+
* so dark mode never inverts them.
|
|
39
|
+
*
|
|
40
|
+
* These are Esri's services, used under Esri's terms (the Esri Master License Agreement and the ArcGIS Online terms of use), not under this
|
|
41
|
+
* package's licence: the tiles load without an API key, but whether your use is allowed (commercial use, traffic, an ArcGIS account) is
|
|
42
|
+
* between you and Esri. Esri asks for the attribution to stay visible and does not allow bulk tile download or offline caching from these
|
|
43
|
+
* services. See https://goto.arcgisonline.com/maps/World_Imagery and the other services' pages.
|
|
44
|
+
*/
|
|
45
|
+
export const esriBasemaps = {
|
|
46
|
+
imagery: { id: 'esri-imagery', layers: [{ url: tiles('World_Imagery'), attribution: IMAGERY, maxZoom: 19 }] },
|
|
47
|
+
streets: { id: 'esri-streets', layers: [{ url: tiles('World_Street_Map'), attribution: STREETS, maxZoom: 19 }] },
|
|
48
|
+
topo: { id: 'esri-topo', layers: [{ url: tiles('World_Topo_Map'), attribution: TOPO, maxZoom: 19 }] },
|
|
49
|
+
hybrid: { id: 'esri-hybrid', layers: [{ url: tiles('World_Imagery'), attribution: IMAGERY, maxZoom: 19 }, esriLabels] }
|
|
50
|
+
};
|
package/dist/index.d.ts
CHANGED
|
@@ -12,3 +12,6 @@ export type { MapMarker, MarkerKind, Basemap, MapSelection, MapFeatureInfo, MapV
|
|
|
12
12
|
export type { MapStyle, SizeSpec, ColorSpec, FeatureStyle, PieStroke, LegendInfo, ClusterStyle, ClusterSizeSpec, ClusterColorSpec, ClusterBy, ClusterAgg, ClusterInfo } from './style.js';
|
|
13
13
|
export type { PointsInput, PointInput, PointsMode, HeatmapOptions } from './points.js';
|
|
14
14
|
export type { ControlPosition, ScaleUnit, HeadingStatus } from './util.js';
|
|
15
|
+
export type { MapLayer, MapLayerRequest, MapLayerData, MapLayerLoadState, BasemapTiles, BasemapOsm, BasemapLayer, BasemapStack, BasemapOption } from './types.js';
|
|
16
|
+
export { esriBasemaps, esriLabels, basemapTiles } from './basemaps.js';
|
|
17
|
+
export { propertyStyle, drawableSymbol, MARKER_SIZES, SIMPLESTYLE_KEYS } from './style.js';
|
package/dist/index.js
CHANGED
|
@@ -3,3 +3,5 @@ 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 { esriBasemaps, esriLabels, basemapTiles } from './basemaps.js';
|
|
7
|
+
export { propertyStyle, drawableSymbol, MARKER_SIZES, SIMPLESTYLE_KEYS } from './style.js';
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #302: the `layers` prop. Keeps one OpenLayers vector layer per `MapLayer` in step with the list: adds, removes and updates only what
|
|
3
|
+
* changed, loads bbox `loader` layers as the view moves, and styles every feature with `createFeatureStyle`. Loaded lazily by the Map.
|
|
4
|
+
*/
|
|
5
|
+
import type OLMap from 'ol/Map.js';
|
|
6
|
+
import VectorLayer from 'ol/layer/Vector.js';
|
|
7
|
+
import VectorSource from 'ol/source/Vector.js';
|
|
8
|
+
import type { FeatureLike } from 'ol/Feature.js';
|
|
9
|
+
import { type MapTokens } from './ol-style.js';
|
|
10
|
+
import type { MapLayer } from './types.js';
|
|
11
|
+
export type LayerHost = {
|
|
12
|
+
map: OLMap;
|
|
13
|
+
tokens: () => Partial<MapTokens>;
|
|
14
|
+
/** Whether a feature of this layer is the selected one. */
|
|
15
|
+
selected: (layer: VectorLayer<VectorSource>, f: FeatureLike) => boolean;
|
|
16
|
+
/** Labels drawn at this resolution (`labelMinZoom`). */
|
|
17
|
+
labels: (resolution: number) => boolean;
|
|
18
|
+
/** A layer (or the selected feature in it) went away: the Map rechecks its selection. */
|
|
19
|
+
changed: () => void;
|
|
20
|
+
};
|
|
21
|
+
/** GeoJSON (lon/lat) to features with ids: the GeoJSON `id`, else `properties.id`, else the index. */
|
|
22
|
+
export declare function readGeo(data: object): import("ol/Feature.js").default<import("ol/geom.js").Geometry, {
|
|
23
|
+
[x: string]: any;
|
|
24
|
+
}>[];
|
|
25
|
+
/** A lon/lat box `pad` larger on each side, clamped to the world. */
|
|
26
|
+
export declare function padBox(ext: number[], pad: number): [number, number, number, number];
|
|
27
|
+
export declare class LayerManager {
|
|
28
|
+
#private;
|
|
29
|
+
constructor(host: LayerHost);
|
|
30
|
+
/** The OpenLayers layer of an entry. */
|
|
31
|
+
layer(id: string): VectorLayer<VectorSource<import("ol/Feature.js").default<import("ol/geom.js").Geometry, {
|
|
32
|
+
[x: string]: any;
|
|
33
|
+
}>>, import("ol/Feature.js").default<import("ol/geom.js").Geometry, {
|
|
34
|
+
[x: string]: any;
|
|
35
|
+
}>> | undefined;
|
|
36
|
+
/** Whether an OpenLayers layer is one of ours. */
|
|
37
|
+
owns(l: unknown): boolean;
|
|
38
|
+
/** Apply the list: remove what left, create what is new, update only what changed. */
|
|
39
|
+
sync(list: MapLayer[]): void;
|
|
40
|
+
/** New theme tokens or label zoom: drop the cached styles and redraw. */
|
|
41
|
+
restyle(): void;
|
|
42
|
+
/** The selection moved: redraw (cached styles carry the selection in their key). */
|
|
43
|
+
redraw(): void;
|
|
44
|
+
/** Load a loader layer again now. */
|
|
45
|
+
reload(id: string): void;
|
|
46
|
+
destroy(): void;
|
|
47
|
+
}
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import VectorLayer from 'ol/layer/Vector.js';
|
|
2
|
+
import VectorSource from 'ol/source/Vector.js';
|
|
3
|
+
import GeoJSON from 'ol/format/GeoJSON.js';
|
|
4
|
+
import { transformExtent } from 'ol/proj.js';
|
|
5
|
+
import { containsExtent } from 'ol/extent.js';
|
|
6
|
+
import { createFeatureStyle } from './ol-style.js';
|
|
7
|
+
const fmt = new GeoJSON();
|
|
8
|
+
const DEBOUNCE = 250;
|
|
9
|
+
/** GeoJSON (lon/lat) to features with ids: the GeoJSON `id`, else `properties.id`, else the index. */
|
|
10
|
+
export function readGeo(data) {
|
|
11
|
+
const fs = fmt.readFeatures(Array.isArray(data) ? { type: 'FeatureCollection', features: data } : data, { featureProjection: 'EPSG:3857' });
|
|
12
|
+
fs.forEach((f, i) => { if (f.getId() === undefined)
|
|
13
|
+
f.setId(String(f.get('id') ?? i)); });
|
|
14
|
+
return fs;
|
|
15
|
+
}
|
|
16
|
+
/** A lon/lat box `pad` larger on each side, clamped to the world. */
|
|
17
|
+
export function padBox(ext, pad) {
|
|
18
|
+
const w = (ext[2] - ext[0]) * pad, h = (ext[3] - ext[1]) * pad;
|
|
19
|
+
return [Math.max(-180, ext[0] - w), Math.max(-90, ext[1] - h), Math.min(180, ext[2] + w), Math.min(90, ext[3] + h)];
|
|
20
|
+
}
|
|
21
|
+
export class LayerManager {
|
|
22
|
+
#host;
|
|
23
|
+
#entries = new Map();
|
|
24
|
+
#timer;
|
|
25
|
+
#onMove = () => { clearTimeout(this.#timer); this.#timer = setTimeout(() => this.#loadAll(), DEBOUNCE); };
|
|
26
|
+
constructor(host) {
|
|
27
|
+
this.#host = host;
|
|
28
|
+
host.map.on('moveend', this.#onMove);
|
|
29
|
+
}
|
|
30
|
+
/** The OpenLayers layer of an entry. */
|
|
31
|
+
layer(id) { return this.#entries.get(id)?.layer; }
|
|
32
|
+
/** Whether an OpenLayers layer is one of ours. */
|
|
33
|
+
owns(l) { for (const e of this.#entries.values())
|
|
34
|
+
if (e.layer === l)
|
|
35
|
+
return true; return false; }
|
|
36
|
+
/** Apply the list: remove what left, create what is new, update only what changed. */
|
|
37
|
+
sync(list) {
|
|
38
|
+
const ids = new Set(list.map((l) => l.id));
|
|
39
|
+
let gone = false;
|
|
40
|
+
for (const [id, e] of this.#entries)
|
|
41
|
+
if (!ids.has(id)) {
|
|
42
|
+
this.#drop(e);
|
|
43
|
+
this.#entries.delete(id);
|
|
44
|
+
gone = true;
|
|
45
|
+
}
|
|
46
|
+
list.forEach((spec, i) => {
|
|
47
|
+
const e = this.#entries.get(spec.id);
|
|
48
|
+
if (e)
|
|
49
|
+
this.#update(e, spec, i);
|
|
50
|
+
else
|
|
51
|
+
this.#entries.set(spec.id, this.#create(spec, i));
|
|
52
|
+
});
|
|
53
|
+
if (gone)
|
|
54
|
+
this.#host.changed();
|
|
55
|
+
}
|
|
56
|
+
/** New theme tokens or label zoom: drop the cached styles and redraw. */
|
|
57
|
+
restyle() { for (const e of this.#entries.values()) {
|
|
58
|
+
e.style.reset();
|
|
59
|
+
e.layer.changed();
|
|
60
|
+
} }
|
|
61
|
+
/** The selection moved: redraw (cached styles carry the selection in their key). */
|
|
62
|
+
redraw() { for (const e of this.#entries.values())
|
|
63
|
+
e.layer.changed(); }
|
|
64
|
+
/** Load a loader layer again now. */
|
|
65
|
+
reload(id) { const e = this.#entries.get(id); if (e) {
|
|
66
|
+
e.loaded = undefined;
|
|
67
|
+
void this.#load(e);
|
|
68
|
+
} }
|
|
69
|
+
destroy() {
|
|
70
|
+
clearTimeout(this.#timer);
|
|
71
|
+
this.#host.map.un('moveend', this.#onMove);
|
|
72
|
+
for (const e of this.#entries.values())
|
|
73
|
+
this.#drop(e);
|
|
74
|
+
this.#entries.clear();
|
|
75
|
+
}
|
|
76
|
+
#create(spec, i) {
|
|
77
|
+
const own = new VectorSource();
|
|
78
|
+
const entry = { spec: { ...spec }, own, truncated: false };
|
|
79
|
+
entry.style = this.#styleOf(entry);
|
|
80
|
+
entry.layer = new VectorLayer({ source: spec.source ?? own, style: entry.style, declutter: spec.declutter ?? false, properties: { id: spec.id, trussLayer: true } });
|
|
81
|
+
this.#apply(entry, spec, i);
|
|
82
|
+
if (spec.geojson)
|
|
83
|
+
own.addFeatures(readGeo(spec.geojson));
|
|
84
|
+
this.#host.map.addLayer(entry.layer);
|
|
85
|
+
if (spec.loader)
|
|
86
|
+
void this.#load(entry);
|
|
87
|
+
return entry;
|
|
88
|
+
}
|
|
89
|
+
#update(e, spec, i) {
|
|
90
|
+
const was = e.spec;
|
|
91
|
+
e.spec = { ...spec }; // a copy: a `$state` entry changed in place still differs from what was applied
|
|
92
|
+
if (spec.source !== was.source)
|
|
93
|
+
e.layer.setSource(spec.source ?? e.own);
|
|
94
|
+
if (spec.geojson !== was.geojson) {
|
|
95
|
+
e.own.clear(true);
|
|
96
|
+
if (spec.geojson)
|
|
97
|
+
e.own.addFeatures(readGeo(spec.geojson));
|
|
98
|
+
e.own.changed();
|
|
99
|
+
this.#host.changed();
|
|
100
|
+
}
|
|
101
|
+
// simplestyle is read when the style function is built, so a change rebuilds it; a new `style` only drops the cached looks
|
|
102
|
+
if (spec.simplestyle !== was.simplestyle) {
|
|
103
|
+
e.style = this.#styleOf(e);
|
|
104
|
+
e.layer.setStyle(e.style);
|
|
105
|
+
}
|
|
106
|
+
else if (spec.style !== was.style) {
|
|
107
|
+
e.style.reset();
|
|
108
|
+
e.layer.changed();
|
|
109
|
+
}
|
|
110
|
+
this.#apply(e, spec, i);
|
|
111
|
+
if (spec.loader && (spec.loader !== was.loader || (spec.visible !== false && was.visible === false))) {
|
|
112
|
+
if (spec.loader !== was.loader)
|
|
113
|
+
e.loaded = undefined;
|
|
114
|
+
void this.#load(e);
|
|
115
|
+
}
|
|
116
|
+
if (!spec.loader && was.loader) {
|
|
117
|
+
e.abort?.abort();
|
|
118
|
+
e.loaded = undefined;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
#styleOf(e) {
|
|
122
|
+
return createFeatureStyle({
|
|
123
|
+
style: (p, f) => { const s = e.spec.style; return typeof s === 'function' ? s(p, f) : s; },
|
|
124
|
+
simplestyle: e.spec.simplestyle,
|
|
125
|
+
selected: (f) => this.#host.selected(e.layer, f),
|
|
126
|
+
tokens: this.#host.tokens,
|
|
127
|
+
labels: this.#host.labels
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
#apply(e, spec, i) {
|
|
131
|
+
// OpenLayers' setters only fire a change (and a redraw) when the value differs
|
|
132
|
+
const l = e.layer;
|
|
133
|
+
l.setVisible(spec.visible !== false);
|
|
134
|
+
l.setZIndex(spec.zIndex ?? 30 + i);
|
|
135
|
+
l.setOpacity(spec.opacity ?? 1);
|
|
136
|
+
l.set('trussInteractive', spec.interactive !== false);
|
|
137
|
+
l.set('label', spec.label);
|
|
138
|
+
}
|
|
139
|
+
#drop(e) {
|
|
140
|
+
e.abort?.abort();
|
|
141
|
+
this.#host.map.removeLayer(e.layer);
|
|
142
|
+
e.style.reset();
|
|
143
|
+
}
|
|
144
|
+
#loadAll() { for (const e of this.#entries.values())
|
|
145
|
+
if (e.spec.loader)
|
|
146
|
+
void this.#load(e); }
|
|
147
|
+
async #load(e) {
|
|
148
|
+
const loader = e.spec.loader;
|
|
149
|
+
const map = this.#host.map;
|
|
150
|
+
const size = map.getSize();
|
|
151
|
+
if (!loader || e.spec.visible === false || !size || !size[0] || !size[1])
|
|
152
|
+
return;
|
|
153
|
+
const view = transformExtent(map.getView().calculateExtent(size), 'EPSG:3857', 'EPSG:4326');
|
|
154
|
+
if (e.loaded && !e.truncated && containsExtent(e.loaded, padBox(view, 0)))
|
|
155
|
+
return;
|
|
156
|
+
e.abort?.abort();
|
|
157
|
+
const ac = (e.abort = new AbortController());
|
|
158
|
+
const bbox = padBox(view, 0.25);
|
|
159
|
+
const report = e.spec.onload;
|
|
160
|
+
report?.({ loading: true, count: this.#source(e).getFeatures().length, truncated: e.truncated });
|
|
161
|
+
try {
|
|
162
|
+
const r = await loader({ bbox, zoom: map.getView().getZoom() ?? 0, signal: ac.signal });
|
|
163
|
+
if (ac.signal.aborted || e.abort !== ac)
|
|
164
|
+
return;
|
|
165
|
+
const data = r;
|
|
166
|
+
const wrapped = !!data && 'geojson' in data;
|
|
167
|
+
const geo = wrapped ? data.geojson : data;
|
|
168
|
+
const fs = geo ? readGeo(geo) : [];
|
|
169
|
+
const src = this.#source(e);
|
|
170
|
+
src.clear(true);
|
|
171
|
+
src.addFeatures(fs);
|
|
172
|
+
src.changed();
|
|
173
|
+
e.loaded = bbox;
|
|
174
|
+
e.truncated = wrapped && !!data.truncated;
|
|
175
|
+
this.#host.changed();
|
|
176
|
+
report?.({ loading: false, count: fs.length, truncated: e.truncated });
|
|
177
|
+
}
|
|
178
|
+
catch (err) {
|
|
179
|
+
if (ac.signal.aborted || e.abort !== ac)
|
|
180
|
+
return;
|
|
181
|
+
report?.({ loading: false, count: this.#source(e).getFeatures().length, truncated: e.truncated, error: err instanceof Error ? err.message : String(err) });
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
#source(e) { return (e.layer.getSource() ?? e.own); }
|
|
185
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Map's feature look as OpenLayers styles, for layers your app builds itself (`@ruckc/truss-ol/ol-style`). This module imports `ol`, so it
|
|
3
|
+
* is a separate entry: import it from client-only code (the Map loads it lazily, so OpenLayers never reaches the server render).
|
|
4
|
+
*/
|
|
5
|
+
import { Style } from 'ol/style.js';
|
|
6
|
+
import type { FeatureLike } from 'ol/Feature.js';
|
|
7
|
+
import { type FeatureStyle, type Props } from './style.js';
|
|
8
|
+
export { propertyStyle, drawableSymbol, MARKER_SIZES, SIMPLESTYLE_KEYS, type FeatureStyle } from './style.js';
|
|
9
|
+
/** The theme colours a feature style uses, resolved to concrete colours (canvas styles cannot read CSS variables). */
|
|
10
|
+
export type MapTokens = {
|
|
11
|
+
primary: string;
|
|
12
|
+
surface: string;
|
|
13
|
+
'on-surface': string;
|
|
14
|
+
'on-primary': string;
|
|
15
|
+
outline: string;
|
|
16
|
+
};
|
|
17
|
+
/** Classic light values, used for any token not given. */
|
|
18
|
+
export declare const DEFAULT_TOKENS: MapTokens;
|
|
19
|
+
/** The map tokens as they resolve at `el` (so a `data-theme` / `data-truss-theme` subtree applies). Read again after a theme change (`onThemeChange`). */
|
|
20
|
+
export declare function readMapTokens(el: Element): MapTokens;
|
|
21
|
+
export type OlStyleOptions = {
|
|
22
|
+
/** Draw the selection look: a halo under a point, a heavier outline and fill on a shape. */
|
|
23
|
+
selected?: boolean;
|
|
24
|
+
/** The feature's geometry type (`Point`, `LineString`, ...): points get a marker, everything else the shape look. Default: a shape. */
|
|
25
|
+
geometryType?: string;
|
|
26
|
+
/** Theme colours (`readMapTokens(el)`); missing ones are the classic light values. */
|
|
27
|
+
tokens?: Partial<MapTokens>;
|
|
28
|
+
/** The colour for what the style leaves out (fill, stroke, marker). Default: the `primary` token. */
|
|
29
|
+
color?: string;
|
|
30
|
+
/** Draw `label`. Default true. */
|
|
31
|
+
labels?: boolean;
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* The OpenLayers styles for one feature look, the same the Map draws its own GeoJSON features and points with. A point is a dot of `radius`
|
|
35
|
+
* (default 5) in `markerColor`, else `fill`, outlined in the surface colour, or a pie (`colors`), with an optional `symbol` inside and the
|
|
36
|
+
* `label` below; a shape has a `stroke` of `strokeWidth` (default 2.5) and a translucent `fill` (default 0.14 opacity). Colours not given are
|
|
37
|
+
* `color`, else the theme's primary. The selection look adds a halo (points) or a heavier outline and fill (shapes).
|
|
38
|
+
*/
|
|
39
|
+
export declare function createOlStyle(s: FeatureStyle, o?: OlStyleOptions): Style[];
|
|
40
|
+
export type FeatureStyleSpec = {
|
|
41
|
+
/** The look of every feature, or a function of a feature's properties (and id and geometry type) returning it. */
|
|
42
|
+
style?: FeatureStyle | ((properties: Props, feature: {
|
|
43
|
+
id: string | number | undefined;
|
|
44
|
+
type: string;
|
|
45
|
+
}) => FeatureStyle | undefined);
|
|
46
|
+
/** Read each feature's own `style` object and simplestyle properties, which win over `style`. Default true. */
|
|
47
|
+
simplestyle?: boolean;
|
|
48
|
+
/** Whether a feature is selected (it then gets the selection look). */
|
|
49
|
+
selected?: (feature: FeatureLike) => boolean;
|
|
50
|
+
/** Theme colours, or a function returning them (read whenever the cache is empty: call `reset()` after a theme change). */
|
|
51
|
+
tokens?: Partial<MapTokens> | (() => Partial<MapTokens>);
|
|
52
|
+
/** The colour for what the style leaves out. Default: the `primary` token. */
|
|
53
|
+
color?: string;
|
|
54
|
+
/** Draw labels: a boolean, or a function of the view resolution. Default true. */
|
|
55
|
+
labels?: boolean | ((resolution: number) => boolean);
|
|
56
|
+
};
|
|
57
|
+
/** An OpenLayers style function from {@link createFeatureStyle}; `reset()` drops its cached styles (after a theme change, or a new `style`). */
|
|
58
|
+
export type FeatureStyleFunction = ((feature: FeatureLike, resolution: number) => Style[] | undefined) & {
|
|
59
|
+
reset(): void;
|
|
60
|
+
};
|
|
61
|
+
/**
|
|
62
|
+
* The Map's internal style builder as an OpenLayers style function, for vector layers your app creates: the same tokens, selection look,
|
|
63
|
+
* labels and simplestyle reading as the Map's own layers. Styles are cached per distinct look (up to 2000), so large layers stay cheap.
|
|
64
|
+
*
|
|
65
|
+
* ```ts
|
|
66
|
+
* const style = createFeatureStyle({ style: { markerColor: '#d33' }, tokens: () => readMapTokens(el), selected: (f) => f.getId() === sel });
|
|
67
|
+
* new VectorLayer({ source, style });
|
|
68
|
+
* onThemeChange(el, () => { style.reset(); layer.changed(); });
|
|
69
|
+
* ```
|
|
70
|
+
*/
|
|
71
|
+
export declare function createFeatureStyle(spec?: FeatureStyleSpec): FeatureStyleFunction;
|
package/dist/ol-style.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Map's feature look as OpenLayers styles, for layers your app builds itself (`@ruckc/truss-ol/ol-style`). This module imports `ol`, so it
|
|
3
|
+
* is a separate entry: import it from client-only code (the Map loads it lazily, so OpenLayers never reaches the server render).
|
|
4
|
+
*/
|
|
5
|
+
import { Circle as CircleStyle, Fill, Icon, Stroke, Style, Text } from 'ol/style.js';
|
|
6
|
+
import { readColorTokens } from '@ruckc/truss-ui';
|
|
7
|
+
import { drawPie, drawableSymbol, isLight, pieKey, pieStroke, propertyStyle, withAlpha } from './style.js';
|
|
8
|
+
export { propertyStyle, drawableSymbol, MARKER_SIZES, SIMPLESTYLE_KEYS } from './style.js';
|
|
9
|
+
/** Classic light values, used for any token not given. */
|
|
10
|
+
export const DEFAULT_TOKENS = { primary: '#1f5f8b', surface: '#ffffff', 'on-surface': '#1b1c1f', 'on-primary': '#ffffff', outline: '#73777f' };
|
|
11
|
+
/** The map tokens as they resolve at `el` (so a `data-theme` / `data-truss-theme` subtree applies). Read again after a theme change (`onThemeChange`). */
|
|
12
|
+
export function readMapTokens(el) {
|
|
13
|
+
const names = Object.keys(DEFAULT_TOKENS);
|
|
14
|
+
const C = readColorTokens(el, names.map((n) => `--tr-${n}`));
|
|
15
|
+
return Object.fromEntries(names.map((n) => [n, C[`--tr-${n}`] ?? DEFAULT_TOKENS[n]]));
|
|
16
|
+
}
|
|
17
|
+
const FONT = '600 12px Inter Variable, system-ui, sans-serif';
|
|
18
|
+
const pies = new Map();
|
|
19
|
+
/** A pie marker as an icon, one canvas per distinct look however many features share it. */
|
|
20
|
+
function pieIcon(colors, radius, stroke) {
|
|
21
|
+
const key = pieKey(colors, radius, stroke);
|
|
22
|
+
let ic = pies.get(key);
|
|
23
|
+
if (!ic) {
|
|
24
|
+
const ratio = Math.ceil(window.devicePixelRatio);
|
|
25
|
+
pies.set(key, (ic = new Icon({ img: drawPie(colors, radius, stroke, ratio), scale: 1 / ratio })));
|
|
26
|
+
}
|
|
27
|
+
return ic;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* The OpenLayers styles for one feature look, the same the Map draws its own GeoJSON features and points with. A point is a dot of `radius`
|
|
31
|
+
* (default 5) in `markerColor`, else `fill`, outlined in the surface colour, or a pie (`colors`), with an optional `symbol` inside and the
|
|
32
|
+
* `label` below; a shape has a `stroke` of `strokeWidth` (default 2.5) and a translucent `fill` (default 0.14 opacity). Colours not given are
|
|
33
|
+
* `color`, else the theme's primary. The selection look adds a halo (points) or a heavier outline and fill (shapes).
|
|
34
|
+
*/
|
|
35
|
+
export function createOlStyle(s, o = {}) {
|
|
36
|
+
const T = { ...DEFAULT_TOKENS, ...o.tokens };
|
|
37
|
+
const base = o.color ?? T.primary;
|
|
38
|
+
const on = !!o.selected;
|
|
39
|
+
const strokeC = typeof s.stroke === 'object' ? s.stroke.color : s.stroke;
|
|
40
|
+
const strokeW = typeof s.stroke === 'object' ? s.stroke.width : undefined;
|
|
41
|
+
const sc = (c) => (s.strokeOpacity === undefined ? c : withAlpha(c, s.strokeOpacity));
|
|
42
|
+
const label = o.labels === false || s.label === undefined || s.label === null ? undefined : String(s.label);
|
|
43
|
+
const text = (offsetY) => label === undefined ? undefined
|
|
44
|
+
: new Text({ text: label, offsetY, font: FONT, fill: new Fill({ color: T['on-surface'] }), stroke: new Stroke({ color: T.surface, width: 3 }) });
|
|
45
|
+
const t = o.geometryType;
|
|
46
|
+
if (t === 'Point' || t === 'MultiPoint') {
|
|
47
|
+
const fillC = s.markerColor ?? s.fill ?? base;
|
|
48
|
+
const r = s.radius ?? 5;
|
|
49
|
+
if (s.colors?.length) {
|
|
50
|
+
const pie = new Style({ image: pieIcon(s.colors, r, pieStroke(s.stroke, s.strokeWidth)), text: text(r + 12) });
|
|
51
|
+
return on ? [new Style({ image: new CircleStyle({ radius: r + 6, fill: new Fill({ color: withAlpha(T.primary, 0.25) }), stroke: new Stroke({ color: T.primary, width: 2.5 }) }) }), pie] : [pie];
|
|
52
|
+
}
|
|
53
|
+
const sym = drawableSymbol(s.symbol);
|
|
54
|
+
const rr = sym ? Math.max(r, 9) : r;
|
|
55
|
+
const dot = new Style({
|
|
56
|
+
image: new CircleStyle({ radius: on ? rr + 2 : rr, fill: new Fill({ color: s.opacity === undefined ? fillC : withAlpha(fillC, s.opacity) }), stroke: new Stroke({ color: strokeC ? sc(strokeC) : T.surface, width: s.strokeWidth ?? strokeW ?? 1.5 }) }),
|
|
57
|
+
text: sym
|
|
58
|
+
? new Text({ text: sym, font: `700 ${Math.round(rr * 1.1)}px Inter Variable, system-ui, sans-serif`, fill: new Fill({ color: s.markerColor === undefined && s.fill === undefined && o.color === undefined ? T['on-primary'] : isLight(fillC) ? '#111111' : '#ffffff' }) })
|
|
59
|
+
: text(rr + 12)
|
|
60
|
+
});
|
|
61
|
+
const out = on ? [new Style({ image: new CircleStyle({ radius: rr + 8, fill: new Fill({ color: withAlpha(fillC, 0.25) }) }) }), dot] : [dot];
|
|
62
|
+
return sym && label !== undefined ? [...out, new Style({ text: text(rr + 12 + (on ? 2 : 0)) })] : out;
|
|
63
|
+
}
|
|
64
|
+
return [new Style({
|
|
65
|
+
stroke: new Stroke({ color: sc(strokeC ?? base), width: (s.strokeWidth ?? strokeW ?? 2.5) + (on ? 1.5 : 0), lineCap: 'round', lineJoin: 'round' }),
|
|
66
|
+
fill: new Fill({ color: withAlpha(s.fill ?? base, Math.min(1, (s.opacity ?? 0.14) + (on ? 0.14 : 0))) }),
|
|
67
|
+
text: text(0)
|
|
68
|
+
})];
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* The Map's internal style builder as an OpenLayers style function, for vector layers your app creates: the same tokens, selection look,
|
|
72
|
+
* labels and simplestyle reading as the Map's own layers. Styles are cached per distinct look (up to 2000), so large layers stay cheap.
|
|
73
|
+
*
|
|
74
|
+
* ```ts
|
|
75
|
+
* const style = createFeatureStyle({ style: { markerColor: '#d33' }, tokens: () => readMapTokens(el), selected: (f) => f.getId() === sel });
|
|
76
|
+
* new VectorLayer({ source, style });
|
|
77
|
+
* onThemeChange(el, () => { style.reset(); layer.changed(); });
|
|
78
|
+
* ```
|
|
79
|
+
*/
|
|
80
|
+
export function createFeatureStyle(spec = {}) {
|
|
81
|
+
const cache = new Map();
|
|
82
|
+
let tokens;
|
|
83
|
+
const fn = ((f, resolution) => {
|
|
84
|
+
const g = f.getGeometry();
|
|
85
|
+
if (!g)
|
|
86
|
+
return undefined;
|
|
87
|
+
const type = g.getType();
|
|
88
|
+
const p = f.getProperties();
|
|
89
|
+
const st = spec.style;
|
|
90
|
+
const own = typeof st === 'function' ? st(p, { id: f.getId(), type }) : st;
|
|
91
|
+
const look = spec.simplestyle === false ? { ...own } : { ...own, ...propertyStyle(p) };
|
|
92
|
+
const selected = !!spec.selected?.(f);
|
|
93
|
+
const labels = typeof spec.labels === 'function' ? spec.labels(resolution) : spec.labels !== false;
|
|
94
|
+
const key = JSON.stringify([type, selected, labels, look]);
|
|
95
|
+
let out = cache.get(key);
|
|
96
|
+
if (!out) {
|
|
97
|
+
if (!cache.size)
|
|
98
|
+
tokens = typeof spec.tokens === 'function' ? spec.tokens() : spec.tokens;
|
|
99
|
+
if (cache.size >= 2000)
|
|
100
|
+
cache.clear();
|
|
101
|
+
cache.set(key, (out = createOlStyle(look, { selected, geometryType: type, tokens, color: spec.color, labels })));
|
|
102
|
+
}
|
|
103
|
+
return out;
|
|
104
|
+
});
|
|
105
|
+
fn.reset = () => cache.clear();
|
|
106
|
+
return fn;
|
|
107
|
+
}
|
package/dist/style.d.ts
CHANGED
|
@@ -175,16 +175,26 @@ export declare function pieKey(colors: string[], radius: number, stroke: PieStro
|
|
|
175
175
|
export declare function drawPie(colors: string[], radius: number, stroke: PieStroke, ratio?: number, doc?: Document): HTMLCanvasElement;
|
|
176
176
|
/** Per-feature drawing overrides. Any field left out keeps the feature's default (or data-driven) look. */
|
|
177
177
|
export type FeatureStyle = {
|
|
178
|
-
/** Fill colour of polygons and points
|
|
178
|
+
/** Fill colour of polygons, and of points that have no `markerColor`. */
|
|
179
179
|
fill?: string;
|
|
180
|
-
/** Fill opacity 0 to 1. */
|
|
180
|
+
/** Fill opacity 0 to 1 (polygons, and points). */
|
|
181
181
|
opacity?: number;
|
|
182
182
|
/** Outline / line colour. For a pie (`colors`) the outline as `{ color, width }`; a plain colour string works there too. */
|
|
183
183
|
stroke?: string | PieStroke;
|
|
184
184
|
/** Outline / line width in px. */
|
|
185
185
|
strokeWidth?: number;
|
|
186
|
+
/** Outline / line opacity 0 to 1. Default: the colour as given. */
|
|
187
|
+
strokeOpacity?: number;
|
|
186
188
|
/** Point radius in px. */
|
|
187
189
|
radius?: number;
|
|
190
|
+
/** Points only: the marker's colour (simplestyle `marker-color`). Wins over `fill` for points; polygons and lines ignore it. */
|
|
191
|
+
markerColor?: string;
|
|
192
|
+
/**
|
|
193
|
+
* Points only: a symbol drawn inside the marker (simplestyle `marker-symbol`). One or two characters (a letter, a digit, an emoji) or a
|
|
194
|
+
* number up to 999 are drawn in black or white, whichever reads on the marker, and the marker grows to at least a 9px radius to hold it.
|
|
195
|
+
* Anything longer (a Maki icon name such as `rail`) is not drawn: no icon set is bundled.
|
|
196
|
+
*/
|
|
197
|
+
symbol?: string;
|
|
188
198
|
/**
|
|
189
199
|
* Points only: draw a pie marker instead of a dot. One colour is a filled circle; two to six (extra ones are ignored) are equal slices
|
|
190
200
|
* starting at 12 o'clock and running clockwise. Any CSS colour, e.g. hex strings straight from your data. Wins over `fill`.
|
|
@@ -193,11 +203,24 @@ export type FeatureStyle = {
|
|
|
193
203
|
/** Text drawn next to the feature. */
|
|
194
204
|
label?: string;
|
|
195
205
|
};
|
|
206
|
+
/** simplestyle-spec `marker-size` names as marker radii in px (`marker-size` may also be a radius in px). */
|
|
207
|
+
export declare const MARKER_SIZES: {
|
|
208
|
+
readonly small: 5;
|
|
209
|
+
readonly medium: 7;
|
|
210
|
+
readonly large: 10;
|
|
211
|
+
};
|
|
212
|
+
/** The simplestyle-spec 1.1 keys, and `title` (the label). A default popup leaves them out. */
|
|
213
|
+
export declare const SIMPLESTYLE_KEYS: readonly ["marker-size", "marker-symbol", "marker-color", "stroke", "stroke-opacity", "stroke-width", "fill", "fill-opacity", "title"];
|
|
196
214
|
/**
|
|
197
|
-
* The style a GeoJSON feature carries in its own properties: a `style` object (
|
|
198
|
-
*
|
|
215
|
+
* The style a GeoJSON feature carries in its own properties: a `style` object ({@link FeatureStyle}) and/or the simplestyle-spec 1.1 keys
|
|
216
|
+
* `marker-color`, `marker-size` (`small`, `medium`, `large`, or a radius in px), `marker-symbol`, `stroke`, `stroke-width`, `stroke-opacity`,
|
|
217
|
+
* `fill` and `fill-opacity`, plus `title` (the label). Numbers may be numeric strings, opacities are clamped to 0..1, and values that do not
|
|
218
|
+
* parse are ignored. A `style` object wins over the simplestyle keys. The spec's own defaults (grey markers) are not applied: what a feature
|
|
219
|
+
* leaves out takes the layer's style, then the theme.
|
|
199
220
|
*/
|
|
200
221
|
export declare function propertyStyle(p: Props): FeatureStyle;
|
|
222
|
+
/** The part of a marker symbol ({@link FeatureStyle.symbol}) that can be drawn as text: at most two characters (an emoji counts as one), or a number up to 999; else `undefined`. */
|
|
223
|
+
export declare function drawableSymbol(s: string | undefined): string | undefined;
|
|
201
224
|
/** A feature's heading for a popup: its `name`, `title`, `label`, or `id` property, else `Feature`. */
|
|
202
225
|
export declare function featureTitle(p: Props): string;
|
|
203
226
|
/** The properties a default popup lists: at most `max` entries, without styling keys, empty values and internals; objects as JSON. */
|
package/dist/style.js
CHANGED
|
@@ -183,19 +183,48 @@ export function drawPie(colors, radius, stroke, ratio = 1, doc = document) {
|
|
|
183
183
|
});
|
|
184
184
|
return cv;
|
|
185
185
|
}
|
|
186
|
-
|
|
186
|
+
/** simplestyle-spec `marker-size` names as marker radii in px (`marker-size` may also be a radius in px). */
|
|
187
|
+
export const MARKER_SIZES = { small: 5, medium: 7, large: 10 };
|
|
188
|
+
/** The simplestyle-spec 1.1 keys, and `title` (the label). A default popup leaves them out. */
|
|
189
|
+
export const SIMPLESTYLE_KEYS = ['marker-size', 'marker-symbol', 'marker-color', 'stroke', 'stroke-opacity', 'stroke-width', 'fill', 'fill-opacity', 'title'];
|
|
190
|
+
const num = (v) => {
|
|
191
|
+
const n = typeof v === 'number' ? v : typeof v === 'string' && v.trim() !== '' ? Number(v) : NaN;
|
|
192
|
+
return Number.isFinite(n) ? n : undefined;
|
|
193
|
+
};
|
|
194
|
+
const unit = (v) => { const n = num(v); return n === undefined ? undefined : Math.min(Math.max(n, 0), 1); };
|
|
195
|
+
const str = (v) => (typeof v === 'number' && Number.isFinite(v) ? String(v) : col(v));
|
|
196
|
+
const col = (v) => (typeof v === 'string' && v.trim() !== '' ? v.trim() : undefined);
|
|
197
|
+
const size = (v) => { const k = typeof v === 'string' ? v.trim().toLowerCase() : ''; return k in MARKER_SIZES ? MARKER_SIZES[k] : num(v); };
|
|
198
|
+
/** How each simplestyle key (and `title`) reads into a {@link FeatureStyle} field. */
|
|
199
|
+
const SIMPLE = [
|
|
200
|
+
['fill', 'fill', col], ['fill-opacity', 'opacity', unit], ['stroke', 'stroke', col], ['stroke-width', 'strokeWidth', num], ['stroke-opacity', 'strokeOpacity', unit],
|
|
201
|
+
['marker-size', 'radius', size], ['marker-color', 'markerColor', col], ['marker-symbol', 'symbol', str], ['title', 'label', (v) => v]
|
|
202
|
+
];
|
|
187
203
|
/**
|
|
188
|
-
* The style a GeoJSON feature carries in its own properties: a `style` object (
|
|
189
|
-
*
|
|
204
|
+
* The style a GeoJSON feature carries in its own properties: a `style` object ({@link FeatureStyle}) and/or the simplestyle-spec 1.1 keys
|
|
205
|
+
* `marker-color`, `marker-size` (`small`, `medium`, `large`, or a radius in px), `marker-symbol`, `stroke`, `stroke-width`, `stroke-opacity`,
|
|
206
|
+
* `fill` and `fill-opacity`, plus `title` (the label). Numbers may be numeric strings, opacities are clamped to 0..1, and values that do not
|
|
207
|
+
* parse are ignored. A `style` object wins over the simplestyle keys. The spec's own defaults (grey markers) are not applied: what a feature
|
|
208
|
+
* leaves out takes the layer's style, then the theme.
|
|
190
209
|
*/
|
|
191
210
|
export function propertyStyle(p) {
|
|
192
211
|
const out = {};
|
|
193
|
-
for (const [k, to] of
|
|
194
|
-
|
|
195
|
-
|
|
212
|
+
for (const [k, to, read] of SIMPLE) {
|
|
213
|
+
const v = p[k] === undefined || p[k] === null ? undefined : read(p[k]);
|
|
214
|
+
if (v !== undefined)
|
|
215
|
+
out[to] = v;
|
|
216
|
+
}
|
|
196
217
|
const s = p.style;
|
|
197
218
|
return s && typeof s === 'object' ? { ...out, ...s } : out;
|
|
198
219
|
}
|
|
220
|
+
/** The part of a marker symbol ({@link FeatureStyle.symbol}) that can be drawn as text: at most two characters (an emoji counts as one), or a number up to 999; else `undefined`. */
|
|
221
|
+
export function drawableSymbol(s) {
|
|
222
|
+
if (!s)
|
|
223
|
+
return undefined;
|
|
224
|
+
if (/^\d{1,3}$/.test(s))
|
|
225
|
+
return s;
|
|
226
|
+
return [...new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(s)].length <= 2 ? s : undefined;
|
|
227
|
+
}
|
|
199
228
|
/** A feature's heading for a popup: its `name`, `title`, `label`, or `id` property, else `Feature`. */
|
|
200
229
|
export function featureTitle(p) {
|
|
201
230
|
for (const k of ['name', 'title', 'label', 'id'])
|
|
@@ -205,7 +234,7 @@ export function featureTitle(p) {
|
|
|
205
234
|
}
|
|
206
235
|
/** The properties a default popup lists: at most `max` entries, without styling keys, empty values and internals; objects as JSON. */
|
|
207
236
|
export function popupEntries(p, max = 8) {
|
|
208
|
-
const skip = new Set(['geometry', 'style', 'kind', ...
|
|
237
|
+
const skip = new Set(['geometry', 'style', 'kind', ...SIMPLESTYLE_KEYS, '_cluster']);
|
|
209
238
|
const out = [];
|
|
210
239
|
for (const [k, v] of Object.entries(p)) {
|
|
211
240
|
if (skip.has(k) || v === undefined || v === null || v === '')
|