@ruckc/truss-ol 1.56.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 +101 -7
- package/dist/Map.svelte +419 -53
- package/dist/Map.svelte.d.ts +78 -2
- package/dist/basemaps.d.ts +106 -0
- package/dist/basemaps.js +50 -0
- package/dist/contextmenu.d.ts +9 -0
- package/dist/contextmenu.js +23 -0
- package/dist/edit.d.ts +42 -0
- package/dist/edit.js +116 -0
- package/dist/index.d.ts +4 -1
- package/dist/index.js +2 -0
- package/dist/layers-ol.d.ts +47 -0
- package/dist/layers-ol.js +185 -0
- package/dist/locate.d.ts +9 -0
- package/dist/locate.js +29 -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 +167 -10
- package/dist/util.d.ts +1 -0
- package/dist/util.js +1 -0
- package/package.json +7 -2
|
@@ -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
|
+
}
|
package/dist/locate.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { MapLocateError, MapLocateOptions, MapLocation } from './types.js';
|
|
2
|
+
/** @internal The Geolocation API behind the Map's locate control (#303). */
|
|
3
|
+
/** A `GeolocationPositionError` code as the Map reports it. */
|
|
4
|
+
export declare function locateErrorCode(code: number): MapLocateError['code'];
|
|
5
|
+
export declare function toLocation(p: GeolocationPosition): MapLocation;
|
|
6
|
+
/** Resolved `controls.locate` options; `undefined` when the control is off. */
|
|
7
|
+
export declare function locateOptions(v: boolean | MapLocateOptions | undefined): Required<MapLocateOptions> | undefined;
|
|
8
|
+
/** Watch the position: `onfix` on each update, `onerror` once (the watch stops). Returns the stop function. */
|
|
9
|
+
export declare function watchLocation(o: Required<MapLocateOptions>, onfix: (l: MapLocation) => void, onerror: (code: MapLocateError['code']) => void): () => void;
|
package/dist/locate.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** @internal The Geolocation API behind the Map's locate control (#303). */
|
|
2
|
+
/** A `GeolocationPositionError` code as the Map reports it. */
|
|
3
|
+
export function locateErrorCode(code) {
|
|
4
|
+
return code === 1 ? 'denied' : code === 3 ? 'timeout' : 'unavailable';
|
|
5
|
+
}
|
|
6
|
+
export function toLocation(p) {
|
|
7
|
+
const c = p.coords;
|
|
8
|
+
return { lonLat: [c.longitude, c.latitude], accuracy: c.accuracy, heading: c.heading ?? null, speed: c.speed ?? null, timestamp: p.timestamp };
|
|
9
|
+
}
|
|
10
|
+
/** Resolved `controls.locate` options; `undefined` when the control is off. */
|
|
11
|
+
export function locateOptions(v) {
|
|
12
|
+
if (!v)
|
|
13
|
+
return undefined;
|
|
14
|
+
const o = v === true ? {} : v;
|
|
15
|
+
return { follow: o.follow ?? false, zoom: o.zoom ?? 15, enableHighAccuracy: o.enableHighAccuracy ?? true, timeout: o.timeout ?? 15000, maximumAge: o.maximumAge ?? 30000 };
|
|
16
|
+
}
|
|
17
|
+
/** Watch the position: `onfix` on each update, `onerror` once (the watch stops). Returns the stop function. */
|
|
18
|
+
export function watchLocation(o, onfix, onerror) {
|
|
19
|
+
// `Object(undefined)` is `{}`: no navigator (SSR) and no Geolocation API are the same case
|
|
20
|
+
const geo = Object(globalThis.navigator).geolocation;
|
|
21
|
+
let id;
|
|
22
|
+
const stop = () => { if (id !== undefined)
|
|
23
|
+
geo.clearWatch(id); id = undefined; };
|
|
24
|
+
if (!geo)
|
|
25
|
+
onerror('unsupported');
|
|
26
|
+
else
|
|
27
|
+
id = geo.watchPosition((p) => onfix(toLocation(p)), (e) => { stop(); onerror(locateErrorCode(e.code)); }, { enableHighAccuracy: o.enableHighAccuracy, timeout: o.timeout, maximumAge: o.maximumAge });
|
|
28
|
+
return stop;
|
|
29
|
+
}
|
|
@@ -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 === '')
|