@emuanalytics/flow-rdf-core 4.1.8 → 4.2.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,8 +1,11 @@
1
1
  import * as maplibreSpec from '@emuanalytics/maplibre-gl-style-spec';
2
- import { makeObservable, observable, computed, action } from 'mobx';
3
- import { isDefined, isObjectFull, isNil } from '../utils/type-checks.mjs';
4
- import { ReactiveExpression } from '../expressions/reactive-expression.mjs';
2
+ import { makeObservable, observable, computed, action, toJS } from 'mobx';
3
+ import { isNil, isBoolean, isDefined, isObjectFull } from '../utils/type-checks.mjs';
4
+ import { expandFlowStyle } from './flow-style/expand.mjs';
5
+ import { saveStoredFlowStyle, loadStoredFlowStyle, setStoredFlowStyleProperty } from './flow-style/stored-format.mjs';
6
+ import { flowStyleVersion } from './flow-style/values.mjs';
5
7
  import { FlowCoreError } from '../errors/flow-error.mjs';
8
+ import { ReactiveExpression } from '../expressions/reactive-expression.mjs';
6
9
 
7
10
  var __defProp = Object.defineProperty;
8
11
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
@@ -17,11 +20,24 @@ const _MapLayer = class _MapLayer {
17
20
  __publicField(this, "_filter", null);
18
21
  __publicField(this, "_paintProps", {});
19
22
  __publicField(this, "_layoutProps", {});
23
+ __publicField(this, "_visibility", null);
24
+ __publicField(this, "_subLayers", null);
25
+ __publicField(this, "_flow", null);
26
+ __publicField(this, "_issues", []);
27
+ // A flow layer's `interactive` option when it isn't a boolean: the default applies, with a warning in version 2
28
+ __publicField(this, "_invalidInteractive");
20
29
  this._options = {
21
30
  ..._MapLayer._defaultOptions,
22
31
  ...options
23
32
  };
24
- this.getPropertyMetadata("visibility", options.type);
33
+ const isFlow = options.type === "flow";
34
+ if (isFlow && !isNil(options.interactive) && !isBoolean(options.interactive)) {
35
+ this._invalidInteractive = options.interactive;
36
+ this._options.interactive = true;
37
+ }
38
+ if (!isFlow) {
39
+ this.getPropertyMetadata("visibility", options.type);
40
+ }
25
41
  makeObservable(
26
42
  this,
27
43
  {
@@ -30,8 +46,13 @@ const _MapLayer = class _MapLayer {
30
46
  _layoutProps: observable,
31
47
  _filter: observable,
32
48
  _options: observable,
49
+ _visibility: observable.ref,
50
+ _subLayers: observable.ref,
51
+ _flow: observable.ref,
52
+ _issues: observable.ref,
33
53
  //computed
34
54
  layerSpecification: computed,
55
+ layerSpecifications: computed,
35
56
  // actions
36
57
  bindState: action,
37
58
  setMinZoom: action,
@@ -41,22 +62,32 @@ const _MapLayer = class _MapLayer {
41
62
  setBelow: action,
42
63
  setStyle: action,
43
64
  setStyleProperty: action,
44
- setFilter: action
65
+ setFilter: action,
66
+ setVisibility: action,
67
+ setSubLayers: action,
68
+ setVersion1FlowStyle: action
45
69
  },
46
70
  { name: this.formattedName(options.id) }
47
71
  );
48
72
  if (options.filter) {
49
73
  this.setFilter(options.filter);
50
74
  }
51
- if (options.style) {
75
+ if (isFlow) {
76
+ this.setStyle(options.style);
77
+ } else if (options.style) {
52
78
  this.setStyle(options.style);
53
79
  }
54
80
  }
81
+ /**
82
+ * The specification of the layer's own MapLibre layer. A layer that renders as several MapLibre layers, such as a
83
+ * flow layer, doesn't render this one.
84
+ */
55
85
  get layerSpecification() {
56
86
  void this._options.above;
57
87
  void this._options.below;
58
88
  const layer = {
59
89
  id: this._options.id,
90
+ // A flow layer's own type, 'flow', is never rendered: it has sub-layers
60
91
  type: this._options.type,
61
92
  source: this._options.source
62
93
  };
@@ -88,8 +119,94 @@ const _MapLayer = class _MapLayer {
88
119
  return accum;
89
120
  }, {});
90
121
  }
122
+ if (this._visibility) {
123
+ layer.layout = { ...layer.layout, visibility: this.visibilityValue(this._visibility) };
124
+ }
125
+ if (isDefined(this._options.metadata)) {
126
+ layer.metadata = toJS(this._options.metadata);
127
+ }
91
128
  return layer;
92
129
  }
130
+ /**
131
+ * The specifications of every MapLibre layer the layer renders as, in draw order: its sub-layers', or its own.
132
+ *
133
+ * @internal
134
+ */
135
+ get layerSpecifications() {
136
+ if (!this._subLayers) {
137
+ return [this.layerSpecification];
138
+ }
139
+ return this._subLayers.map((subLayer) => this.subLayerSpecification(subLayer));
140
+ }
141
+ /**
142
+ * IDs of the MapLibre layers the layer renders as, in draw order.
143
+ *
144
+ * @internal
145
+ */
146
+ get maplibreLayerIds() {
147
+ return this._subLayers ? this._subLayers.map(({ options }) => options.id) : [this._options.id];
148
+ }
149
+ /**
150
+ * IDs of the MapLibre layers whose features click and hover events report, as this layer.
151
+ *
152
+ * @internal
153
+ */
154
+ get interactiveLayerIds() {
155
+ if (!this.interactive) {
156
+ return [];
157
+ }
158
+ return this._subLayers ? this._subLayers.filter(({ options }) => options.interactive !== false).map(({ options }) => options.id) : [this._options.id];
159
+ }
160
+ /**
161
+ * IDs of the map data sources the layer's MapLibre layers display.
162
+ *
163
+ * @internal
164
+ */
165
+ get sourceIds() {
166
+ if (!this._subLayers) {
167
+ return [this._options.source];
168
+ }
169
+ return [...new Set(this._subLayers.map(({ layer }) => layer.source))];
170
+ }
171
+ /**
172
+ * The layer's sub-layers, or `null` for a layer that renders as one MapLibre layer.
173
+ *
174
+ * @internal
175
+ */
176
+ get subLayers() {
177
+ return this._subLayers ? this._subLayers.map(({ options }) => options) : null;
178
+ }
179
+ /**
180
+ * Layer metadata, copied to the `metadata` of the layer's MapLibre layers.
181
+ *
182
+ * @experimental
183
+ */
184
+ get metadata() {
185
+ return this._options.metadata;
186
+ }
187
+ /**
188
+ * A flow layer's style, in its stored format and version, ready to save. A copy: change the layer with
189
+ * {@link setStyle} and {@link setStyleProperty}. `undefined` for a MapLibre layer.
190
+ *
191
+ * Reading it in a MobX reaction, or a component that renders from state, tracks changes to the style.
192
+ *
193
+ * @experimental
194
+ */
195
+ get flowStyle() {
196
+ return this._flow ? saveStoredFlowStyle(this._flow.stored) : void 0;
197
+ }
198
+ /**
199
+ * The problems with a flow layer's style, updated whenever the style changes. An `error` means a property, or the
200
+ * whole style, isn't rendered; a `warning` means it is rendered anyway. Empty for a MapLibre layer, which throws on a
201
+ * bad style instead.
202
+ *
203
+ * The list is observable: read it in a MobX reaction to follow it.
204
+ *
205
+ * @experimental
206
+ */
207
+ get issues() {
208
+ return this._issues;
209
+ }
93
210
  get id() {
94
211
  return this._options.id;
95
212
  }
@@ -115,6 +232,8 @@ const _MapLayer = class _MapLayer {
115
232
  }
116
233
  Object.values(this._paintProps).forEach((prop) => prop.bindState(state));
117
234
  Object.values(this._layoutProps).forEach((prop) => prop.bindState(state));
235
+ this._visibility?.bindState(state);
236
+ this._subLayers?.forEach(({ layer }) => layer.bindState(state));
118
237
  return this;
119
238
  }
120
239
  setMinZoom(zoom) {
@@ -137,8 +256,28 @@ const _MapLayer = class _MapLayer {
137
256
  this._options.below = layerId;
138
257
  return this;
139
258
  }
140
- setStyle(styleProgram) {
141
- const parsedProgram = ReactiveExpression.parseProgram(styleProgram);
259
+ /**
260
+ * Replaces the layer's style.
261
+ *
262
+ * - **MapLibre layer types**: sets each property of a style program, such as one built with {@link layerStyle}.
263
+ * Properties the program doesn't set are kept. Throws on an invalid program or an unknown property.
264
+ * - **Flow layers**: replaces the whole flow style with a version 2 {@link FlowStyle}, such as one built with
265
+ * {@link flowLayerStyle}. The layer's MapLibre layers are updated in place, without reloading the source. Never
266
+ * throws: a property with a problem isn't rendered, the rest is, and {@link issues} lists the problems.
267
+ *
268
+ * @param style - Style program for a MapLibre layer, or flow style for a flow layer.
269
+ */
270
+ setStyle(style) {
271
+ if (this._options.type === "flow") {
272
+ this.replaceFlowStyle(style);
273
+ return;
274
+ }
275
+ if (typeof style !== "string") {
276
+ throw new FlowCoreError(
277
+ `${this.formattedName()}: a '${this._options.type}' layer's style is a style program string; a flow style needs type 'flow'`
278
+ );
279
+ }
280
+ const parsedProgram = ReactiveExpression.parseProgram(style);
142
281
  const props = Object.keys(parsedProgram);
143
282
  props.forEach((prop) => {
144
283
  const metadata = this.getPropertyMetadata(prop, this._options.type);
@@ -147,12 +286,34 @@ const _MapLayer = class _MapLayer {
147
286
  });
148
287
  }
149
288
  /**
150
- * Set an individual style property.
289
+ * Sets or removes one style property. Its value follows different rules for MapLibre layers and flow layers.
290
+ *
291
+ * - **MapLibre layer types**: `property` is a MapLibre paint or layout property, such as `circle-color`, and a string
292
+ * `value` is a reactive expression, so `'red'` is the color red and `'@color'` the feature property `color`.
293
+ * Throws on an unknown property or an expression that doesn't parse.
294
+ * - **Flow layers**: `property` is a {@link FlowStyle} property, such as `fillColor`, and `value` follows flow
295
+ * rules, as in {@link flowLayerStyle}: a bare value is a literal, so `'@color'` is the text `@color`; `expr('…')`
296
+ * makes a reactive expression, such as `expr('@color')` or `expr("@@hover ? 'yellow' : 'white'")`; and a
297
+ * {@link FlowStyleDataDriven} table makes an expression with the table attached. The layer's MapLibre layers are
298
+ * updated in place, without reloading the source, and {@link flowStyle} returns the edited style. Never throws:
299
+ * {@link issues} lists any problems.
300
+ *
301
+ * @example
302
+ * The same edit on a MapLibre layer and on a flow layer:
303
+ * ```js
304
+ * circleLayer.setStyleProperty('circle-stroke-color', "@@hover ? 'yellow' : 'white'");
305
+ * flowLayer.setStyleProperty('strokeColor', expr("@@hover ? 'yellow' : 'white'"));
306
+ * ```
151
307
  *
152
- * @param property Property name.
153
- * @param expression Property style expression.
308
+ * @param property - Property name.
309
+ * @param value - Property value, or `null` to remove the property.
154
310
  */
155
- setStyleProperty(property, expression) {
311
+ setStyleProperty(property, value) {
312
+ if (this._options.type === "flow") {
313
+ this.setFlowStyleProperty(property, value);
314
+ return;
315
+ }
316
+ const expression = value;
156
317
  const metadata = this.getPropertyMetadata(property, this._options.type);
157
318
  const props = metadata.type === "paint" ? this._paintProps : this._layoutProps;
158
319
  if (isNil(expression)) {
@@ -178,6 +339,182 @@ const _MapLayer = class _MapLayer {
178
339
  this._filter = expr;
179
340
  }
180
341
  }
342
+ /**
343
+ * Shows or hides every MapLibre layer of the layer, overriding the `visibility` of their style programs.
344
+ *
345
+ * @param visibility - Reactive expression or boolean. Specify `null` to leave visibility to the style programs.
346
+ * @internal
347
+ */
348
+ setVisibility(visibility) {
349
+ if (isNil(visibility)) {
350
+ this._visibility = null;
351
+ return;
352
+ }
353
+ const expr = new ReactiveExpression(isBoolean(visibility) ? String(visibility) : visibility).bindState(this._state);
354
+ if (expr.parseError) {
355
+ throw expr.parseError;
356
+ }
357
+ this._visibility = expr;
358
+ }
359
+ /**
360
+ * Makes the layer render as an ordered group of MapLibre layers, its sub-layers, instead of one. The first sub-layer
361
+ * is drawn lowest. Replacing the sub-layers updates the map in place: MapLibre layers whose IDs persist are restyled,
362
+ * and their sources aren't reloaded. The layer's own style program isn't rendered while it has sub-layers.
363
+ *
364
+ * @param subLayers - Sub-layers in draw order. An empty list renders nothing. Specify `null` to render the layer as
365
+ * one MapLibre layer again.
366
+ * @throws {@link FlowCoreError} if two sub-layers have the same ID, or a sub-layer's type, style program or filter
367
+ * is invalid. The layer's sub-layers are then unchanged.
368
+ * @internal
369
+ */
370
+ setSubLayers(subLayers) {
371
+ if (isNil(subLayers)) {
372
+ this._subLayers = null;
373
+ return;
374
+ }
375
+ const ids = /* @__PURE__ */ new Set();
376
+ const built = subLayers.map((options) => {
377
+ if (ids.has(options.id)) {
378
+ throw new FlowCoreError(`${this.formattedName()}: duplicate sub-layer id '${options.id}'`);
379
+ }
380
+ ids.add(options.id);
381
+ const layer = new _MapLayer({
382
+ id: options.id,
383
+ type: options.type,
384
+ source: options.source ?? this._options.source,
385
+ style: options.style,
386
+ filter: options.filter
387
+ }).bindState(this._state);
388
+ return { options: { ...options }, layer };
389
+ });
390
+ this._subLayers = built;
391
+ }
392
+ /**
393
+ * Loads a version 1 flow style, the legacy stored format, into a flow layer, with its geometry. The layer then keeps
394
+ * version 1: {@link setStyleProperty} writes version 1 forms, {@link setStyle} converts a version 2 style to version 1
395
+ * (keeping the layer's geometry), and {@link flowStyle} returns version 1, so the style saves back in the format old
396
+ * CAA Analyser reads. Loading and saving an unchanged style gives a deep-equal style. Never throws.
397
+ *
398
+ * Use `createVersion1FlowLayer()` (`flow-style/version1-flow-layer.ts`) to build such a layer.
399
+ *
400
+ * @param style - The style as stored: a version 1 style (`type: 'flow'`, `version` 1 or missing), or anything else,
401
+ * which {@link issues} reports.
402
+ * @param geometry - The geometry: the composite sub-layer's `type`, `circle`, `line` or `fill`.
403
+ * @internal
404
+ */
405
+ setVersion1FlowStyle(style, geometry) {
406
+ if (this._options.type !== "flow") {
407
+ throw new FlowCoreError(`${this.formattedName()}: a version 1 flow style needs type 'flow'`);
408
+ }
409
+ this.updateFlowLayer({ stored: loadStoredFlowStyle(style), version1: { geometry }, loadIssues: [] });
410
+ }
411
+ /** Replaces a flow layer's style, under the version rules of the layer. */
412
+ replaceFlowStyle(style) {
413
+ const version1 = this._flow?.version1;
414
+ this.updateFlowLayer(
415
+ version1 && flowStyleVersion(style) === 2 ? { ...this.convertToVersion1(style, version1.geometry), version1 } : { stored: loadStoredFlowStyle(style), version1, loadIssues: [] }
416
+ );
417
+ }
418
+ /**
419
+ * A version 2 style, written in version 1 form for a version 1 layer: each property as {@link setStyleProperty}
420
+ * writes it. The layer's geometry stays; a different one in the style is a warning.
421
+ */
422
+ convertToVersion1(style, geometry) {
423
+ let stored = loadStoredFlowStyle({ type: "flow", version: 1 });
424
+ for (const key of Object.keys(style)) {
425
+ if (key !== "type" && key !== "version") {
426
+ stored = setStoredFlowStyleProperty(stored, key, style[key]);
427
+ }
428
+ }
429
+ const loadIssues = style.type === geometry ? [] : [
430
+ {
431
+ path: "type",
432
+ message: `The layer keeps version 1 and its geometry, ${describeValue(geometry)}: the style's type, ${describeValue(style.type)}, is not used.`,
433
+ severity: "warning"
434
+ }
435
+ ];
436
+ return { stored, loadIssues };
437
+ }
438
+ /** Sets or removes one property of a flow layer's style, under the style's version rules. */
439
+ setFlowStyleProperty(property, value) {
440
+ const flow = this._flow;
441
+ try {
442
+ this.updateFlowLayer({
443
+ ...flow,
444
+ stored: setStoredFlowStyleProperty(flow.stored, property, value),
445
+ loadIssues: []
446
+ });
447
+ } catch (e) {
448
+ this._issues = [...this._issues, unreadable(property, e)];
449
+ }
450
+ }
451
+ /** Sets a flow layer's style, and renders it as sub-layers. */
452
+ updateFlowLayer(flow) {
453
+ this._flow = flow;
454
+ const { stored, version1, loadIssues } = flow;
455
+ const issues = [...loadIssues];
456
+ let subLayers = [];
457
+ if (!version1 && stored.version === 1 && stored.style?.type === "flow") {
458
+ issues.push({
459
+ path: "version",
460
+ message: "A flow layer takes a version 2 flow style, with `version: 2` and its geometry as `type`. Build one with `flowLayerStyle()`.",
461
+ severity: "error"
462
+ });
463
+ } else {
464
+ const expanded = expandFlowStyle(this._options.id, stored.style, {
465
+ geometry: version1?.geometry,
466
+ interactive: this._invalidInteractive
467
+ });
468
+ issues.push(...expanded.issues);
469
+ subLayers = expanded.subLayers.map(({ id, type, style, interactive }) => ({
470
+ id,
471
+ type,
472
+ style,
473
+ interactive,
474
+ metadata: { flowLayer: this._options.id }
475
+ }));
476
+ }
477
+ try {
478
+ this.setSubLayers(subLayers);
479
+ } catch (e) {
480
+ issues.push(unreadable("", e));
481
+ this.setSubLayers([]);
482
+ }
483
+ this._issues = issues;
484
+ }
485
+ /** The MapLibre layer specification of a sub-layer, with the layer's shared settings applied. */
486
+ subLayerSpecification({ options, layer }) {
487
+ const { minzoom: _minzoom, maxzoom: _maxzoom, filter, ...spec } = layer.layerSpecification;
488
+ const result = { ...spec };
489
+ const sourceLayer = options.source ? options.sourceLayer : options.sourceLayer ?? this._options.sourceLayer;
490
+ if (isDefined(sourceLayer)) {
491
+ result["source-layer"] = sourceLayer;
492
+ }
493
+ const minZoom = maxDefined(this._options.minZoom, options.minZoom);
494
+ const maxZoom = minDefined(this._options.maxZoom, options.maxZoom);
495
+ if (isDefined(minZoom)) {
496
+ result.minzoom = minZoom;
497
+ }
498
+ if (isDefined(maxZoom)) {
499
+ result.maxzoom = maxZoom;
500
+ }
501
+ const layerFilter = this._filter?.maplibreExpression;
502
+ if (isDefined(layerFilter) && isDefined(filter)) {
503
+ result.filter = ["all", layerFilter, filter];
504
+ } else if (isDefined(layerFilter) || isDefined(filter)) {
505
+ result.filter = layerFilter ?? filter;
506
+ }
507
+ if (this._visibility) {
508
+ result.layout = { ...result.layout, visibility: this.visibilityValue(this._visibility) };
509
+ }
510
+ if (isDefined(this._options.metadata) || isDefined(options.metadata)) {
511
+ result.metadata = { ...toJS(this._options.metadata), ...toJS(options.metadata) };
512
+ }
513
+ return result;
514
+ }
515
+ visibilityValue(expr) {
516
+ return expr.value ? "visible" : "none";
517
+ }
181
518
  formattedName(id) {
182
519
  return `MapLayer<${id || this._options.id}>`;
183
520
  }
@@ -219,5 +556,17 @@ __publicField(_MapLayer, "_defaultOptions", {
219
556
  maxZoom: 18
220
557
  });
221
558
  let MapLayer = _MapLayer;
559
+ function unreadable(path, e) {
560
+ return { path, message: `The style could not be rendered: ${e?.message ?? String(e)}`, severity: "error" };
561
+ }
562
+ function describeValue(value) {
563
+ return typeof value === "string" ? `'${value}'` : JSON.stringify(value) ?? String(value);
564
+ }
565
+ function maxDefined(a, b) {
566
+ return isDefined(a) && isDefined(b) ? Math.max(a, b) : a ?? b;
567
+ }
568
+ function minDefined(a, b) {
569
+ return isDefined(a) && isDefined(b) ? Math.min(a, b) : a ?? b;
570
+ }
222
571
 
223
572
  export { MapLayer };
@@ -25,6 +25,7 @@ const _MapStyle = class _MapStyle {
25
25
  _layerOrder: observable,
26
26
  _baseStyle: observable.ref,
27
27
  //computed
28
+ renderedStyle: computed,
28
29
  styleSpecification: computed,
29
30
  // actions
30
31
  bindState: action,
@@ -38,42 +39,107 @@ const _MapStyle = class _MapStyle {
38
39
  );
39
40
  }
40
41
  get styleSpecification() {
42
+ return this.renderedStyle.spec;
43
+ }
44
+ /**
45
+ * Problems found while building {@link styleSpecification}: each names a MapLibre layer that was left out, because
46
+ * another layer or the base style already has its ID, or its source isn't on the map.
47
+ *
48
+ * @internal
49
+ */
50
+ get styleProblems() {
51
+ return this.renderedStyle.problems;
52
+ }
53
+ /**
54
+ * The ID of the {@link MapLayer} that rendered each MapLibre layer in {@link styleSpecification}, by MapLibre layer
55
+ * ID. Base style layers aren't included, unless a MapLayer restyled them.
56
+ *
57
+ * @internal
58
+ */
59
+ get maplibreLayerOwners() {
60
+ return this.renderedStyle.owners;
61
+ }
62
+ /** The style specification, the problems found while building it, and which MapLayer rendered each MapLibre layer. */
63
+ get renderedStyle() {
41
64
  const spec = {
42
65
  ...this._baseStyle,
43
66
  sources: { ...this._baseStyle.sources },
44
67
  layers: [...this._baseStyle.layers]
45
68
  };
69
+ const problems = [];
70
+ const baseLayerIds = new Set(this._baseStyle.layers.map((l) => l.id));
71
+ const ownIds = new Set(this._layerOrder.filter((id) => this._layers[id].maplibreLayerIds.includes(id)));
72
+ const owners = /* @__PURE__ */ new Map();
73
+ const placed = /* @__PURE__ */ new Map();
46
74
  Object.values(this._sources).forEach((source) => {
47
75
  spec.sources[source.id] = source.dataSourceSpecification;
48
76
  });
49
77
  this._layerOrder.forEach((id) => {
50
78
  const layer = this._layers[id];
51
- const layerSpec = layer.layerSpecification;
52
- const baseLayerIndex = spec.layers.findIndex((l) => l.id === id);
53
- if (baseLayerIndex >= 0) {
54
- const baseLayer = spec.layers[baseLayerIndex];
55
- const mergedBaseLayer = {
56
- ...baseLayer,
57
- paint: {
58
- ...baseLayer.paint,
59
- ...layerSpec.paint
60
- },
61
- layout: {
62
- ...baseLayer.layout,
63
- ...layerSpec.layout
64
- }
65
- };
66
- spec.layers.splice(baseLayerIndex, 1, mergedBaseLayer);
67
- } else {
68
- const source = spec.sources[layer.source];
69
- if (source.type === "vector" && isNil(layerSpec["source-layer"])) {
70
- layerSpec["source-layer"] = "geometry";
79
+ if (!layer.subLayers) {
80
+ owners.set(id, id);
81
+ const layerSpec = layer.layerSpecification;
82
+ const baseLayerIndex = baseLayerIds.has(id) ? spec.layers.findIndex((l) => l.id === id) : -1;
83
+ if (baseLayerIndex >= 0) {
84
+ const baseLayer = spec.layers[baseLayerIndex];
85
+ const mergedBaseLayer = {
86
+ ...baseLayer,
87
+ paint: {
88
+ ...baseLayer.paint,
89
+ ...layerSpec.paint
90
+ },
91
+ layout: {
92
+ ...baseLayer.layout,
93
+ ...layerSpec.layout
94
+ },
95
+ ...layerSpec.metadata && { metadata: { ...baseLayer.metadata, ...layerSpec.metadata } }
96
+ };
97
+ spec.layers.splice(baseLayerIndex, 1, mergedBaseLayer);
98
+ } else {
99
+ const layerIndex = this.layerInsertionPoint(layer, layerSpec.type, spec, placed);
100
+ spec.layers.splice(layerIndex, 0, this.withDefaultSourceLayer(layerSpec, spec));
71
101
  }
72
- const layerIndex = this.layerInsertionPoint(layer, spec);
73
- spec.layers.splice(layerIndex, 0, layer.layerSpecification);
102
+ placed.set(id, [id]);
103
+ return;
74
104
  }
105
+ const layerSpecs = layer.layerSpecifications.filter((layerSpec) => {
106
+ if (baseLayerIds.has(layerSpec.id)) {
107
+ problems.push(this.duplicateIdProblem(layer, layerSpec.id, "the base style"));
108
+ return false;
109
+ } else if (owners.has(layerSpec.id)) {
110
+ problems.push(this.duplicateIdProblem(layer, layerSpec.id, owners.get(layerSpec.id)));
111
+ return false;
112
+ } else if (layerSpec.id !== id && ownIds.has(layerSpec.id)) {
113
+ problems.push(this.duplicateIdProblem(layer, layerSpec.id, layerSpec.id));
114
+ return false;
115
+ } else if (!spec.sources[layerSpec.source]) {
116
+ problems.push(
117
+ `${this.formattedName}: layer '${id}' leaves out MapLibre layer '${layerSpec.id}', whose source '${layerSpec.source}' is not on the map`
118
+ );
119
+ return false;
120
+ }
121
+ return true;
122
+ });
123
+ if (layer.above || layer.below) {
124
+ const layerIndex = this.layerInsertionPoint(layer, void 0, spec, placed);
125
+ spec.layers.splice(
126
+ layerIndex,
127
+ 0,
128
+ ...layerSpecs.map((layerSpec) => this.withDefaultSourceLayer(layerSpec, spec))
129
+ );
130
+ } else {
131
+ layerSpecs.forEach((layerSpec) => {
132
+ const layerIndex = this.layerInsertionPoint(layer, layerSpec.type, spec, placed);
133
+ spec.layers.splice(layerIndex, 0, this.withDefaultSourceLayer(layerSpec, spec));
134
+ });
135
+ }
136
+ layerSpecs.forEach((layerSpec) => owners.set(layerSpec.id, id));
137
+ placed.set(
138
+ id,
139
+ layerSpecs.map((layerSpec) => layerSpec.id)
140
+ );
75
141
  });
76
- return spec;
142
+ return { spec, problems, owners };
77
143
  }
78
144
  get formattedName() {
79
145
  return `MapStyle<${this._baseStyle.id}>`;
@@ -99,7 +165,7 @@ const _MapStyle = class _MapStyle {
99
165
  if (!this._sources[id]) {
100
166
  throw new FlowCoreError(`${this.formattedName}: no source with id '${id}'`);
101
167
  }
102
- const linkedLayers = Object.values(this._layers).filter((layer) => layer.source === id).map((layer) => layer.id);
168
+ const linkedLayers = Object.values(this._layers).filter((layer) => layer.sourceIds.includes(id)).map((layer) => layer.id);
103
169
  if (removeLayers) {
104
170
  linkedLayers.forEach((id2) => this.removeLayer(id2));
105
171
  } else if (linkedLayers.length) {
@@ -121,9 +187,23 @@ const _MapStyle = class _MapStyle {
121
187
  return Object.values(this._sources).filter((source) => filter ? filter(source) : true);
122
188
  }
123
189
  addLayer(layer) {
124
- if (!this._sources[layer.source] && !this._baseStyle.sources[layer.source]) {
125
- throw new FlowCoreError(`${this.formattedName}: no source with id '${layer.source}'`);
190
+ layer.sourceIds.forEach((sourceId) => {
191
+ if (!this._sources[sourceId] && !this._baseStyle.sources[sourceId]) {
192
+ throw new FlowCoreError(`${this.formattedName}: no source with id '${sourceId}'`);
193
+ }
194
+ });
195
+ if (this._layers[layer.id]) {
196
+ throw new FlowCoreError(`${this.formattedName}: a layer with id '${layer.id}' is already on the map`);
126
197
  }
198
+ const maplibreIds = new Set(layer.maplibreLayerIds);
199
+ Object.values(this._layers).forEach((other) => {
200
+ const shared = other.maplibreLayerIds.find((maplibreId) => maplibreIds.has(maplibreId));
201
+ if (shared) {
202
+ throw new FlowCoreError(
203
+ `${this.formattedName}: layer '${layer.id}' uses MapLibre layer id '${shared}', which layer '${other.id}' already uses`
204
+ );
205
+ }
206
+ });
127
207
  this._layers[layer.id] = layer;
128
208
  this._layerOrder.push(layer.id);
129
209
  layer.bindState(this._state);
@@ -148,16 +228,33 @@ const _MapStyle = class _MapStyle {
148
228
  getLayers(filter) {
149
229
  return this._layerOrder.map((layerId) => this._layers[layerId]).filter((layer) => filter ? filter(layer) : true);
150
230
  }
151
- layerInsertionPoint(layer, spec) {
231
+ duplicateIdProblem(layer, maplibreId, owner) {
232
+ const usedBy = owner === "the base style" ? owner : `layer '${owner}'`;
233
+ return `${this.formattedName}: layer '${layer.id}' leaves out MapLibre layer '${maplibreId}', whose id ${usedBy} already uses`;
234
+ }
235
+ /** Defaults the source layer to 'geometry' if missing and the source type is 'vector'. */
236
+ withDefaultSourceLayer(layerSpec, spec) {
237
+ if (spec.sources[layerSpec.source]?.type === "vector" && isNil(layerSpec["source-layer"])) {
238
+ return { ...layerSpec, "source-layer": "geometry" };
239
+ }
240
+ return layerSpec;
241
+ }
242
+ /**
243
+ * Where to insert a MapLibre layer of a type for a layer: above or below the layer's `above` or `below` layer, or
244
+ * else at the base style's insertion point for the type. `above` and `below` name a MapLibre layer or a MapLayer;
245
+ * for a MapLayer with sub-layers, the group's top or bottom MapLibre layer.
246
+ */
247
+ layerInsertionPoint(layer, type, spec, placed) {
152
248
  let insertionIndex;
249
+ const indexes = (id) => (placed.get(id) ?? [id]).map((layerId) => spec.layers.findIndex((l) => l.id === layerId)).filter((i) => i >= 0);
153
250
  if (layer.above) {
154
- insertionIndex = spec.layers.findIndex((l) => l.id === layer.above);
155
- if (insertionIndex >= 0)
156
- insertionIndex++;
251
+ const found = indexes(layer.above);
252
+ insertionIndex = found.length ? Math.max(...found) + 1 : -1;
157
253
  } else if (layer.below) {
158
- insertionIndex = spec.layers.findIndex((l) => l.id === layer.below);
254
+ const found = indexes(layer.below);
255
+ insertionIndex = found.length ? Math.min(...found) : -1;
159
256
  } else {
160
- const below = spec.metadata?.insertionPoints?.[layer.type];
257
+ const below = spec.metadata?.insertionPoints?.[type ?? layer.type];
161
258
  insertionIndex = spec.layers.findIndex((l) => l.id === below);
162
259
  }
163
260
  if (insertionIndex === -1) {
@@ -1,3 +1,3 @@
1
- const version = "4.1.8";
1
+ const version = "4.2.0";
2
2
 
3
3
  export { version };