@emuanalytics/flow-rdf-core 4.2.0 → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,8 @@
1
1
  import * as maplibreSpec from '@emuanalytics/maplibre-gl-style-spec';
2
- import { makeObservable, observable, computed, action, toJS } from 'mobx';
3
- import { isNil, isBoolean, isDefined, isObjectFull } from '../utils/type-checks.mjs';
2
+ import { makeObservable, observable, computed, action, toJS, comparer } from 'mobx';
3
+ import { isNil, isBoolean, isDefined, isObjectFull, isString, isIn } from '../utils/type-checks.mjs';
4
+ import { expandCompositeLayer } from './composite/expand.mjs';
5
+ import { saveCompositeLayerSpec, loadCompositeLayerSpec } from './composite/stored-format.mjs';
4
6
  import { expandFlowStyle } from './flow-style/expand.mjs';
5
7
  import { saveStoredFlowStyle, loadStoredFlowStyle, setStoredFlowStyleProperty } from './flow-style/stored-format.mjs';
6
8
  import { flowStyleVersion } from './flow-style/values.mjs';
@@ -22,20 +24,25 @@ const _MapLayer = class _MapLayer {
22
24
  __publicField(this, "_layoutProps", {});
23
25
  __publicField(this, "_visibility", null);
24
26
  __publicField(this, "_subLayers", null);
27
+ __publicField(this, "_ownedSources", null);
28
+ __publicField(this, "_ownedSourcesListeners", /* @__PURE__ */ new Set());
25
29
  __publicField(this, "_flow", null);
30
+ __publicField(this, "_composite", null);
31
+ __publicField(this, "_mapSources", null);
26
32
  __publicField(this, "_issues", []);
27
33
  // A flow layer's `interactive` option when it isn't a boolean: the default applies, with a warning in version 2
28
34
  __publicField(this, "_invalidInteractive");
29
- this._options = {
30
- ..._MapLayer._defaultOptions,
31
- ...options
32
- };
35
+ const isComposite = options.type === "composite";
36
+ this._options = isComposite ? (
37
+ // A composite layer's own zoom range applies only if set: its sub-layers have theirs
38
+ { interactive: true, ...options, source: "" }
39
+ ) : { ..._MapLayer._defaultOptions, ...options };
33
40
  const isFlow = options.type === "flow";
34
41
  if (isFlow && !isNil(options.interactive) && !isBoolean(options.interactive)) {
35
42
  this._invalidInteractive = options.interactive;
36
43
  this._options.interactive = true;
37
44
  }
38
- if (!isFlow) {
45
+ if (!isFlow && !isComposite) {
39
46
  this.getPropertyMetadata("visibility", options.type);
40
47
  }
41
48
  makeObservable(
@@ -48,11 +55,15 @@ const _MapLayer = class _MapLayer {
48
55
  _options: observable,
49
56
  _visibility: observable.ref,
50
57
  _subLayers: observable.ref,
58
+ _ownedSources: observable.ref,
51
59
  _flow: observable.ref,
60
+ _composite: observable.ref,
61
+ _mapSources: observable.ref,
52
62
  _issues: observable.ref,
53
63
  //computed
54
64
  layerSpecification: computed,
55
65
  layerSpecifications: computed,
66
+ compositeIssues: computed,
56
67
  // actions
57
68
  bindState: action,
58
69
  setMinZoom: action,
@@ -65,6 +76,8 @@ const _MapLayer = class _MapLayer {
65
76
  setFilter: action,
66
77
  setVisibility: action,
67
78
  setSubLayers: action,
79
+ setOwnedSources: action,
80
+ setMapSources: action,
68
81
  setVersion1FlowStyle: action
69
82
  },
70
83
  { name: this.formattedName(options.id) }
@@ -72,7 +85,10 @@ const _MapLayer = class _MapLayer {
72
85
  if (options.filter) {
73
86
  this.setFilter(options.filter);
74
87
  }
75
- if (isFlow) {
88
+ if (isDefined(options.visibility)) {
89
+ this.setVisibility(options.visibility);
90
+ }
91
+ if (isFlow || isComposite) {
76
92
  this.setStyle(options.style);
77
93
  } else if (options.style) {
78
94
  this.setStyle(options.style);
@@ -176,6 +192,14 @@ const _MapLayer = class _MapLayer {
176
192
  get subLayers() {
177
193
  return this._subLayers ? this._subLayers.map(({ options }) => options) : null;
178
194
  }
195
+ /**
196
+ * The data sources the layer brings with it (see {@link setOwnedSources}), or `null` for none.
197
+ *
198
+ * @internal
199
+ */
200
+ get ownedSources() {
201
+ return this._ownedSources;
202
+ }
179
203
  /**
180
204
  * Layer metadata, copied to the `metadata` of the layer's MapLibre layers.
181
205
  *
@@ -196,16 +220,31 @@ const _MapLayer = class _MapLayer {
196
220
  return this._flow ? saveStoredFlowStyle(this._flow.stored) : void 0;
197
221
  }
198
222
  /**
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.
223
+ * A composite layer's spec, in its stored format and version (a version 1 spec stays version 1), ready to save. A
224
+ * copy: change the layer with {@link setStyle}. `undefined` for any other layer type.
225
+ *
226
+ * Reading it in a MobX reaction, or a component that renders from state, tracks changes to the spec.
227
+ *
228
+ * @experimental
229
+ */
230
+ get compositeSpec() {
231
+ return this._composite ? saveCompositeLayerSpec(this._composite.stored) : void 0;
232
+ }
233
+ /**
234
+ * The problems with a flow layer's style or a composite layer's spec, updated whenever the style changes. An `error`
235
+ * means a property, a sub-layer, a data source or the whole style isn't rendered; a `warning` means it is rendered
236
+ * anyway. Each has the path of the problem in the style or spec, such as `layers[1].style.fillColor`. Empty for a
237
+ * MapLibre layer, which throws on a bad style instead.
238
+ *
239
+ * A composite layer on a map also lists each sub-layer whose data source is neither in the spec nor on the map, and
240
+ * so isn't rendered, and the map emits each new issue of a composite layer as an `error` event.
202
241
  *
203
242
  * The list is observable: read it in a MobX reaction to follow it.
204
243
  *
205
244
  * @experimental
206
245
  */
207
246
  get issues() {
208
- return this._issues;
247
+ return this._composite ? this.compositeIssues : this._issues;
209
248
  }
210
249
  get id() {
211
250
  return this._options.id;
@@ -213,6 +252,7 @@ const _MapLayer = class _MapLayer {
213
252
  get type() {
214
253
  return this._options.type;
215
254
  }
255
+ /** The data source the layer displays. Empty for a composite layer, whose sub-layers name their own. */
216
256
  get source() {
217
257
  return this._options.source;
218
258
  }
@@ -264,14 +304,22 @@ const _MapLayer = class _MapLayer {
264
304
  * - **Flow layers**: replaces the whole flow style with a version 2 {@link FlowStyle}, such as one built with
265
305
  * {@link flowLayerStyle}. The layer's MapLibre layers are updated in place, without reloading the source. Never
266
306
  * throws: a property with a problem isn't rendered, the rest is, and {@link issues} lists the problems.
307
+ * - **Composite layers**: replaces the whole spec with a {@link CompositeLayerSpecification}, such as one edited with
308
+ * {@link updateCompositeFlowStyle}, in one update of the map: MapLibre layers whose IDs persist keep their place
309
+ * and are restyled, data sources whose options are unchanged aren't reloaded, and a spec equal to the current one
310
+ * changes nothing. The spec keeps its own version. Never throws: {@link issues} lists the problems.
267
311
  *
268
- * @param style - Style program for a MapLibre layer, or flow style for a flow layer.
312
+ * @param style - Style program for a MapLibre layer, flow style for a flow layer, or spec for a composite layer.
269
313
  */
270
314
  setStyle(style) {
271
315
  if (this._options.type === "flow") {
272
316
  this.replaceFlowStyle(style);
273
317
  return;
274
318
  }
319
+ if (this._options.type === "composite") {
320
+ this.replaceCompositeSpec(style);
321
+ return;
322
+ }
275
323
  if (typeof style !== "string") {
276
324
  throw new FlowCoreError(
277
325
  `${this.formattedName()}: a '${this._options.type}' layer's style is a style program string; a flow style needs type 'flow'`
@@ -297,6 +345,8 @@ const _MapLayer = class _MapLayer {
297
345
  * {@link FlowStyleDataDriven} table makes an expression with the table attached. The layer's MapLibre layers are
298
346
  * updated in place, without reloading the source, and {@link flowStyle} returns the edited style. Never throws:
299
347
  * {@link issues} lists any problems.
348
+ * - **Composite layers**: throws. Edit the spec instead, with {@link updateCompositeFlowStyle}, and give it to
349
+ * {@link setStyle}.
300
350
  *
301
351
  * @example
302
352
  * The same edit on a MapLibre layer and on a flow layer:
@@ -313,6 +363,11 @@ const _MapLayer = class _MapLayer {
313
363
  this.setFlowStyleProperty(property, value);
314
364
  return;
315
365
  }
366
+ if (this._options.type === "composite") {
367
+ throw new FlowCoreError(
368
+ `${this.formattedName()}: a composite layer is edited through its spec: give an edited spec, such as one from updateCompositeFlowStyle(), to setStyle()`
369
+ );
370
+ }
316
371
  const expression = value;
317
372
  const metadata = this.getPropertyMetadata(property, this._options.type);
318
373
  const props = metadata.type === "paint" ? this._paintProps : this._layoutProps;
@@ -326,9 +381,16 @@ const _MapLayer = class _MapLayer {
326
381
  props[property] = expr;
327
382
  }
328
383
  }
384
+ /**
385
+ * Sets or clears the layer's filter.
386
+ *
387
+ * @param expression - Reactive expression that a feature must match to be drawn. Specify `null`, or an empty
388
+ * string, to clear the filter.
389
+ * @throws `FlowCoreExpressionError` if the expression doesn't parse.
390
+ */
329
391
  setFilter(expression) {
330
392
  this._filter = null;
331
- if (isDefined(expression)) {
393
+ if (isString(expression) && expression.trim() !== "") {
332
394
  let expr = new ReactiveExpression(expression).bindState(this._state);
333
395
  if (expr.parseError) {
334
396
  throw expr.parseError;
@@ -340,10 +402,13 @@ const _MapLayer = class _MapLayer {
340
402
  }
341
403
  }
342
404
  /**
343
- * Shows or hides every MapLibre layer of the layer, overriding the `visibility` of their style programs.
405
+ * Shows or hides the layer, and every MapLibre layer of a flow or composite layer, overriding the `visibility` of
406
+ * their styles.
344
407
  *
345
- * @param visibility - Reactive expression or boolean. Specify `null` to leave visibility to the style programs.
346
- * @internal
408
+ * @param visibility - Reactive expression, such as `'$showAirports'`, or boolean. Specify `null` to leave visibility
409
+ * to the styles.
410
+ * @throws `FlowCoreExpressionError` if the expression doesn't parse.
411
+ * @experimental
347
412
  */
348
413
  setVisibility(visibility) {
349
414
  if (isNil(visibility)) {
@@ -389,6 +454,57 @@ const _MapLayer = class _MapLayer {
389
454
  });
390
455
  this._subLayers = built;
391
456
  }
457
+ /**
458
+ * Declares the data sources the layer brings with it, so that its sub-layers can display them. The map's
459
+ * `MapStyle` adds each one, by ID, while a layer on the map brings it, and shares it between the layers that
460
+ * bring the same ID: the first layer added to the map gives its options, and a later one that gives different
461
+ * options is reported as a style problem. A source the app added with the same ID is used instead, and is never
462
+ * removed. Changing the list updates the map in place: a source whose options are unchanged keeps its
463
+ * `MapDataSource`, so it isn't reloaded.
464
+ *
465
+ * @param sources - Options of each data source. Specify `null`, or an empty list, to bring none.
466
+ * @throws {@link FlowCoreError} if two sources have the same ID, or a source's type is invalid. The layer's sources
467
+ * are then unchanged.
468
+ * @internal
469
+ */
470
+ setOwnedSources(sources) {
471
+ const ids = /* @__PURE__ */ new Set();
472
+ sources?.forEach((source) => {
473
+ if (ids.has(source.id)) {
474
+ throw new FlowCoreError(`${this.formattedName()}: duplicate data source id '${source.id}'`);
475
+ }
476
+ ids.add(source.id);
477
+ if (!isIn(source.type, ["vector", "geojson", "raster"])) {
478
+ throw new FlowCoreError(
479
+ `${this.formattedName()}: data source '${source.id}' has unrecognized type '${source.type}'`
480
+ );
481
+ }
482
+ });
483
+ this._ownedSources = sources?.length ? Object.freeze(sources.map((source) => ({ ...source }))) : null;
484
+ this._ownedSourcesListeners.forEach((listener) => listener());
485
+ }
486
+ /**
487
+ * Calls a listener, synchronously, whenever {@link setOwnedSources} is called: `MapStyle` uses it to add and
488
+ * remove the sources in the same action.
489
+ *
490
+ * @returns A function that removes the listener.
491
+ * @internal
492
+ */
493
+ observeOwnedSources(listener) {
494
+ this._ownedSourcesListeners.add(listener);
495
+ return () => this._ownedSourcesListeners.delete(listener);
496
+ }
497
+ /**
498
+ * Tells the layer which data sources are on its map, while it is on one: a composite layer lists each sub-layer
499
+ * whose data source is missing in {@link issues}. `MapStyle` sets it when the layer is added, and clears it when the
500
+ * layer is removed.
501
+ *
502
+ * @param lookup - Whether a data source ID is on the map, read reactively; `null` when the layer isn't on a map.
503
+ * @internal
504
+ */
505
+ setMapSources(lookup) {
506
+ this._mapSources = lookup;
507
+ }
392
508
  /**
393
509
  * Loads a version 1 flow style, the legacy stored format, into a flow layer, with its geometry. The layer then keeps
394
510
  * version 1: {@link setStyleProperty} writes version 1 forms, {@link setStyle} converts a version 2 style to version 1
@@ -482,6 +598,79 @@ const _MapLayer = class _MapLayer {
482
598
  }
483
599
  this._issues = issues;
484
600
  }
601
+ /** Replaces a composite layer's spec: its sources and sub-layers, in the action that calls it. */
602
+ replaceCompositeSpec(spec) {
603
+ if (this._composite && comparer.structural(this._composite.stored.spec, spec)) {
604
+ return;
605
+ }
606
+ const stored = loadCompositeLayerSpec(spec);
607
+ const expanded = expandCompositeLayer(this._options.id, stored.spec);
608
+ const issues = [...expanded.issues];
609
+ try {
610
+ this.setOwnedSources(expanded.sources);
611
+ } catch (e) {
612
+ issues.push(unreadable("dataSources", e));
613
+ this.setOwnedSources(null);
614
+ }
615
+ try {
616
+ this.setSubLayers(expanded.subLayers);
617
+ } catch {
618
+ const valid = expanded.subLayers.filter((subLayer) => {
619
+ try {
620
+ new _MapLayer({
621
+ id: subLayer.id,
622
+ type: subLayer.type,
623
+ source: "",
624
+ style: subLayer.style,
625
+ filter: subLayer.filter
626
+ });
627
+ return true;
628
+ } catch (e) {
629
+ issues.push(unreadable(this.compositeSubLayerPath(stored.spec, subLayer), e));
630
+ return false;
631
+ }
632
+ });
633
+ this.setSubLayers(valid);
634
+ }
635
+ this._composite = { stored, expanded: { ...expanded, issues } };
636
+ }
637
+ /**
638
+ * A composite layer's issues: the expansion's, and, on a map, its sub-layers' missing data sources. A sub-layer
639
+ * source that isn't in the spec's data sources is a warning in the spec alone; on the map it's nothing if the map
640
+ * has the source, and an error if it doesn't, since the sub-layer then isn't rendered.
641
+ */
642
+ get compositeIssues() {
643
+ const { stored, expanded } = this._composite;
644
+ const hasSource = this._mapSources;
645
+ if (!hasSource) {
646
+ return expanded.issues;
647
+ }
648
+ return expanded.issues.flatMap((issue) => {
649
+ const index = /^layers\[(\d+)\]\.source$/.exec(issue.path)?.[1];
650
+ if (issue.severity !== "warning" || index === void 0) {
651
+ return [issue];
652
+ }
653
+ const { layers, dataSources } = stored.spec;
654
+ const source = layers[Number(index)].source;
655
+ if (hasSource(source)) {
656
+ return [];
657
+ }
658
+ const inSpec = Array.isArray(dataSources) && dataSources.some((dataSource) => dataSource?.id === source);
659
+ return [
660
+ {
661
+ path: issue.path,
662
+ message: `Data source '${source}' isn't on the map: ` + (inSpec ? "it is in `dataSources` but isn't added (see its errors)" : "it isn't in `dataSources`, and the application hasn't added it") + ". The sub-layer isn't rendered.",
663
+ severity: "error"
664
+ }
665
+ ];
666
+ });
667
+ }
668
+ /** The spec path of the sub-layer that gave a MapLibre layer, from its metadata. */
669
+ compositeSubLayerPath(spec, subLayer) {
670
+ const id = subLayer.metadata?.compositeSubLayer;
671
+ const index = (spec.layers ?? []).findIndex((layer) => layer?.id === id);
672
+ return index >= 0 ? `layers[${index}]` : "";
673
+ }
485
674
  /** The MapLibre layer specification of a sub-layer, with the layer's shared settings applied. */
486
675
  subLayerSpecification({ options, layer }) {
487
676
  const { minzoom: _minzoom, maxzoom: _maxzoom, filter, ...spec } = layer.layerSpecification;
@@ -1,5 +1,6 @@
1
- import { makeObservable, observable, computed, action } from 'mobx';
1
+ import { makeObservable, observable, computed, action, comparer } from 'mobx';
2
2
  import { isNil } from '../utils/type-checks.mjs';
3
+ import { MapDataSource } from './map-data-source.mjs';
3
4
  import { FlowCoreError } from '../errors/flow-error.mjs';
4
5
 
5
6
  var __defProp = Object.defineProperty;
@@ -9,18 +10,34 @@ var __publicField = (obj, key, value) => {
9
10
  return value;
10
11
  };
11
12
  const _MapStyle = class _MapStyle {
12
- constructor() {
13
+ /**
14
+ * Each map creates its own map style, with hooks of its own.
15
+ *
16
+ * @param hooks - What the map does as the style adds and removes the data sources that layers bring.
17
+ *
18
+ * @internal
19
+ */
20
+ constructor(hooks = {}) {
13
21
  __publicField(this, "_state", null);
14
22
  __publicField(this, "_baseStyle");
23
+ __publicField(this, "_hooks");
24
+ // Sources the app added
15
25
  __publicField(this, "_sources", {});
26
+ // Sources that layers brought, by ID, with the options each was made from
27
+ __publicField(this, "_ownedSources", {});
28
+ __publicField(this, "_ownedSourceOptions", /* @__PURE__ */ new Map());
29
+ // MapLayer ID to the function that stops following the layer's owned sources
30
+ __publicField(this, "_ownedSourceDisposers", /* @__PURE__ */ new Map());
16
31
  __publicField(this, "_layers", {});
17
32
  __publicField(this, "_layerOrder", []);
18
33
  this._baseStyle = _MapStyle._defaultBaseStyle;
34
+ this._hooks = hooks;
19
35
  makeObservable(
20
36
  this,
21
37
  {
22
38
  //observable
23
39
  _sources: observable,
40
+ _ownedSources: observable.shallow,
24
41
  _layers: observable,
25
42
  _layerOrder: observable,
26
43
  _baseStyle: observable.ref,
@@ -33,7 +50,8 @@ const _MapStyle = class _MapStyle {
33
50
  addSource: action,
34
51
  removeSource: action,
35
52
  addLayer: action,
36
- removeLayer: action
53
+ removeLayer: action,
54
+ syncOwnedSources: action
37
55
  },
38
56
  { name: this.formattedName }
39
57
  );
@@ -71,9 +89,10 @@ const _MapStyle = class _MapStyle {
71
89
  const ownIds = new Set(this._layerOrder.filter((id) => this._layers[id].maplibreLayerIds.includes(id)));
72
90
  const owners = /* @__PURE__ */ new Map();
73
91
  const placed = /* @__PURE__ */ new Map();
74
- Object.values(this._sources).forEach((source) => {
92
+ [...Object.values(this._sources), ...Object.values(this._ownedSources)].forEach((source) => {
75
93
  spec.sources[source.id] = source.dataSourceSpecification;
76
94
  });
95
+ problems.push(...this.ownedSourceConflicts());
77
96
  this._layerOrder.forEach((id) => {
78
97
  const layer = this._layers[id];
79
98
  if (!layer.subLayers) {
@@ -113,6 +132,9 @@ const _MapStyle = class _MapStyle {
113
132
  problems.push(this.duplicateIdProblem(layer, layerSpec.id, layerSpec.id));
114
133
  return false;
115
134
  } else if (!spec.sources[layerSpec.source]) {
135
+ if (layer.type === "composite") {
136
+ return false;
137
+ }
116
138
  problems.push(
117
139
  `${this.formattedName}: layer '${id}' leaves out MapLibre layer '${layerSpec.id}', whose source '${layerSpec.source}' is not on the map`
118
140
  );
@@ -147,25 +169,38 @@ const _MapStyle = class _MapStyle {
147
169
  bindState(state) {
148
170
  this._state = state;
149
171
  state.transaction(() => {
150
- Object.values(this._sources).forEach((source) => source.bindState(state));
172
+ this.getSources().forEach((source) => source.bindState(state));
151
173
  Object.values(this._layers).forEach((layer) => layer.bindState(state));
152
174
  });
153
175
  return this;
154
176
  }
155
177
  setBaseStyle(style) {
156
178
  this._baseStyle = style ? Object.freeze({ ...style }) : _MapStyle._defaultBaseStyle;
179
+ this.syncOwnedSources();
157
180
  return this;
158
181
  }
182
+ /**
183
+ * Adds a data source. A source that layers brought with the same ID is removed: the app's takes its place.
184
+ */
159
185
  addSource(source) {
160
186
  this._sources[source.id] = source;
161
187
  source.bindState(this._state);
188
+ this.syncOwnedSources();
162
189
  return this;
163
190
  }
191
+ /**
192
+ * Removes a data source, the app's or one that layers brought.
193
+ *
194
+ * @param id - Data source ID.
195
+ * @param removeLayers - Also remove the layers that display or bring the source.
196
+ * @throws {@link FlowCoreError} if there's no source with the ID, or, unless `removeLayers`, a layer displays or
197
+ * brings it.
198
+ */
164
199
  removeSource(id, removeLayers = false) {
165
- if (!this._sources[id]) {
200
+ if (!this._sources[id] && !this._ownedSources[id]) {
166
201
  throw new FlowCoreError(`${this.formattedName}: no source with id '${id}'`);
167
202
  }
168
- const linkedLayers = Object.values(this._layers).filter((layer) => layer.sourceIds.includes(id)).map((layer) => layer.id);
203
+ const linkedLayers = Object.values(this._layers).filter((layer) => layer.sourceIds.includes(id) || layer.ownedSources?.some((source) => source.id === id)).map((layer) => layer.id);
169
204
  if (removeLayers) {
170
205
  linkedLayers.forEach((id2) => this.removeLayer(id2));
171
206
  } else if (linkedLayers.length) {
@@ -176,19 +211,32 @@ const _MapStyle = class _MapStyle {
176
211
  delete this._sources[id];
177
212
  return this;
178
213
  }
214
+ /**
215
+ * Whether the source with the ID is one that layers brought (see {@link MapLayer.setOwnedSources}), rather than
216
+ * one the app added.
217
+ *
218
+ * @internal
219
+ */
220
+ isOwnedSource(id) {
221
+ return !!this._ownedSources[id];
222
+ }
179
223
  getSource(id) {
180
- const source = this._sources[id];
224
+ const source = this._sources[id] ?? this._ownedSources[id];
181
225
  if (!source) {
182
226
  throw new FlowCoreError(`${this.formattedName}: no source with id '${id}'`);
183
227
  }
184
228
  return source;
185
229
  }
186
230
  getSources(filter) {
187
- return Object.values(this._sources).filter((source) => filter ? filter(source) : true);
231
+ return [...Object.values(this._sources), ...Object.values(this._ownedSources)].filter(
232
+ (source) => filter ? filter(source) : true
233
+ );
188
234
  }
189
235
  addLayer(layer) {
190
- layer.sourceIds.forEach((sourceId) => {
191
- if (!this._sources[sourceId] && !this._baseStyle.sources[sourceId]) {
236
+ const brought = new Set(layer.ownedSources?.map((source) => source.id));
237
+ const sourceIds = layer.type === "composite" ? [] : layer.sourceIds;
238
+ sourceIds.forEach((sourceId) => {
239
+ if (!this._sources[sourceId] && !this._ownedSources[sourceId] && !this._baseStyle.sources[sourceId] && !brought.has(sourceId)) {
192
240
  throw new FlowCoreError(`${this.formattedName}: no source with id '${sourceId}'`);
193
241
  }
194
242
  });
@@ -207,15 +255,25 @@ const _MapStyle = class _MapStyle {
207
255
  this._layers[layer.id] = layer;
208
256
  this._layerOrder.push(layer.id);
209
257
  layer.bindState(this._state);
258
+ layer.setMapSources((id) => !!(this._sources[id] || this._ownedSources[id] || this._baseStyle.sources[id]));
259
+ this._ownedSourceDisposers.set(
260
+ layer.id,
261
+ layer.observeOwnedSources(() => this.syncOwnedSources())
262
+ );
263
+ this.syncOwnedSources();
210
264
  return this;
211
265
  }
212
266
  removeLayer(id) {
213
267
  if (!this._layers[id]) {
214
268
  throw new FlowCoreError(`${this.formattedName}: no layer with id '${id}'`);
215
269
  }
270
+ this._layers[id].setMapSources(null);
216
271
  delete this._layers[id];
217
272
  const index = this._layerOrder.indexOf(id);
218
273
  this._layerOrder.splice(index, 1);
274
+ this._ownedSourceDisposers.get(id)?.();
275
+ this._ownedSourceDisposers.delete(id);
276
+ this.syncOwnedSources();
219
277
  return this;
220
278
  }
221
279
  getLayer(id) {
@@ -228,6 +286,62 @@ const _MapStyle = class _MapStyle {
228
286
  getLayers(filter) {
229
287
  return this._layerOrder.map((layerId) => this._layers[layerId]).filter((layer) => filter ? filter(layer) : true);
230
288
  }
289
+ /**
290
+ * Adds and removes the sources that layers bring, so that each ID that a layer on the map brings, and that neither
291
+ * the app nor the base style has, is on the map once, with the options of the first layer added that brings it. A
292
+ * source whose options are unchanged keeps its instance, so MapLibre doesn't reload it.
293
+ */
294
+ syncOwnedSources() {
295
+ const wanted = /* @__PURE__ */ new Map();
296
+ this._layerOrder.forEach(
297
+ (layerId) => this._layers[layerId].ownedSources?.forEach((options) => {
298
+ if (!wanted.has(options.id) && !this._sources[options.id] && !this._baseStyle.sources[options.id]) {
299
+ wanted.set(options.id, options);
300
+ }
301
+ })
302
+ );
303
+ Object.keys(this._ownedSources).forEach((id) => {
304
+ const options = wanted.get(id);
305
+ if (!options || !comparer.structural(options, this._ownedSourceOptions.get(id))) {
306
+ this._hooks.event?.("beforeSourceRemoved", id);
307
+ delete this._ownedSources[id];
308
+ this._ownedSourceOptions.delete(id);
309
+ this._hooks.event?.("sourceRemoved", id);
310
+ }
311
+ });
312
+ wanted.forEach((options, id) => {
313
+ if (!this._ownedSources[id]) {
314
+ this._hooks.event?.("beforeSourceAdded", id);
315
+ const source = new MapDataSource(options);
316
+ this._hooks.prepare?.(source);
317
+ source.bindState(this._state);
318
+ this._ownedSources[id] = source;
319
+ this._ownedSourceOptions.set(id, options);
320
+ this._hooks.event?.("sourceAdded", id);
321
+ }
322
+ });
323
+ }
324
+ /** A problem for each layer that brings a source with options other than those of the source on the map. */
325
+ ownedSourceConflicts() {
326
+ const problems = [];
327
+ const first = /* @__PURE__ */ new Map();
328
+ this._layerOrder.forEach(
329
+ (layerId) => this._layers[layerId].ownedSources?.forEach((options) => {
330
+ if (this._sources[options.id] || this._baseStyle.sources[options.id]) {
331
+ return;
332
+ }
333
+ const used = first.get(options.id);
334
+ if (!used) {
335
+ first.set(options.id, { layer: layerId, options });
336
+ } else if (!comparer.structural(used.options, options)) {
337
+ problems.push(
338
+ `${this.formattedName}: layer '${layerId}' brings data source '${options.id}' with options that differ from those of layer '${used.layer}', which are used`
339
+ );
340
+ }
341
+ })
342
+ );
343
+ return problems;
344
+ }
231
345
  duplicateIdProblem(layer, maplibreId, owner) {
232
346
  const usedBy = owner === "the base style" ? owner : `layer '${owner}'`;
233
347
  return `${this.formattedName}: layer '${layer.id}' leaves out MapLibre layer '${maplibreId}', whose id ${usedBy} already uses`;
@@ -1,3 +1,3 @@
1
- const version = "4.2.0";
1
+ const version = "4.3.0";
2
2
 
3
3
  export { version };