-
-
Notifications
You must be signed in to change notification settings - Fork 649
Expand file tree
/
Copy pathlayer-sync.ts
More file actions
3676 lines (3439 loc) · 133 KB
/
Copy pathlayer-sync.ts
File metadata and controls
3676 lines (3439 loc) · 133 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
controlRendersLayer,
DEFAULT_LAYER_STYLE,
type GeoLibreLayer,
type ExternalNativePaintBridge,
geojsonHasZCoordinates,
getExternalNativePaintBridge,
type LayerStyle,
pluginOwnsPaint,
proportionalRadiusExpression,
ruleBasedVisibilityFilter,
shouldUseTiledRendering,
styleValue,
validateMapExpression,
} from "@geolibre/core";
import { addProtocol, config } from "maplibre-gl";
import type { GeoJSON } from "geojson";
import type maplibregl from "maplibre-gl";
import type { PropertyValueSpecification } from "maplibre-gl";
import { FileSource, PMTiles, Protocol } from "pmtiles";
import {
ensureGeoJsonVtProtocol,
geojsonVtTileUrl,
hasGeoJsonVtSource,
registerGeoJsonVtSource,
TILE_MAX_ZOOM,
TILE_SOURCE_LAYER,
unregisterGeoJsonVtSource,
} from "./geojson-vt-protocol";
import {
circleLayerId,
clusterCountLayerId,
clusterLayerId,
detectGeometryProfile,
fillExtrusionLayerId,
fillLayerId,
generatorCircleLayerId,
generatorFillLayerId,
generatorLineLayerId,
generatorSourceId,
heatmapLayerId,
invertedFillLayerId,
invertedSourceId,
labelLayerId,
labelSourceId,
lineDecorationLayerId,
lineLayerId,
markerLayerId,
sourceId,
textLayerId,
} from "./geojson-loader";
import { buildDedupedLabelFeatures } from "./label-dedup";
import {
buildGeneratedGeometry,
buildInvertedMask,
generatedGeometryKinds,
} from "./derived-geometry";
import { ensureGeneratedImageHandler } from "./generated-images";
import { prepareFillPattern } from "./fill-patterns";
import { prepareLineDecoration } from "./line-decorations";
import {
KML_ICON_URL_PROPERTY,
markerImageValue,
markerIconSizeValue,
prepareKmlFeatureIcons,
} from "./markers";
import { isPlaceholderLayer } from "./placeholders";
import {
circlePaint,
clusterCirclePaint,
fillExtrusionPaint,
fillPaint,
heatmapPaint,
linePaint,
rasterPaint,
} from "./style-mapper";
/**
* Notified of the computed `beforeId` for a deck.gl-backed external custom layer
* (a `maplibre-gl-raster` COG) whenever layers are synced. Such a layer is not a
* real MapLibre style layer — `@deck.gl/mapbox` groups it by a `beforeId` prop —
* so `moveLayer` cannot reorder it; the host registers a handler that pushes the
* `beforeId` into the owning control instead. See issue #393 follow-up.
*/
let externalDeckLayerOrderHandler:
| ((layerId: string, beforeId: string | undefined) => void)
| null = null;
/** Register (or clear with `null`) the deck-layer order handler. */
export function setExternalDeckLayerOrderHandler(
handler: ((layerId: string, beforeId: string | undefined) => void) | null,
): void {
externalDeckLayerOrderHandler = handler;
}
const WMS_PROXY_PATH = "/__geolibre_wms_proxy";
const PMTILES_PROTOCOL = "pmtiles";
const PMTILES_PROTOCOL_GLOBAL_KEY = "__geolibrePMTilesProtocol";
const PMTILES_ARCHIVE_KEYS_GLOBAL_KEY = "__geolibrePMTilesArchiveKeys";
const MIN_LAYER_ZOOM = DEFAULT_LAYER_STYLE.minZoom;
const MAX_LAYER_ZOOM = DEFAULT_LAYER_STYLE.maxZoom;
const TEXT_MARKER_SHAPE = "text_marker";
const GEOMAN_SHAPE_PROPERTY = "__gm_shape";
const GEOMAN_TEXT_PROPERTY = "__gm_text";
const pointGeometryFilter: maplibregl.FilterSpecification = [
"match",
["geometry-type"],
["Point", "MultiPoint"],
true,
false,
];
const textMarkerShapeFilter: maplibregl.FilterSpecification = [
"any",
["==", ["get", GEOMAN_SHAPE_PROPERTY], TEXT_MARKER_SHAPE],
["==", ["get", "shape"], TEXT_MARKER_SHAPE],
];
const textMarkerFilter: maplibregl.FilterSpecification = [
"all",
pointGeometryFilter,
textMarkerShapeFilter,
];
const nonTextMarkerPointFilter: maplibregl.FilterSpecification = [
"all",
pointGeometryFilter,
["!", textMarkerShapeFilter],
];
/**
* Filter for the unclustered-point circle layer in cluster mode: every feature
* without a `point_count`, excluding text markers when present so they render
* only through the symbol layer rather than also as plain circles.
*/
function unclusteredPointFilter(hasTextMarkers: boolean): maplibregl.FilterSpecification {
if (!hasTextMarkers) return ["!", ["has", "point_count"]];
return [
"all",
["!", ["has", "point_count"]],
nonTextMarkerPointFilter,
] as maplibregl.FilterSpecification;
}
/**
* Combine a sub-layer's geometry filter with the layer's per-feature filters:
* the transient {@link GeoLibreLayer.timeFilter} (a Time-Slider-bound layer
* only renders features inside the current timeline window), the transient
* {@link GeoLibreLayer.embedFilter} (the embed API's `setFilter`, set by the
* host page that frames the app), and the rule-based visibility filter (a
* rule-based layer whose else rule is switched off hides features matching no
* rule — see {@link ruleBasedVisibilityFilter}). Returns the geometry filter
* unchanged when none applies, so the common path
* produces an identical spec and `ensureLayer` performs no filter update.
*
* Aggregate cluster layers (the bubble and its count) intentionally do not pass
* through here: a cluster feature carries no time or rule property, so an
* `["all", ...]` wrap would drop every cluster whenever a window or rule filter
* is active. Per-feature layers (fill, line, point, heatmap, text) filter
* correctly.
*
* Tile-backed layers (vector tiles, vector MBTiles) use this too. The filter is
* an expression evaluated per feature as each tile decodes, so it needs no local
* copy of the data and stays correct for tiles loaded later; control-owned
* PMTiles layers reach the same behavior through
* {@link applyExternalNativeFeatureFilters}.
*
* @param layer - The store layer being synced.
* @param geometryFilter - The sub-layer's own geometry-type filter.
* @returns The combined filter, or the original when no extra filter applies.
*/
function withFeatureFilters(
layer: GeoLibreLayer,
geometryFilter: maplibregl.FilterSpecification,
): maplibregl.FilterSpecification {
const filters: unknown[] = [];
const timeFilter = layer.timeFilter;
if (Array.isArray(timeFilter) && timeFilter.length > 0) {
filters.push(timeFilter);
}
if (Array.isArray(layer.embedFilter) && layer.embedFilter.length > 0) {
filters.push(layer.embedFilter);
}
const ruleFilter = ruleBasedVisibilityFilter(layer.style);
if (ruleFilter) filters.push(ruleFilter);
if (layer.metadata?.sourceKind === "annotation") {
filters.push(["!=", ["get", "visible"], false]);
}
if (filters.length === 0) return geometryFilter;
return ["all", geometryFilter, ...filters] as unknown as maplibregl.FilterSpecification;
}
// Tracked filter state for external-native vector layers whose per-feature
// filters (a Time Slider window and/or the rule-based hide-unmatched filter)
// GeoLibre applies. `base` is the control's own filter, captured the first time
// a filter is applied so it can be combined without nesting and fully restored
// when the last filter is removed; `appliedKey` is the JSON of the combined
// filter we last pushed, compared against the next combined filter (both built
// here, so they round-trip) to avoid calling `setFilter` on every sync tick.
// Keyed first by the map instance (a WeakMap, so entries are garbage-collected
// when a map is destroyed and a fresh map never inherits stale base filters)
// then by native MapLibre layer id.
interface NativeFilterState {
base: maplibregl.FilterSpecification | null;
appliedKey: string;
}
const externalNativeBaseFilters = new WeakMap<maplibregl.Map, Map<string, NativeFilterState>>();
function nativeFilterStatesFor(map: maplibregl.Map): Map<string, NativeFilterState> {
let perLayer = externalNativeBaseFilters.get(map);
if (!perLayer) {
perLayer = new Map();
externalNativeBaseFilters.set(map, perLayer);
}
return perLayer;
}
/**
* Whether a MapLibre layer type accepts a `filter`. Raster/hillshade/background
* layers do not, so a time window is never pushed onto them.
*/
function nativeLayerSupportsFilter(type: string): boolean {
return (
type === "circle" ||
type === "fill" ||
type === "line" ||
type === "symbol" ||
type === "fill-extrusion" ||
type === "heatmap"
);
}
/**
* The active per-feature filters GeoLibre applies on top of an external
* layer's own filters: the transient Time-Slider window, the embed API's
* host-set `setFilter` expression, and the rule-based hide-unmatched filter
* (see {@link ruleBasedVisibilityFilter}). Empty when none applies.
*/
function externalFeatureFilterExtras(layer: GeoLibreLayer): unknown[] {
const extras: unknown[] = [];
const timeFilter = layer.timeFilter;
if (Array.isArray(timeFilter) && timeFilter.length > 0) {
extras.push(timeFilter);
}
if (Array.isArray(layer.embedFilter) && layer.embedFilter.length > 0) {
extras.push(layer.embedFilter);
}
const ruleFilter = ruleBasedVisibilityFilter(layer.style);
if (ruleFilter) extras.push(ruleFilter);
return extras;
}
/**
* Combine a base filter (an external layer's own filter, possibly null) with
* the active per-feature extras into one MapLibre filter. Returns the base
* unchanged (null stays null) when no extras apply.
*/
function combineExternalFilters(
base: maplibregl.FilterSpecification | null,
extras: unknown[],
): maplibregl.FilterSpecification | null {
if (extras.length === 0) return base;
return (base
? ["all", base, ...extras]
: extras.length === 1
? extras[0]
: ["all", ...extras]) as unknown as maplibregl.FilterSpecification;
}
/**
* Apply (or clear) GeoLibre's per-feature filters — a Time-Slider window, the
* embed API's host-set `setFilter` expression, and the rule-based
* hide-unmatched filter (see {@link ruleBasedVisibilityFilter}, and
* {@link externalFeatureFilterExtras} for the set this reads)
* — on an external-native vector layer that a control owns and paints itself
* (e.g. the Add Vector Layer control). The control segregates geometry across
* its own native layers with a base filter such as
* `["==", ["geometry-type"], "Point"]`; this combines that base filter with the
* active per-feature filters via `["all", ...]` so they narrow the visible
* features without disturbing the control's paint. The control's base filter is
* captured once and restored when the last per-feature filter is removed.
*
* @param map - The MapLibre map.
* @param nativeLayerId - A control-owned native layer id.
* @param layer - The store layer (reads `timeFilter`, `embedFilter`, and the
* rule filter).
*/
function applyExternalNativeFeatureFilters(
map: maplibregl.Map,
nativeLayerId: string,
layer: GeoLibreLayer,
): void {
if (!map.getLayer(nativeLayerId)) return;
const states = nativeFilterStatesFor(map);
const extras = externalFeatureFilterExtras(layer);
if (extras.length === 0) {
// Nothing to narrow: restore the control's own filter (once) and stop
// tracking.
const state = states.get(nativeLayerId);
if (state) {
map.setFilter(nativeLayerId, state.base ?? undefined);
states.delete(nativeLayerId);
}
return;
}
// Filters active: capture the control's base filter the first time, then
// keep reusing it so repeated ticks combine rather than nest.
let state = states.get(nativeLayerId);
if (!state) {
const base = (map.getFilter(nativeLayerId) as maplibregl.FilterSpecification) ?? null;
state = { base, appliedKey: "" };
states.set(nativeLayerId, state);
}
const combined = combineExternalFilters(state.base, extras)!;
// Compare against the last filter we applied (not `getFilter`, which MapLibre
// may have normalized) so an unchanged filter does not re-push on every tick.
const combinedKey = JSON.stringify(combined);
if (state.appliedKey !== combinedKey) {
map.setFilter(nativeLayerId, combined);
state.appliedKey = combinedKey;
}
}
// Native layer ids whose zoom range GeoLibre has taken over. A pristine external
// layer keeps its source-declared range, but once the user sets a non-default
// range we keep applying the style range on every sync, including a later reset
// back to the full [0, 24] window.
const managedZoomRangeLayerIds = new Set<string>();
const geoJsonSourceData = new WeakMap<maplibregl.GeoJSONSource, GeoJSON>();
function rememberGeoJsonData(map: maplibregl.Map, sourceId: string, data: GeoJSON): void {
const source = map.getSource(sourceId);
if (source?.type === "geojson") geoJsonSourceData.set(source as maplibregl.GeoJSONSource, data);
}
function setGeoJsonData(source: maplibregl.GeoJSONSource, data: GeoJSON): void {
if (geoJsonSourceData.get(source) === data) return;
source.setData(data);
geoJsonSourceData.set(source, data);
}
function clampLayerZoom(value: number, fallback: number): number {
if (!Number.isFinite(value)) return fallback;
return Math.min(MAX_LAYER_ZOOM, Math.max(MIN_LAYER_ZOOM, value));
}
function styleLayerZoomRange(style: LayerStyle): {
maxzoom: number;
minzoom: number;
} {
const minzoom = clampLayerZoom(styleValue(style, "minZoom"), MIN_LAYER_ZOOM);
const maxzoom = clampLayerZoom(styleValue(style, "maxZoom"), MAX_LAYER_ZOOM);
return {
minzoom: Math.min(minzoom, maxzoom),
maxzoom: Math.max(minzoom, maxzoom),
};
}
// Intersect a native layer's source-declared zoom range with the user-configured
// style range, taking the tighter bound on each end. This keeps a tile
// service's zoom floor/ceiling intact while still letting the user narrow the
// window from the Style panel. When the two ranges do not overlap the bounds
// are swapped so MapLibre never receives an inverted (minzoom > maxzoom) range.
function intersectZoomRange(
nativeSpec: { minzoom?: number; maxzoom?: number },
style: LayerStyle,
): { minzoom: number; maxzoom: number } {
const styleRange = styleLayerZoomRange(style);
const minzoom = Math.max(nativeSpec.minzoom ?? MIN_LAYER_ZOOM, styleRange.minzoom);
const maxzoom = Math.min(nativeSpec.maxzoom ?? MAX_LAYER_ZOOM, styleRange.maxzoom);
return {
minzoom: Math.min(minzoom, maxzoom),
maxzoom: Math.max(minzoom, maxzoom),
};
}
export function syncLayer(map: maplibregl.Map, layer: GeoLibreLayer, beforeId?: string): void {
if (isExternalNativeLayer(layer)) {
syncExternalNativeLayer(map, layer, beforeId);
return;
}
if (isPlaceholderLayer(layer)) return;
if (layer.type === "geojson" && layer.geojson) {
// 3D Z-value rendering hands the layer to the shared deck.gl overlay
// (deckgl-viz plugin), which honors coordinate Z values that MapLibre's
// flat 2D layers ignore. Drop any MapLibre rendering so the layer is not
// drawn twice; toggling back off re-adds it through the paths below.
// Data without real Z coordinates keeps the normal 2D render even if the
// flag is set (e.g. a saved flag after a tool dropped the Z values), so
// the flag never leaves a layer invisible; the Z scan is cached per
// GeoJSON object.
if (
styleValue(layer.style, "elevation3dEnabled") === true &&
geojsonHasZCoordinates(layer.geojson)
) {
removeLayerFromMap(map, layer.id, layer);
return;
}
if (shouldUseTiledRendering(layer.geojson)) {
syncGeoJsonVtLayer(map, layer, beforeId);
} else {
syncGeoJsonLayer(map, layer, beforeId);
}
return;
}
if (
layer.type === "raster" ||
layer.type === "wms" ||
layer.type === "wmts" ||
layer.type === "xyz"
) {
syncRasterTileLayer(map, layer, beforeId);
return;
}
if (layer.type === "vector-tiles") {
syncVectorTileLayer(map, layer, beforeId);
return;
}
if (layer.type === "mbtiles") {
syncMbtilesLayer(map, layer, beforeId);
return;
}
if (layer.type === "video") {
syncVideoLayer(map, layer, beforeId);
return;
}
if (layer.type === "image") {
syncImageLayer(map, layer, beforeId);
return;
}
}
function isExternalNativeLayer(layer: GeoLibreLayer): boolean {
return getExternalNativeLayerIds(layer).length > 0;
}
function syncExternalNativeLayer(
map: maplibregl.Map,
layer: GeoLibreLayer,
beforeId?: string,
): void {
const nativeLayerIds = getExternalNativeLayerIds(layer);
if (isPMTilesExternalLayer(layer)) {
ensurePMTilesExternalLayer(map, layer, nativeLayerIds, beforeId);
}
// A plugin-painted layer (a MapLibre CustomLayerInterface) has no paint
// properties to set, so the panel's opacity/visibility only reach it through
// the setters the registration supplied. Forward them before the branches
// below, which cover the native visibility/zoom/order work the custom layer
// still honors.
applyExternalNativePaintBridge(layer);
// Custom render layers (e.g. 3D Tiles) manage their own visibility, opacity,
// and zoom behavior through the control that registered them, so the standard
// visibility/paint/zoom-range sync below must be skipped — only ordering is
// handled here.
if (isExternalCustomLayer(layer)) {
// Controls whose native fills are ordinary vector polygons (e.g. Overture
// Maps buildings) opt into GeoLibre-owned 3D extrusion. The Style panel
// offers the 3D mode to these layers, so without this the toggle would
// silently no-op on the ordering-only path below.
if (
supportsNativeFillExtrusion(layer) &&
syncExternalNativeExtrusion(map, layer, nativeLayerIds, beforeId)
) {
return;
}
clearExternalNativeExtrusion(map, layer, nativeLayerIds);
for (const nativeLayerId of nativeLayerIds) {
// A store layer can legitimately outlive its map layers: a layer whose
// restore failed keeps the `nativeLayerIds` it was saved with, and the
// owning control has not (yet) recreated them. Styling a layer that is
// not on the map raises "Cannot get style of non-existing layer" on the
// map's error channel, which fills the Diagnostics panel with noise the
// user can do nothing about, so skip those ids until the control brings
// them back.
const nativeLayer = map.getLayer(nativeLayerId);
if (!nativeLayer) continue;
moveLayer(map, nativeLayerId, beforeId);
// The owning control mirrors direct per-layer visibility changes from
// the store, but effective state such as a hidden parent group never
// mutates the child's stored `visible` flag. Apply the effective value
// to ordinary native MapLibre layers here so group visibility reaches
// control-rendered vectors too. MapLibre custom layers also accept the
// standard layout visibility property.
setNativeLayerVisibility(map, nativeLayerId, layer.visible ? "visible" : "none");
// Control-painted vector layers (e.g. Add Vector Layer's circle/fill/line
// layers) still honor a Time Slider window and the rule-based
// hide-unmatched filter: filtering is independent of the paint the
// control owns. Native layers without a filter (deck.gl / 3D Tiles
// custom layers) are skipped by the type guard.
if (nativeLayerSupportsFilter(nativeLayer.type)) {
applyExternalNativeFeatureFilters(map, nativeLayerId, layer);
}
}
syncVectorControlPointSymbology(map, layer, beforeId);
// A deck.gl raster has no real MapLibre style layer to move (it renders in a
// `deck-layer-group-*` keyed by its beforeId prop), so forward the computed
// beforeId to the control that owns it.
if (layer.metadata.externalDeckLayer === true) {
externalDeckLayerOrderHandler?.(layer.id, beforeId);
}
return;
}
if (isWaybackExternalRasterLayer(layer)) {
syncWaybackExternalRasterLayer(map, layer, nativeLayerIds, beforeId);
return;
}
if (isBasemapControlRasterLayer(layer)) {
syncBasemapControlRasterLayer(map, layer, nativeLayerIds, beforeId);
return;
}
if (isWebServiceTileRasterLayer(layer)) {
syncWebServiceTileRasterLayer(map, layer, nativeLayerIds, beforeId);
return;
}
// Generic external raster tiles registered by third-party plugins (e.g. a
// titiler-served XYZ source) carry no recognized sourceKind, so they match
// none of the handlers above. Honor the documented external-layer contract
// (a `source` with `tiles` and `type: "raster"`) by building the source and
// raster layer here instead of dropping through to the GeoJSON path below.
// IMPORTANT: this is a structural catch-all, so add any new named raster
// handler (new sourceKind) BEFORE this check — placing it after would let a
// layer that also has `source.tiles` be intercepted by the generic path.
if (isExternalRasterTileLayer(layer)) {
syncExternalRasterTileLayer(map, layer, nativeLayerIds, beforeId);
return;
}
ensureExternalGeoJsonNativeLayer(map, layer, nativeLayerIds, beforeId);
if (
!controlOwnsPaint(layer) &&
syncExternalNativeExtrusion(map, layer, nativeLayerIds, beforeId)
) {
return;
}
clearExternalNativeExtrusion(map, layer, nativeLayerIds);
for (const nativeLayerId of nativeLayerIds) {
const nativeLayer = map.getLayer(nativeLayerId);
if (!nativeLayer) continue;
setNativeLayerVisibility(map, nativeLayerId, layer.visible ? "visible" : "none");
// Narrow the control-painted features to the Time Slider window (if the
// layer is bound) and to the rule-based hide-unmatched filter (if the else
// rule is switched off). Filtering is independent of paint, so this
// applies even when the control owns the paint.
if (nativeLayerSupportsFilter(nativeLayer.type)) {
applyExternalNativeFeatureFilters(map, nativeLayerId, layer);
}
if (!controlOwnsPaint(layer)) {
setExternalNativeLayerPaint(map, nativeLayerId, nativeLayer.type, layer);
}
// External layers carry their own zoom range from the control or tile
// service that registered them, so we leave a pristine layer's native range
// alone. Once the user moves off the defaults GeoLibre owns the range and
// keeps applying it, so a later reset to the full [0, 24] window still takes
// effect rather than stranding the layer at the narrowed range.
const zoomRange = styleLayerZoomRange(layer.style);
const isDefaultRange =
zoomRange.minzoom === MIN_LAYER_ZOOM && zoomRange.maxzoom === MAX_LAYER_ZOOM;
if (!isDefaultRange) {
managedZoomRangeLayerIds.add(nativeLayerId);
}
if (managedZoomRangeLayerIds.has(nativeLayerId)) {
setLayerZoomRange(map, nativeLayerId, zoomRange);
}
moveLayer(map, nativeLayerId, beforeId);
}
}
function ensureExternalGeoJsonNativeLayer(
map: maplibregl.Map,
layer: GeoLibreLayer,
nativeLayerIds: string[],
beforeId?: string,
): void {
if (!layer.geojson) return;
if (nativeLayerIds.length === 0) {
console.warn(
`[layer-sync] external native GeoJSON layer "${layer.id}" has no nativeLayerIds; skipping native layer creation`,
);
return;
}
const nativeSourceId =
getExternalSourceIds(layer)[0] ??
stringSource(layer.source.sourceId) ??
sourceIdFromNativeLayerId(nativeLayerIds[0]) ??
sourceId(layer.id);
// Always refresh the source so re-registration with new geojson data takes
// effect, then short-circuit only the layer creation when the native layers
// already exist.
if (!map.getSource(nativeSourceId)) {
map.addSource(nativeSourceId, {
type: "geojson",
data: layer.geojson,
});
rememberGeoJsonData(map, nativeSourceId, layer.geojson);
} else {
setGeoJsonData(map.getSource(nativeSourceId) as maplibregl.GeoJSONSource, layer.geojson);
}
if (nativeLayerIds.every((id) => map.getLayer(id))) return;
const visibility = layer.visible ? "visible" : "none";
const zoomRange = styleLayerZoomRange(layer.style);
const geometryType = stringMetadata(layer.metadata.geometryType);
const symbolLayer = layer.metadata.symbolLayer === true;
const profile = detectGeometryProfile(layer.geojson);
const primaryLayerId = nativeLayerIds[0];
// Each registration is rendered with a single representative native layer
// (the first nativeLayerId), chosen by the dominant geometry below. A
// FeatureCollection mixing geometry types only renders the representative
// one; callers that need every type drawn should register one entry per
// geometry type (one nativeLayerId each).
if (symbolLayer) {
ensureLayer(
map,
primaryLayerId,
{
id: primaryLayerId,
type: "symbol",
source: nativeSourceId,
...zoomRange,
layout: {
"text-allow-overlap": true,
// Literal glyph rendered at every feature as a sprite-free point
// marker (an asterisk, not a property lookup). Symbol registrations
// here carry no label field, so this is intentional placeholder text.
"text-field": "*",
"text-ignore-placement": true,
"text-size": Math.max(8, styleValue(layer.style, "circleRadius") * 2.5),
visibility,
},
paint: {
"text-color": styleValue(layer.style, "fillColor"),
"text-halo-color": styleValue(layer.style, "strokeColor"),
"text-halo-width": styleValue(layer.style, "strokeWidth"),
"text-opacity": layer.opacity,
},
},
beforeId,
);
return;
}
if (geometryType === "point" || profile.hasPoint) {
ensureLayer(
map,
primaryLayerId,
{
id: primaryLayerId,
type: "circle",
source: nativeSourceId,
...zoomRange,
filter: ["match", ["geometry-type"], ["Point", "MultiPoint"], true, false],
paint: circlePaint(layer.style, layer.opacity),
layout: { visibility },
},
beforeId,
);
return;
}
if (geometryType === "line" || profile.hasLine || profile.hasPolygon) {
ensureLayer(
map,
primaryLayerId,
{
id: primaryLayerId,
type: "line",
source: nativeSourceId,
...zoomRange,
filter: [
"match",
["geometry-type"],
["LineString", "MultiLineString", "Polygon", "MultiPolygon"],
true,
false,
],
paint: linePaint(layer.style, layer.opacity),
layout: { visibility },
},
beforeId,
);
}
}
function sourceIdFromNativeLayerId(layerId: string | undefined): string | null {
return layerId ? `${layerId}-source` : null;
}
function isPMTilesExternalLayer(layer: GeoLibreLayer): boolean {
return (
layer.type === "pmtiles" &&
layer.metadata.sourceKind === "pmtiles-url" &&
layer.metadata.externalNativeLayer === true
);
}
// Delegates to core's `controlRendersLayer` so the flag this dispatch branches
// on has exactly one definition: the Layer Library's "can this be re-added and
// rendered?" gate reads the same predicate (issue #1520), and a change to what
// marks a custom-render layer cannot leave the two disagreeing.
function isExternalCustomLayer(layer: GeoLibreLayer): boolean {
return controlRendersLayer(layer);
}
// Opt-in for control-managed layers (`customLayerType`, the ordering-only path)
// whose native fill layers are plain vector polygons GeoLibre can re-render as
// fill-extrusions. Controls that implement extrusion themselves — Add Vector
// Layer and DuckDB push `extrusionEnabled` into their own control style — must
// leave this unset, or both would extrude the same features.
function supportsNativeFillExtrusion(layer: GeoLibreLayer): boolean {
return layer.metadata.nativeFillExtrusion === true;
}
// External controls that paint their native layers with data-driven MapLibre
// expressions (selection-based color, radius, opacity, ...) cannot express that
// paint through GeoLibre's flat per-layer style. They opt in with this flag so
// the sync below keeps managing visibility, zoom range, and ordering while
// leaving the control's own paint untouched. Unlike `customLayerType`, which
// drops the layer onto an ordering-only path, these layers still respond to the
// panel's show/hide and reorder controls.
function controlOwnsPaint(layer: GeoLibreLayer): boolean {
return layer.metadata.controlOwnsPaint === true || pluginOwnsPaint(layer);
}
// Last opacity/visibility handed to a layer's paint bridge, so a sync pass that
// changed nothing (a reorder, a basemap swap) does not call the plugin's setters
// again — each call typically triggers a WebGL repaint. Keyed by bridge identity
// as well as layer id: a re-registration (project reload, unregister →
// register) installs a new bridge whose renderer has never been told the current
// values, so it must get a fresh apply even when the store values did not move.
const appliedBridgeState = new Map<
string,
{ bridge: ExternalNativePaintBridge; opacity: number; visible: boolean }
>();
// Forward the panel's generic controls to a plugin-painted layer's own API. The
// setters are optional, so a plugin can bridge opacity only (the common case:
// visibility already works, MapLibre honors it on a custom layer).
function applyExternalNativePaintBridge(layer: GeoLibreLayer): void {
const bridge = getExternalNativePaintBridge(layer.id);
if (!bridge) {
appliedBridgeState.delete(layer.id);
return;
}
const applied = appliedBridgeState.get(layer.id);
const sameBridge = applied?.bridge === bridge;
if (!sameBridge || applied.opacity !== layer.opacity) {
bridge.setOpacity?.(layer.opacity);
}
if (!sameBridge || applied.visible !== layer.visible) {
bridge.setVisibility?.(layer.visible);
}
appliedBridgeState.set(layer.id, { bridge, opacity: layer.opacity, visible: layer.visible });
}
function ensurePMTilesExternalLayer(
map: maplibregl.Map,
layer: GeoLibreLayer,
nativeLayerIds: string[],
beforeId?: string,
): void {
const rawUrl = stringSource(layer.source.url) ?? layer.sourcePath;
const sourceId = getPMTilesSourceId(layer);
if (!rawUrl || !sourceId) return;
ensurePMTilesProtocol(rawUrl);
if (!map.getSource(sourceId)) {
const tileUrl = normalizePMTilesUrl(rawUrl);
if (getPMTilesTileType(layer) === "raster") {
map.addSource(sourceId, {
type: "raster",
url: tileUrl,
tileSize: 256,
});
} else {
map.addSource(sourceId, {
type: "vector",
url: tileUrl,
});
}
}
if (getPMTilesTileType(layer) === "raster") {
ensureLayer(
map,
nativeLayerIds[0] ?? `${sourceId}-raster`,
{
id: nativeLayerIds[0] ?? `${sourceId}-raster`,
type: "raster",
source: sourceId,
...styleLayerZoomRange(layer.style),
paint: rasterPaint(layer.style, layer.opacity),
layout: { visibility: layer.visible ? "visible" : "none" },
},
beforeId,
);
return;
}
const sourceLayers = getPMTilesRenderableSourceLayers(layer, sourceId, nativeLayerIds);
if (sourceLayers.length === 0) {
// Vector tile sources require a `source-layer` on every layer. With no
// known source layer there is nothing valid to render, so skip rather
// than add a layer MapLibre would reject at runtime.
return;
}
for (const sourceLayer of sourceLayers) {
const fillId = getPMTilesNativeLayerId(
nativeLayerIds,
pmtilesVectorLayerId(sourceId, sourceLayer, "fill"),
);
const lineId = getPMTilesNativeLayerId(
nativeLayerIds,
pmtilesVectorLayerId(sourceId, sourceLayer, "line"),
);
const circleId = getPMTilesNativeLayerId(
nativeLayerIds,
pmtilesVectorLayerId(sourceId, sourceLayer, "circle"),
);
ensureLayer(
map,
fillId,
{
id: fillId,
type: "fill",
source: sourceId,
"source-layer": sourceLayer,
...styleLayerZoomRange(layer.style),
filter: withFeatureFilters(layer, ["==", ["geometry-type"], "Polygon"]),
paint: fillPaint(layer.style, layer.opacity),
layout: { visibility: layer.visible ? "visible" : "none" },
},
beforeId,
);
ensureLayer(
map,
lineId,
{
id: lineId,
type: "line",
source: sourceId,
"source-layer": sourceLayer,
...styleLayerZoomRange(layer.style),
filter: withFeatureFilters(layer, [
"any",
["==", ["geometry-type"], "LineString"],
["==", ["geometry-type"], "Polygon"],
]),
paint: linePaint(layer.style, layer.opacity),
layout: { visibility: layer.visible ? "visible" : "none" },
},
beforeId,
);
ensureLayer(
map,
circleId,
{
id: circleId,
type: "circle",
source: sourceId,
"source-layer": sourceLayer,
...styleLayerZoomRange(layer.style),
filter: withFeatureFilters(layer, ["==", ["geometry-type"], "Point"]),
paint: circlePaint(layer.style, layer.opacity),
layout: { visibility: layer.visible ? "visible" : "none" },
},
beforeId,
);
}
}
function ensurePMTilesProtocol(url: string): void {
const protocol = getSharedPMTilesProtocol();
// Register the same instance we add archives to so MapLibre routes tile
// requests through it. isMapLibreProtocolRegistered() reflects MapLibre's
// live state, so this also re-registers after setStyle() clears protocols.
if (!isMapLibreProtocolRegistered()) {
addProtocol(PMTILES_PROTOCOL, protocol.tile);
}
// A key may already be backed by an in-memory archive from
// registerPMTilesArchive(); re-adding would silently replace it with a
// FetchSource for a URL that does not exist.
const key = stripPMTilesProtocol(url);
if (!protocol.tiles.has(key)) {
protocol.add(new PMTiles(key));
}
}
/**
* The MapLibre layer ids `syncLayers` creates for a `pmtiles` store layer, in
* the exact naming scheme `ensurePMTilesExternalLayer` uses. A layer built
* outside the PMTiles control (e.g. the offline basemap extract dialog) must
* put these in `metadata.nativeLayerIds` — a non-empty list is what marks the
* layer renderable rather than a placeholder.
*/
export function pmtilesNativeLayerIds(
sourceId: string,
tileType: "vector" | "raster",
sourceLayers: readonly string[],
): string[] {
if (tileType === "raster") {
return [`${sourceId}-raster`];
}
return sourceLayers.flatMap((sourceLayer) =>
["fill", "line", "circle"].map((kind) => pmtilesVectorLayerId(sourceId, sourceLayer, kind)),
);
}
/** Facts about a PMTiles archive needed to build a GeoLibre layer for it. */
export interface PMTilesArchiveInfo {
tileType: "vector" | "raster";
/** Vector-tile layer ids from the archive metadata (empty for raster). */
sourceLayers: string[];
/** `[minLon, minLat, maxLon, maxLat]` from the archive header. */
bounds: [number, number, number, number];
minZoom: number;
maxZoom: number;
}
/**
* Reads the header (and, for vector archives, the metadata's `vector_layers`)
* of an in-memory PMTiles archive, so callers can construct a properly-shaped
* `pmtiles` store layer for it.
*/
export async function readPMTilesArchiveInfo(bytes: Uint8Array): Promise<PMTilesArchiveInfo> {
const file = new File([bytes as BlobPart], "archive.pmtiles", {
type: "application/octet-stream",
});
const archive = new PMTiles(new FileSource(file));
const header = await archive.getHeader();
// PMTiles TileType: 1 = MVT (vector); everything else renders as raster.
const tileType = header.tileType === 1 ? "vector" : "raster";
let sourceLayers: string[] = [];
if (tileType === "vector") {
try {
const metadata = (await archive.getMetadata()) as {
vector_layers?: Array<{ id?: unknown }>;
};
sourceLayers = (metadata.vector_layers ?? [])
.map((layer) => layer.id)
.filter((id): id is string => typeof id === "string" && id.length > 0);
} catch {
// Metadata is optional; a vector archive without it still renders once
// the user knows its layer names.
}
}
return {
tileType,
sourceLayers,
bounds: [header.minLon, header.minLat, header.maxLon, header.maxLat],
minZoom: header.minZoom,
maxZoom: header.maxZoom,
};
}
/**
* Registers an in-memory PMTiles archive (e.g. an offline basemap extract)
* under a synthetic key so store layers can reference it like any remote
* archive. Returns the `pmtiles://<key>` URL to use as the layer's
* `source.url` / `sourcePath`.
*
* Re-registering the same key replaces the previous bytes. The archive is