maplibre-gl-layer-control 0.18.1 → 0.18.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,4876 +1,23 @@
1
- var __defProp = Object.defineProperty;
2
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
- class CustomLayerRegistry {
5
- constructor() {
6
- __publicField(this, "adapters", /* @__PURE__ */ new Map());
7
- __publicField(this, "changeListeners", []);
8
- __publicField(this, "unsubscribers", /* @__PURE__ */ new Map());
9
- }
10
- /**
11
- * Register a custom layer adapter.
12
- * @param adapter The adapter to register
13
- */
14
- register(adapter) {
15
- this.adapters.set(adapter.type, adapter);
16
- if (adapter.onLayerChange) {
17
- const unsubscribe = adapter.onLayerChange((event, layerId) => {
18
- this.notifyChange(event, layerId);
19
- });
20
- this.unsubscribers.set(adapter.type, unsubscribe);
21
- }
22
- }
23
- /**
24
- * Unregister an adapter by type.
25
- * @param type The adapter type to unregister
26
- */
27
- unregister(type) {
28
- const unsubscribe = this.unsubscribers.get(type);
29
- if (unsubscribe) {
30
- unsubscribe();
31
- this.unsubscribers.delete(type);
32
- }
33
- this.adapters.delete(type);
34
- }
35
- /**
36
- * Get all custom layer IDs across all adapters.
37
- * @returns Array of layer IDs
38
- */
39
- getAllLayerIds() {
40
- const ids = [];
41
- this.adapters.forEach((adapter) => {
42
- ids.push(...adapter.getLayerIds());
43
- });
44
- return ids;
45
- }
46
- /**
47
- * Get each adapter's layer IDs as a separate list, in adapter order.
48
- * @returns One array of layer IDs per registered adapter
49
- */
50
- getLayerIdGroups() {
51
- return Array.from(this.adapters.values(), (adapter) => adapter.getLayerIds());
52
- }
53
- /**
54
- * Check if a layer ID is managed by any adapter.
55
- * @param layerId The layer ID to check
56
- * @returns true if the layer is managed by an adapter
57
- */
58
- hasLayer(layerId) {
59
- for (const adapter of this.adapters.values()) {
60
- if (adapter.getLayerIds().includes(layerId)) {
61
- return true;
62
- }
63
- }
64
- return false;
65
- }
66
- /**
67
- * Get the adapter responsible for a specific layer.
68
- * @param layerId The layer ID
69
- * @returns The adapter or null if not found
70
- */
71
- getAdapterForLayer(layerId) {
72
- for (const adapter of this.adapters.values()) {
73
- if (adapter.getLayerIds().includes(layerId)) {
74
- return adapter;
75
- }
76
- }
77
- return null;
78
- }
79
- /**
80
- * Get the state of a custom layer.
81
- * @param layerId The layer ID
82
- * @returns The layer state or null if not found
83
- */
84
- getLayerState(layerId) {
85
- const adapter = this.getAdapterForLayer(layerId);
86
- return adapter ? adapter.getLayerState(layerId) : null;
87
- }
88
- /**
89
- * Set visibility of a custom layer.
90
- * @param layerId The layer ID
91
- * @param visible Whether the layer should be visible
92
- * @returns true if the operation was handled by an adapter
93
- */
94
- setVisibility(layerId, visible) {
95
- const adapter = this.getAdapterForLayer(layerId);
96
- if (adapter) {
97
- adapter.setVisibility(layerId, visible);
98
- return true;
99
- }
100
- return false;
101
- }
102
- /**
103
- * Set opacity of a custom layer.
104
- * @param layerId The layer ID
105
- * @param opacity The opacity value (0-1)
106
- * @returns true if the operation was handled by an adapter
107
- */
108
- setOpacity(layerId, opacity) {
109
- const adapter = this.getAdapterForLayer(layerId);
110
- if (adapter) {
111
- adapter.setOpacity(layerId, opacity);
112
- return true;
113
- }
114
- return false;
115
- }
116
- /**
117
- * Get the symbol type for a custom layer (for UI display).
118
- * @param layerId The layer ID
119
- * @returns The symbol type or null if not available
120
- */
121
- getSymbolType(layerId) {
122
- const adapter = this.getAdapterForLayer(layerId);
123
- if (adapter && adapter.getSymbolType) {
124
- return adapter.getSymbolType(layerId);
125
- }
126
- return null;
127
- }
128
- /**
129
- * Get the bounds of a custom layer (for zoom-to-layer).
130
- * @param layerId The layer ID
131
- * @returns The bounds [west, south, east, north] or null if not available
132
- */
133
- getBounds(layerId) {
134
- const adapter = this.getAdapterForLayer(layerId);
135
- if (adapter && adapter.getBounds) {
136
- return adapter.getBounds(layerId);
137
- }
138
- return null;
139
- }
140
- /**
141
- * Get native MapLibre layer IDs for a custom layer.
142
- * @param layerId The custom layer ID
143
- * @returns Array of native layer IDs, or null if not available
144
- */
145
- getNativeLayerIds(layerId) {
146
- const adapter = this.getAdapterForLayer(layerId);
147
- if (adapter && adapter.getNativeLayerIds) {
148
- return adapter.getNativeLayerIds(layerId);
149
- }
150
- return null;
151
- }
152
- /**
153
- * Remove a custom layer through its adapter.
154
- * @param layerId The layer ID to remove
155
- * @returns true if the operation was handled by an adapter
156
- */
157
- removeLayer(layerId) {
158
- const adapter = this.getAdapterForLayer(layerId);
159
- if (adapter && adapter.removeLayer) {
160
- adapter.removeLayer(layerId);
161
- return true;
162
- }
163
- return false;
164
- }
165
- /**
166
- * Get the layer groups of every adapter. When two adapters define the same
167
- * group ID, the first registered adapter's group wins.
168
- * @returns The groups, in adapter order
169
- */
170
- getGroups() {
171
- const groups = [];
172
- const seen = /* @__PURE__ */ new Set();
173
- this.adapters.forEach((adapter) => {
174
- var _a;
175
- for (const group of ((_a = adapter.getGroups) == null ? void 0 : _a.call(adapter)) ?? []) {
176
- if (seen.has(group.id)) continue;
177
- seen.add(group.id);
178
- groups.push(group);
179
- }
180
- });
181
- return groups;
182
- }
183
- /**
184
- * Get the ID of the group a custom layer belongs to.
185
- * @param layerId The layer ID
186
- * @returns The group ID, or undefined when the layer is ungrouped
187
- */
188
- getLayerGroupId(layerId) {
189
- var _a;
190
- const adapter = this.getAdapterForLayer(layerId);
191
- return (_a = adapter == null ? void 0 : adapter.getLayerGroupId) == null ? void 0 : _a.call(adapter, layerId);
192
- }
193
- /**
194
- * Get the adapter that defines a group.
195
- * @param groupId The group ID
196
- * @returns The adapter or null if no adapter defines the group
197
- */
198
- getAdapterForGroup(groupId) {
199
- var _a;
200
- for (const adapter of this.adapters.values()) {
201
- if ((_a = adapter.getGroups) == null ? void 0 : _a.call(adapter).some((group) => group.id === groupId)) {
202
- return adapter;
203
- }
204
- }
205
- return null;
206
- }
207
- /**
208
- * Set visibility of a group.
209
- * @param groupId The group ID
210
- * @param visible Whether the group should be visible
211
- * @returns true if the operation was handled by an adapter
212
- */
213
- setGroupVisibility(groupId, visible) {
214
- const adapter = this.getAdapterForGroup(groupId);
215
- if (adapter == null ? void 0 : adapter.setGroupVisibility) {
216
- adapter.setGroupVisibility(groupId, visible);
217
- return true;
218
- }
219
- return false;
220
- }
221
- /**
222
- * Set opacity of a group.
223
- * @param groupId The group ID
224
- * @param opacity The opacity value (0-1)
225
- * @returns true if the operation was handled by an adapter
226
- */
227
- setGroupOpacity(groupId, opacity) {
228
- const adapter = this.getAdapterForGroup(groupId);
229
- if (adapter == null ? void 0 : adapter.setGroupOpacity) {
230
- adapter.setGroupOpacity(groupId, opacity);
231
- return true;
232
- }
233
- return false;
234
- }
235
- /**
236
- * Record that a group was collapsed or expanded.
237
- * @param groupId The group ID
238
- * @param collapsed Whether the group is now collapsed
239
- * @returns true if the operation was handled by an adapter
240
- */
241
- setGroupCollapsed(groupId, collapsed) {
242
- const adapter = this.getAdapterForGroup(groupId);
243
- if (adapter == null ? void 0 : adapter.setGroupCollapsed) {
244
- adapter.setGroupCollapsed(groupId, collapsed);
245
- return true;
246
- }
247
- return false;
248
- }
249
- /**
250
- * Subscribe to layer changes across all adapters.
251
- * @param callback Function called when layers are added or removed
252
- * @returns Unsubscribe function
253
- */
254
- onChange(callback) {
255
- this.changeListeners.push(callback);
256
- return () => {
257
- const idx = this.changeListeners.indexOf(callback);
258
- if (idx >= 0) {
259
- this.changeListeners.splice(idx, 1);
260
- }
261
- };
262
- }
263
- notifyChange(event, layerId) {
264
- this.changeListeners.forEach((cb) => cb(event, layerId));
265
- }
266
- /**
267
- * Clean up all subscriptions and adapters.
268
- */
269
- destroy() {
270
- this.unsubscribers.forEach((unsub) => unsub());
271
- this.unsubscribers.clear();
272
- this.adapters.clear();
273
- this.changeListeners = [];
274
- }
275
- }
276
- function getOpacityProperty(layerType) {
277
- switch (layerType) {
278
- case "fill":
279
- return "fill-opacity";
280
- case "line":
281
- return "line-opacity";
282
- case "circle":
283
- return "circle-opacity";
284
- case "symbol":
285
- return ["icon-opacity", "text-opacity"];
286
- case "raster":
287
- return "raster-opacity";
288
- case "background":
289
- return "background-opacity";
290
- case "heatmap":
291
- return "heatmap-opacity";
292
- case "fill-extrusion":
293
- return "fill-extrusion-opacity";
294
- case "hillshade":
295
- return "hillshade-exaggeration";
296
- case "color-relief":
297
- return null;
298
- default:
299
- return `${layerType}-opacity`;
300
- }
301
- }
302
- function getLayerOpacity(map, layerId, layerType) {
303
- const opacityProp = getOpacityProperty(layerType);
304
- if (opacityProp === null) {
305
- return 1;
306
- }
307
- if (Array.isArray(opacityProp)) {
308
- const opacity2 = map.getPaintProperty(layerId, opacityProp[0]);
309
- return opacity2 !== void 0 && opacity2 !== null ? opacity2 : 1;
310
- }
311
- const opacity = map.getPaintProperty(layerId, opacityProp);
312
- return opacity !== void 0 && opacity !== null ? opacity : 1;
313
- }
314
- function setLayerOpacity(map, layerId, layerType, opacity) {
315
- const opacityProp = getOpacityProperty(layerType);
316
- if (opacityProp === null) {
317
- return;
318
- }
319
- if (Array.isArray(opacityProp)) {
320
- opacityProp.forEach((prop) => {
321
- map.setPaintProperty(layerId, prop, opacity);
322
- });
323
- } else {
324
- map.setPaintProperty(layerId, opacityProp, opacity);
325
- }
326
- }
327
- function isStyleableLayerType(layerType) {
328
- return [
329
- "fill",
330
- "line",
331
- "circle",
332
- "symbol",
333
- "raster",
334
- "heatmap",
335
- "fill-extrusion",
336
- "hillshade"
337
- ].includes(layerType);
338
- }
339
- function getLayerType(map, layerId) {
340
- try {
341
- const layer = map.getLayer(layerId);
342
- return layer ? layer.type : null;
343
- } catch (error) {
344
- console.warn(`Failed to get layer type for ${layerId}:`, error);
345
- return null;
346
- }
347
- }
348
- function clonePaintValue(value) {
349
- if (Array.isArray(value)) {
350
- return value.map((item) => clonePaintValue(item));
351
- }
352
- if (value && typeof value === "object") {
353
- try {
354
- return JSON.parse(JSON.stringify(value));
355
- } catch (error) {
356
- return value;
357
- }
358
- }
359
- return value;
360
- }
361
- function cacheOriginalLayerStyle(map, layerId, originalStyles) {
362
- var _a;
363
- if (originalStyles.has(layerId)) {
364
- return;
365
- }
366
- try {
367
- const layer = map.getLayer(layerId);
368
- if (!layer) {
369
- return;
370
- }
371
- const paint = {};
372
- const style = map.getStyle();
373
- const layerDef = (_a = style.layers) == null ? void 0 : _a.find((l) => l.id === layerId);
374
- if (layer.type === "raster") {
375
- const rasterDefaults = {
376
- "raster-opacity": 1,
377
- "raster-brightness-min": 0,
378
- "raster-brightness-max": 1,
379
- "raster-saturation": 0,
380
- "raster-contrast": 0,
381
- "raster-hue-rotate": 0
382
- };
383
- Object.assign(paint, rasterDefaults);
384
- if (layerDef && "paint" in layerDef && layerDef.paint) {
385
- Object.entries(layerDef.paint).forEach(([prop, value]) => {
386
- if (prop.startsWith("raster-")) {
387
- paint[prop] = clonePaintValue(value);
388
- }
389
- });
390
- }
391
- } else {
392
- if (layerDef && "paint" in layerDef && layerDef.paint) {
393
- Object.entries(layerDef.paint).forEach(([prop, value]) => {
394
- paint[prop] = clonePaintValue(value);
395
- });
396
- }
397
- }
398
- originalStyles.set(layerId, { paint });
399
- } catch (error) {
400
- console.warn(`Failed to cache original style for ${layerId}:`, error);
401
- }
402
- }
403
- function restoreOriginalStyle(map, layerId, originalStyles) {
404
- const original = originalStyles.get(layerId);
405
- if (!original) {
406
- return {};
407
- }
408
- const applied = {};
409
- Object.entries(original.paint).forEach(([property, value]) => {
410
- try {
411
- const restoredValue = clonePaintValue(value);
412
- map.setPaintProperty(layerId, property, restoredValue);
413
- applied[property] = restoredValue;
414
- } catch (error) {
415
- console.warn(`Failed to restore ${property} for ${layerId}:`, error);
416
- }
417
- });
418
- return applied;
419
- }
420
- function rgbToHex(r, g, b) {
421
- const clamp2 = (v) => Math.max(0, Math.min(255, Math.round(v)));
422
- const toHex = (v) => {
423
- const hex = clamp2(v).toString(16);
424
- return hex.length === 1 ? `0${hex}` : hex;
425
- };
426
- return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
427
- }
428
- function normalizeColor(value) {
429
- if (typeof value === "string") {
430
- if (value.startsWith("#")) {
431
- if (value.length === 4) {
432
- const r = value[1];
433
- const g = value[2];
434
- const b = value[3];
435
- return `#${r}${r}${g}${g}${b}${b}`;
436
- }
437
- return value;
438
- }
439
- if (value.startsWith("rgb")) {
440
- const match = value.match(/\d+/g);
441
- if (match && match.length >= 3) {
442
- const [r, g, b] = match.map((num) => parseInt(num, 10));
443
- return rgbToHex(r, g, b);
444
- }
445
- }
446
- } else if (Array.isArray(value) && value.length >= 3) {
447
- return rgbToHex(value[0], value[1], value[2]);
448
- }
449
- return "#3388ff";
450
- }
451
- function formatNumericValue(value, step) {
452
- let decimals = 0;
453
- if (step && Number(step) !== 1) {
454
- const stepNumber = Number(step);
455
- if (stepNumber > 0 && stepNumber < 1) {
456
- decimals = Math.min(4, Math.ceil(Math.abs(Math.log10(stepNumber))));
457
- }
458
- }
459
- return value.toFixed(decimals);
460
- }
461
- function clamp(value, min, max) {
462
- return Math.max(min, Math.min(max, value));
463
- }
464
- const COLOR_PROPERTY_MAP = {
465
- fill: ["fill-color", "fill-outline-color"],
466
- line: ["line-color"],
467
- circle: ["circle-color", "circle-stroke-color"],
468
- symbol: ["icon-color", "text-color"],
469
- background: ["background-color"],
470
- heatmap: ["heatmap-color"],
471
- "fill-extrusion": ["fill-extrusion-color"]
472
- };
473
- function extractColorFromExpression(expression) {
474
- if (!Array.isArray(expression) || expression.length === 0) return null;
475
- for (const item of expression) {
476
- if (typeof item === "string") {
477
- if (item.startsWith("#") || item.startsWith("rgb") || item.startsWith("hsl")) {
478
- return normalizeColor(item);
479
- }
480
- } else if (Array.isArray(item)) {
481
- const result = extractColorFromExpression(item);
482
- if (result) return result;
483
- }
484
- }
485
- return null;
486
- }
487
- function getLayerColor(map, layerId, layerType) {
488
- var _a;
489
- const propertyNames = COLOR_PROPERTY_MAP[layerType];
490
- if (!propertyNames) return null;
491
- for (const propertyName of propertyNames) {
492
- try {
493
- const runtimeColor = map.getPaintProperty(layerId, propertyName);
494
- if (runtimeColor) {
495
- if (typeof runtimeColor === "string") {
496
- return normalizeColor(runtimeColor);
497
- }
498
- if (Array.isArray(runtimeColor)) {
499
- const extracted = extractColorFromExpression(runtimeColor);
500
- if (extracted) return extracted;
501
- }
502
- }
503
- } catch {
504
- }
505
- const style = map.getStyle();
506
- const layer = (_a = style == null ? void 0 : style.layers) == null ? void 0 : _a.find(
507
- (l) => l.id === layerId
508
- );
509
- if (layer && "paint" in layer && layer.paint) {
510
- const paintColor = layer.paint[propertyName];
511
- if (paintColor) {
512
- if (typeof paintColor === "string") {
513
- return normalizeColor(paintColor);
514
- }
515
- if (Array.isArray(paintColor)) {
516
- const extracted = extractColorFromExpression(paintColor);
517
- if (extracted) return extracted;
518
- }
519
- }
520
- }
521
- }
522
- return null;
523
- }
524
- function getLayerColorFromSpec(layer) {
525
- const propertyNames = COLOR_PROPERTY_MAP[layer.type];
526
- if (!propertyNames) return null;
527
- for (const propertyName of propertyNames) {
528
- if ("paint" in layer && layer.paint) {
529
- const paintColor = layer.paint[propertyName];
530
- if (paintColor) {
531
- if (typeof paintColor === "string") {
532
- return normalizeColor(paintColor);
533
- }
534
- if (Array.isArray(paintColor)) {
535
- const extracted = extractColorFromExpression(paintColor);
536
- if (extracted) return extracted;
537
- }
538
- }
539
- }
540
- }
541
- return null;
542
- }
543
- function darkenColor(hexColor, amount) {
544
- let hex = hexColor.replace("#", "");
545
- if (hex.length === 3) {
546
- hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
547
- }
548
- const r = Math.max(
549
- 0,
550
- parseInt(hex.slice(0, 2), 16) - Math.round(255 * amount)
551
- );
552
- const g = Math.max(
553
- 0,
554
- parseInt(hex.slice(2, 4), 16) - Math.round(255 * amount)
555
- );
556
- const b = Math.max(
557
- 0,
558
- parseInt(hex.slice(4, 6), 16) - Math.round(255 * amount)
559
- );
560
- return rgbToHex(r, g, b);
561
- }
562
- function createFillSymbol(size, color) {
563
- const padding = 2;
564
- const borderColor = darkenColor(color, 0.3);
565
- return `<svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}" xmlns="http://www.w3.org/2000/svg">
566
- <rect x="${padding}" y="${padding}" width="${size - padding * 2}" height="${size - padding * 2}"
567
- fill="${color}" stroke="${borderColor}" stroke-width="1" rx="1"/>
568
- </svg>`;
569
- }
570
- function createLineSymbol(size, color, strokeWidth = 2) {
571
- const y = size / 2;
572
- const padding = 2;
573
- return `<svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}" xmlns="http://www.w3.org/2000/svg">
574
- <line x1="${padding}" y1="${y}" x2="${size - padding}" y2="${y}"
575
- stroke="${color}" stroke-width="${strokeWidth}" stroke-linecap="round"/>
576
- </svg>`;
577
- }
578
- function createCircleSymbol(size, color) {
579
- const cx = size / 2;
580
- const cy = size / 2;
581
- const r = size / 2 - 3;
582
- const borderColor = darkenColor(color, 0.3);
583
- return `<svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}" xmlns="http://www.w3.org/2000/svg">
584
- <circle cx="${cx}" cy="${cy}" r="${r}" fill="${color}"
585
- stroke="${borderColor}" stroke-width="1"/>
586
- </svg>`;
587
- }
588
- function createMarkerSymbol(size, color) {
589
- const borderColor = darkenColor(color, 0.3);
590
- const cx = size / 2;
591
- const pinWidth = size * 0.5;
592
- const pinHeight = size * 0.7;
593
- return `<svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}" xmlns="http://www.w3.org/2000/svg">
594
- <path d="M${cx} ${size - 2}
595
- L${cx - pinWidth / 2} ${size - pinHeight}
596
- A${pinWidth / 2} ${pinWidth / 2} 0 1 1 ${cx + pinWidth / 2} ${size - pinHeight}
597
- Z"
598
- fill="${color}" stroke="${borderColor}" stroke-width="1"/>
599
- <circle cx="${cx}" cy="${size - pinHeight - pinWidth / 4}" r="${pinWidth / 5}" fill="white"/>
600
- </svg>`;
601
- }
602
- function createRasterSymbol(size) {
603
- const padding = 2;
604
- const id = `rasterGrad_${Math.random().toString(36).slice(2, 9)}`;
605
- return `<svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}" xmlns="http://www.w3.org/2000/svg">
606
- <defs>
607
- <linearGradient id="${id}" x1="0%" y1="0%" x2="100%" y2="100%">
608
- <stop offset="0%" stop-color="#e0e0e0"/>
609
- <stop offset="50%" stop-color="#808080"/>
610
- <stop offset="100%" stop-color="#404040"/>
611
- </linearGradient>
612
- </defs>
613
- <rect x="${padding}" y="${padding}" width="${size - padding * 2}" height="${size - padding * 2}"
614
- fill="url(#${id})" rx="1"/>
615
- </svg>`;
616
- }
617
- function createBackgroundSymbol(size, color) {
618
- return `<svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}" xmlns="http://www.w3.org/2000/svg">
619
- <rect x="1" y="1" width="${size - 2}" height="${size - 2}" fill="${color}" rx="2"/>
620
- <rect x="3" y="3" width="${size - 6}" height="${size - 6}" fill="none"
621
- stroke="white" stroke-width="1" stroke-opacity="0.5" rx="1"/>
622
- </svg>`;
623
- }
624
- function createHeatmapSymbol(size) {
625
- const padding = 2;
626
- const id = `heatmapGrad_${Math.random().toString(36).slice(2, 9)}`;
627
- return `<svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}" xmlns="http://www.w3.org/2000/svg">
628
- <defs>
629
- <radialGradient id="${id}" cx="50%" cy="50%" r="50%">
630
- <stop offset="0%" stop-color="#ffff00"/>
631
- <stop offset="50%" stop-color="#ff8800"/>
632
- <stop offset="100%" stop-color="#ff0000"/>
633
- </radialGradient>
634
- </defs>
635
- <rect x="${padding}" y="${padding}" width="${size - padding * 2}" height="${size - padding * 2}"
636
- fill="url(#${id})" rx="1"/>
637
- </svg>`;
638
- }
639
- function createHillshadeSymbol(size) {
640
- const padding = 2;
641
- const id = `hillshadeGrad_${Math.random().toString(36).slice(2, 9)}`;
642
- return `<svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}" xmlns="http://www.w3.org/2000/svg">
643
- <defs>
644
- <linearGradient id="${id}" x1="0%" y1="0%" x2="100%" y2="100%">
645
- <stop offset="0%" stop-color="#ffffff"/>
646
- <stop offset="100%" stop-color="#666666"/>
647
- </linearGradient>
648
- </defs>
649
- <rect x="${padding}" y="${padding}" width="${size - padding * 2}" height="${size - padding * 2}"
650
- fill="url(#${id})" rx="1"/>
651
- </svg>`;
652
- }
653
- function createFillExtrusionSymbol(size, color) {
654
- const borderColor = darkenColor(color, 0.3);
655
- const topColor = color;
656
- const sideColor = darkenColor(color, 0.2);
657
- const depth = 3;
658
- return `<svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}" xmlns="http://www.w3.org/2000/svg">
659
- <polygon points="${2 + depth},2 ${size - 2},2 ${size - 2},${size - 2 - depth} ${size - 2 - depth},${size - 2} 2,${size - 2} 2,${2 + depth}"
660
- fill="${topColor}" stroke="${borderColor}" stroke-width="1"/>
661
- <polygon points="2,${2 + depth} ${2 + depth},2 ${2 + depth},${size - 2 - depth} 2,${size - 2}"
662
- fill="${sideColor}" stroke="${borderColor}" stroke-width="0.5"/>
663
- <polygon points="${2 + depth},${size - 2 - depth} ${size - 2},${size - 2 - depth} ${size - 2 - depth},${size - 2} 2,${size - 2}"
664
- fill="${sideColor}" stroke="${borderColor}" stroke-width="0.5"/>
665
- </svg>`;
666
- }
667
- function createDefaultSymbol(size, color) {
668
- const padding = 2;
669
- const borderColor = darkenColor(color, 0.3);
670
- return `<svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}" xmlns="http://www.w3.org/2000/svg">
671
- <rect x="${padding}" y="${padding}" width="${size - padding * 2}" height="${size - padding * 2}"
672
- fill="${color}" stroke="${borderColor}" stroke-width="1"/>
673
- </svg>`;
674
- }
675
- function createCOGSymbol(size, color) {
676
- const padding = 2;
677
- const borderColor = darkenColor(color, 0.3);
678
- const cellSize = (size - padding * 2) / 2;
679
- return `<svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}" xmlns="http://www.w3.org/2000/svg">
680
- <rect x="${padding}" y="${padding}" width="${cellSize}" height="${cellSize}" fill="${color}" stroke="${borderColor}" stroke-width="0.5"/>
681
- <rect x="${padding + cellSize}" y="${padding}" width="${cellSize}" height="${cellSize}" fill="${color}" stroke="${borderColor}" stroke-width="0.5" opacity="0.8"/>
682
- <rect x="${padding}" y="${padding + cellSize}" width="${cellSize}" height="${cellSize}" fill="${color}" stroke="${borderColor}" stroke-width="0.5" opacity="0.6"/>
683
- <rect x="${padding + cellSize}" y="${padding + cellSize}" width="${cellSize}" height="${cellSize}" fill="${color}" stroke="${borderColor}" stroke-width="0.5" opacity="0.4"/>
684
- </svg>`;
685
- }
686
- function createZarrSymbol(size, color) {
687
- const padding = 2;
688
- const borderColor = darkenColor(color, 0.3);
689
- const innerSize = size - padding * 2;
690
- return `<svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}" xmlns="http://www.w3.org/2000/svg">
691
- <rect x="${padding + 2}" y="${padding}" width="${innerSize - 2}" height="${innerSize - 2}" fill="${darkenColor(color, 0.2)}" stroke="${borderColor}" stroke-width="0.5" rx="1"/>
692
- <rect x="${padding + 1}" y="${padding + 1}" width="${innerSize - 2}" height="${innerSize - 2}" fill="${darkenColor(color, 0.1)}" stroke="${borderColor}" stroke-width="0.5" rx="1"/>
693
- <rect x="${padding}" y="${padding + 2}" width="${innerSize - 2}" height="${innerSize - 2}" fill="${color}" stroke="${borderColor}" stroke-width="0.5" rx="1"/>
694
- <line x1="${padding + 3}" y1="${padding + 5}" x2="${padding + innerSize - 5}" y2="${padding + 5}" stroke="${borderColor}" stroke-width="0.5" opacity="0.5"/>
695
- <line x1="${padding + 3}" y1="${padding + 8}" x2="${padding + innerSize - 5}" y2="${padding + 8}" stroke="${borderColor}" stroke-width="0.5" opacity="0.5"/>
696
- </svg>`;
697
- }
698
- function createCustomRasterSymbol(size, color) {
699
- const padding = 2;
700
- const borderColor = darkenColor(color, 0.3);
701
- const id = `customRasterGrad_${Math.random().toString(36).slice(2, 9)}`;
702
- return `<svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}" xmlns="http://www.w3.org/2000/svg">
703
- <defs>
704
- <linearGradient id="${id}" x1="0%" y1="0%" x2="100%" y2="100%">
705
- <stop offset="0%" stop-color="${color}"/>
706
- <stop offset="100%" stop-color="${darkenColor(color, 0.4)}"/>
707
- </linearGradient>
708
- </defs>
709
- <rect x="${padding}" y="${padding}" width="${size - padding * 2}" height="${size - padding * 2}"
710
- fill="url(#${id})" stroke="${borderColor}" stroke-width="1" rx="1"/>
711
- <line x1="${size / 2}" y1="${padding}" x2="${size / 2}" y2="${size - padding}" stroke="${borderColor}" stroke-width="0.5" opacity="0.3"/>
712
- <line x1="${padding}" y1="${size / 2}" x2="${size - padding}" y2="${size / 2}" stroke="${borderColor}" stroke-width="0.5" opacity="0.3"/>
713
- </svg>`;
714
- }
715
- function createStackedLayersSymbol(size) {
716
- const colors = ["#a8d4a8", "#8ec4e8", "#d4c4a8"];
717
- const borderColor = "#666666";
718
- return `<svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}" xmlns="http://www.w3.org/2000/svg">
719
- <rect x="4" y="1" width="${size - 6}" height="${size - 6}" fill="${colors[2]}" stroke="${borderColor}" stroke-width="0.75" rx="1"/>
720
- <rect x="2" y="3" width="${size - 6}" height="${size - 6}" fill="${colors[1]}" stroke="${borderColor}" stroke-width="0.75" rx="1"/>
721
- <rect x="0" y="5" width="${size - 6}" height="${size - 6}" fill="${colors[0]}" stroke="${borderColor}" stroke-width="0.75" rx="1"/>
722
- </svg>`;
723
- }
724
- function createLayerSymbolSVG(layerType, color, options = {}) {
725
- const size = options.size || 16;
726
- const strokeWidth = options.strokeWidth || 2;
727
- const fillColor = color || "#888888";
728
- switch (layerType) {
729
- case "fill":
730
- return createFillSymbol(size, fillColor);
731
- case "line":
732
- return createLineSymbol(size, fillColor, strokeWidth);
733
- case "circle":
734
- return createCircleSymbol(size, fillColor);
735
- case "symbol":
736
- return createMarkerSymbol(size, fillColor);
737
- case "raster":
738
- return createRasterSymbol(size);
739
- case "background":
740
- return createBackgroundSymbol(size, fillColor);
741
- case "heatmap":
742
- return createHeatmapSymbol(size);
743
- case "hillshade":
744
- return createHillshadeSymbol(size);
745
- case "fill-extrusion":
746
- return createFillExtrusionSymbol(size, fillColor);
747
- case "background-group":
748
- return createStackedLayersSymbol(size);
749
- case "cog":
750
- return createCOGSymbol(size, fillColor);
751
- case "zarr":
752
- return createZarrSymbol(size, fillColor);
753
- case "custom-raster":
754
- return createCustomRasterSymbol(size, fillColor);
755
- default:
756
- return createDefaultSymbol(size, fillColor);
757
- }
758
- }
759
- function createBackgroundGroupSymbolSVG(size = 16) {
760
- return createStackedLayersSymbol(size);
761
- }
762
- class LayerControl {
763
- constructor(options = {}) {
764
- __publicField(this, "map");
765
- __publicField(this, "mapContainer");
766
- __publicField(this, "container");
767
- __publicField(this, "button");
768
- __publicField(this, "panel");
769
- // Panel positioning
770
- __publicField(this, "resizeHandler", null);
771
- __publicField(this, "mapResizeHandler", null);
772
- // State management
773
- __publicField(this, "state");
774
- __publicField(this, "targetLayers");
775
- __publicField(this, "styleEditors");
776
- __publicField(this, "initialSourceIds", null);
777
- __publicField(this, "initialLayerIds", null);
778
- __publicField(this, "initialLayerStates");
779
- // Panel width management
780
- __publicField(this, "minPanelWidth");
781
- __publicField(this, "maxPanelWidth");
782
- __publicField(this, "initialPanelWidth");
783
- /** Explicit max panel height; null means fill available vertical space */
784
- __publicField(this, "maxPanelHeight");
785
- __publicField(this, "showStyleEditor");
786
- __publicField(this, "showOpacitySlider");
787
- __publicField(this, "showLayerSymbol");
788
- __publicField(this, "excludeDrawnLayers");
789
- __publicField(this, "excludeLayerPatterns");
790
- __publicField(this, "customLayerRegistry", null);
791
- __publicField(this, "customLayerUnsubscribe", null);
792
- __publicField(this, "removedCustomLayerIds", /* @__PURE__ */ new Set());
793
- __publicField(this, "nativeLayerGroups", /* @__PURE__ */ new Map());
794
- /** Layer groups from the custom layer adapters, as of the last panel build */
795
- __publicField(this, "groupStates", /* @__PURE__ */ new Map());
796
- /** Group IDs, parents, and memberships the panel was last built from */
797
- __publicField(this, "groupStructureKey", "");
798
- __publicField(this, "basemapStyleUrl", null);
799
- __publicField(this, "basemapLayerIds", null);
800
- __publicField(this, "widthFrame", null);
801
- // Exact-opacity input popup
802
- __publicField(this, "opacityInputEl", null);
803
- // Panel edge-drag resizing (handles on both the left and right edges)
804
- __publicField(this, "resizeHandleEls", []);
805
- /** Which edge is anchored to the control corner (the other edge is "free") */
806
- __publicField(this, "panelAnchorSide", "right");
807
- __publicField(this, "isPanelResizing", false);
808
- /** The physical edge being dragged in the current resize gesture */
809
- __publicField(this, "panelResizeEdge", "left");
810
- __publicField(this, "panelResizeStartX", null);
811
- __publicField(this, "panelResizeStartWidth", null);
812
- __publicField(this, "panelResizeStartOffset", 0);
813
- // Context menu and drag-drop
814
- __publicField(this, "contextMenuEl", null);
815
- __publicField(this, "enableContextMenu");
816
- __publicField(this, "enableDragAndDrop");
817
- __publicField(this, "onLayerRename");
818
- __publicField(this, "onLayerReorder");
819
- __publicField(this, "onLayerRemove");
820
- __publicField(this, "onLayerStyleChange");
821
- __publicField(this, "onBackgroundVisibilityChange");
822
- __publicField(this, "onBackgroundOpacityChange");
823
- // Background-layer visibility presets
824
- __publicField(this, "enableBackgroundPresets");
825
- __publicField(this, "backgroundPresetStorageKey");
826
- __publicField(this, "onBackgroundPresetsChange");
827
- this.minPanelWidth = options.panelMinWidth || 240;
828
- this.maxPanelWidth = options.panelMaxWidth || 960;
829
- this.initialPanelWidth = options.panelWidth || 350;
830
- this.maxPanelHeight = options.panelMaxHeight ?? null;
831
- this.showStyleEditor = options.showStyleEditor !== false;
832
- this.showOpacitySlider = options.showOpacitySlider !== false;
833
- this.showLayerSymbol = options.showLayerSymbol !== false;
834
- this.excludeDrawnLayers = options.excludeDrawnLayers !== false;
835
- this.excludeLayerPatterns = this.wildcardPatternsToRegex(
836
- options.excludeLayers || []
837
- );
838
- this.enableContextMenu = options.enableContextMenu !== false;
839
- this.enableDragAndDrop = options.enableDragAndDrop !== false;
840
- this.onLayerRename = options.onLayerRename;
841
- this.onLayerReorder = options.onLayerReorder;
842
- this.onLayerRemove = options.onLayerRemove;
843
- this.onLayerStyleChange = options.onLayerStyleChange;
844
- this.onBackgroundVisibilityChange = options.onBackgroundVisibilityChange;
845
- this.onBackgroundOpacityChange = options.onBackgroundOpacityChange;
846
- this.enableBackgroundPresets = options.enableBackgroundPresets !== false;
847
- this.backgroundPresetStorageKey = options.backgroundPresetStorageKey || "maplibre-layer-control:background-presets";
848
- this.onBackgroundPresetsChange = options.onBackgroundPresetsChange;
849
- this.initialLayerStates = options.layerStates || {};
850
- this.state = {
851
- collapsed: options.collapsed !== false,
852
- panelWidth: options.panelWidth || 350,
853
- activeStyleEditor: null,
854
- layerStates: {},
855
- originalStyles: /* @__PURE__ */ new Map(),
856
- userInteractingWithSlider: false,
857
- backgroundLegendOpen: false,
858
- backgroundLayerVisibility: /* @__PURE__ */ new Map(),
859
- onlyRenderedFilter: false,
860
- contextMenu: {
861
- visible: false,
862
- targetLayerId: null,
863
- x: 0,
864
- y: 0
865
- },
866
- renamingLayerId: null,
867
- customLayerNames: /* @__PURE__ */ new Map(),
868
- drag: {
869
- active: false,
870
- layerId: null,
871
- startY: 0,
872
- currentY: 0,
873
- placeholder: null,
874
- draggedElement: null
875
- },
876
- isStyleOperationInProgress: false
877
- };
878
- this.targetLayers = options.layers || Object.keys(this.initialLayerStates);
879
- this.styleEditors = /* @__PURE__ */ new Map();
880
- if (options.customLayerAdapters && options.customLayerAdapters.length > 0) {
881
- this.customLayerRegistry = new CustomLayerRegistry();
882
- options.customLayerAdapters.forEach((adapter) => {
883
- this.customLayerRegistry.register(adapter);
884
- });
885
- }
886
- this.basemapStyleUrl = options.basemapStyleUrl || null;
887
- }
888
- /**
889
- * Called when the control is added to the map
890
- */
891
- onAdd(map) {
892
- this.map = map;
893
- this.mapContainer = map.getContainer();
894
- const style = this.map.getStyle();
895
- if (style && style.sources) {
896
- this.initialSourceIds = new Set(Object.keys(style.sources));
897
- } else {
898
- this.initialSourceIds = /* @__PURE__ */ new Set();
899
- }
900
- if (style && style.layers) {
901
- this.initialLayerIds = new Set(style.layers.map((layer) => layer.id));
902
- } else {
903
- this.initialLayerIds = /* @__PURE__ */ new Set();
904
- }
905
- this.container = this.createContainer();
906
- this.button = this.createToggleButton();
907
- this.panel = this.createPanel();
908
- this.container.appendChild(this.button);
909
- this.mapContainer.appendChild(this.panel);
910
- if (this.enableContextMenu) {
911
- this.contextMenuEl = this.createContextMenu();
912
- this.mapContainer.appendChild(this.contextMenuEl);
913
- }
914
- this.setupEventListeners();
915
- if (this.basemapStyleUrl && !this.basemapLayerIds) {
916
- this.fetchBasemapStyle().then(() => {
917
- if (Object.keys(this.state.layerStates).length === 0) {
918
- this.autoDetectLayers();
919
- }
920
- this.buildLayerItems();
921
- }).catch((error) => {
922
- console.warn(
923
- "Failed to fetch basemap style, falling back to heuristic detection:",
924
- error
925
- );
926
- if (Object.keys(this.state.layerStates).length === 0) {
927
- this.autoDetectLayers();
928
- }
929
- this.buildLayerItems();
930
- });
931
- } else {
932
- if (Object.keys(this.state.layerStates).length === 0) {
933
- this.autoDetectLayers();
934
- }
935
- this.buildLayerItems();
936
- }
937
- if (!this.state.collapsed) {
938
- requestAnimationFrame(() => {
939
- this.updatePanelPosition();
940
- });
941
- }
942
- return this.container;
943
- }
944
- /**
945
- * Fetch the basemap style JSON and extract layer IDs.
946
- * This provides reliable distinction between basemap and user-added layers.
947
- */
948
- async fetchBasemapStyle() {
949
- if (!this.basemapStyleUrl) return;
950
- try {
951
- const response = await fetch(this.basemapStyleUrl);
952
- if (!response.ok) {
953
- throw new Error(`HTTP error! status: ${response.status}`);
954
- }
955
- const styleJson = await response.json();
956
- if (styleJson && Array.isArray(styleJson.layers)) {
957
- this.basemapLayerIds = new Set(
958
- styleJson.layers.map((layer) => layer.id)
959
- );
960
- } else {
961
- this.basemapLayerIds = /* @__PURE__ */ new Set();
962
- }
963
- } catch (error) {
964
- console.warn(
965
- "Failed to fetch basemap style from URL:",
966
- this.basemapStyleUrl,
967
- error
968
- );
969
- throw error;
970
- }
971
- }
972
- /**
973
- * Called when the control is removed from the map
974
- */
975
- onRemove() {
976
- var _a, _b, _c;
977
- if (this.customLayerUnsubscribe) {
978
- this.customLayerUnsubscribe();
979
- this.customLayerUnsubscribe = null;
980
- }
981
- if (this.customLayerRegistry) {
982
- this.customLayerRegistry.destroy();
983
- this.customLayerRegistry = null;
984
- }
985
- if (this.resizeHandler) {
986
- window.removeEventListener("resize", this.resizeHandler);
987
- this.resizeHandler = null;
988
- }
989
- if (this.mapResizeHandler) {
990
- this.map.off("resize", this.mapResizeHandler);
991
- this.mapResizeHandler = null;
992
- }
993
- if (this.contextMenuEl) {
994
- (_a = this.contextMenuEl.parentNode) == null ? void 0 : _a.removeChild(this.contextMenuEl);
995
- this.contextMenuEl = null;
996
- }
997
- this.hideOpacityInput();
998
- this.cleanupDragState();
999
- (_b = this.panel.parentNode) == null ? void 0 : _b.removeChild(this.panel);
1000
- (_c = this.container.parentNode) == null ? void 0 : _c.removeChild(this.container);
1001
- }
1002
- /**
1003
- * Auto-detect layers from the map and populate layerStates
1004
- */
1005
- autoDetectLayers() {
1006
- const style = this.map.getStyle();
1007
- if (!style || !style.layers) {
1008
- return;
1009
- }
1010
- const allLayerIds = style.layers.map((layer) => layer.id);
1011
- if (this.targetLayers.length === 0) {
1012
- const userAddedLayers = [];
1013
- const backgroundLayerIds = [];
1014
- const useBasemapStyleDetection = this.basemapLayerIds !== null && this.basemapLayerIds.size > 0;
1015
- const userAddedSourceIds = useBasemapStyleDetection ? /* @__PURE__ */ new Set() : this.detectUserAddedSources();
1016
- allLayerIds.forEach((layerId) => {
1017
- const layer = this.map.getLayer(layerId);
1018
- if (!layer) return;
1019
- if (this.excludeDrawnLayers && this.isDrawnLayer(layerId)) {
1020
- backgroundLayerIds.push(layerId);
1021
- return;
1022
- }
1023
- if (this.isExcludedByPattern(layerId)) {
1024
- backgroundLayerIds.push(layerId);
1025
- return;
1026
- }
1027
- if (useBasemapStyleDetection) {
1028
- if (this.basemapLayerIds.has(layerId)) {
1029
- backgroundLayerIds.push(layerId);
1030
- } else {
1031
- userAddedLayers.push(layerId);
1032
- }
1033
- } else {
1034
- const sourceId = layer.source;
1035
- if (sourceId && userAddedSourceIds.has(sourceId)) {
1036
- userAddedLayers.push(layerId);
1037
- } else {
1038
- backgroundLayerIds.push(layerId);
1039
- }
1040
- }
1041
- });
1042
- if (backgroundLayerIds.length > 0) {
1043
- this.state.layerStates["Background"] = {
1044
- visible: true,
1045
- opacity: 1,
1046
- name: "Background"
1047
- };
1048
- }
1049
- userAddedLayers.forEach((layerId) => {
1050
- const layer = this.map.getLayer(layerId);
1051
- if (!layer) return;
1052
- const visibility = this.map.getLayoutProperty(layerId, "visibility");
1053
- const isVisible = visibility !== "none";
1054
- const layerType = layer.type;
1055
- const opacity = getLayerOpacity(this.map, layerId, layerType);
1056
- const friendlyName = this.generateFriendlyName(layerId);
1057
- this.state.layerStates[layerId] = this.mergeWithUserState(layerId, {
1058
- visible: isVisible,
1059
- opacity,
1060
- name: friendlyName
1061
- });
1062
- });
1063
- } else {
1064
- const userLayers = [];
1065
- const basemapLayers = [];
1066
- allLayerIds.forEach((layerId) => {
1067
- if (this.isExcludedByPattern(layerId)) {
1068
- basemapLayers.push(layerId);
1069
- return;
1070
- }
1071
- if (this.targetLayers.includes(layerId)) {
1072
- userLayers.push(layerId);
1073
- } else {
1074
- basemapLayers.push(layerId);
1075
- }
1076
- });
1077
- if (basemapLayers.length > 0) {
1078
- this.state.layerStates["Background"] = {
1079
- visible: true,
1080
- opacity: 1,
1081
- name: "Background"
1082
- };
1083
- }
1084
- userLayers.forEach((layerId) => {
1085
- const layer = this.map.getLayer(layerId);
1086
- if (!layer) return;
1087
- const visibility = this.map.getLayoutProperty(layerId, "visibility");
1088
- const isVisible = visibility !== "none";
1089
- const layerType = layer.type;
1090
- const opacity = getLayerOpacity(this.map, layerId, layerType);
1091
- const friendlyName = this.generateFriendlyName(layerId);
1092
- this.state.layerStates[layerId] = this.mergeWithUserState(layerId, {
1093
- visible: isVisible,
1094
- opacity,
1095
- name: friendlyName
1096
- });
1097
- });
1098
- }
1099
- if (this.customLayerRegistry) {
1100
- const customLayerIds = this.customLayerRegistry.getAllLayerIds();
1101
- customLayerIds.forEach((layerId) => {
1102
- if (this.state.layerStates[layerId]) return;
1103
- const customState = this.customLayerRegistry.getLayerState(layerId);
1104
- if (customState) {
1105
- this.state.layerStates[layerId] = {
1106
- visible: customState.visible,
1107
- opacity: customState.opacity,
1108
- name: customState.name,
1109
- isCustomLayer: true,
1110
- customLayerType: this.customLayerRegistry.getSymbolType(layerId) || void 0
1111
- };
1112
- }
1113
- });
1114
- }
1115
- this.targetLayers = Object.keys(this.state.layerStates);
1116
- }
1117
- /**
1118
- * Detect which sources are user-added (not from the basemap style)
1119
- * User-added sources are identified by:
1120
- * - Sources that were NOT present when the control was first added
1121
- * - Additionally for sources added later:
1122
- * - GeoJSON sources with inline data objects (not URL strings)
1123
- * - Image, video, canvas sources
1124
- * - Raster, raster-dem, vector sources from non-basemap tile providers
1125
- */
1126
- detectUserAddedSources() {
1127
- const userAddedSources = /* @__PURE__ */ new Set();
1128
- const style = this.map.getStyle();
1129
- if (!style || !style.sources) return userAddedSources;
1130
- const basemapDomains = /* @__PURE__ */ new Set();
1131
- const knownBasemapProviders = [
1132
- "demotiles.maplibre.org",
1133
- "api.maptiler.com",
1134
- "tiles.stadiamaps.com",
1135
- "api.mapbox.com",
1136
- "basemaps.cartocdn.com",
1137
- "tiles.mapbox.com",
1138
- "a.basemaps.cartocdn.com",
1139
- "b.basemaps.cartocdn.com",
1140
- "c.basemaps.cartocdn.com",
1141
- "d.basemaps.cartocdn.com",
1142
- "tiles.arcgis.com",
1143
- "server.arcgisonline.com",
1144
- "services.arcgisonline.com"
1145
- ];
1146
- const spriteUrl = style.sprite;
1147
- if (spriteUrl && typeof spriteUrl === "string") {
1148
- try {
1149
- const url = new URL(spriteUrl);
1150
- basemapDomains.add(url.hostname);
1151
- } catch {
1152
- }
1153
- }
1154
- if (style.glyphs) {
1155
- try {
1156
- const url = new URL(
1157
- style.glyphs.replace("{fontstack}", "x").replace("{range}", "x")
1158
- );
1159
- basemapDomains.add(url.hostname);
1160
- } catch {
1161
- }
1162
- }
1163
- for (const [sourceId, source] of Object.entries(style.sources)) {
1164
- if (this.initialSourceIds && this.initialSourceIds.has(sourceId)) {
1165
- continue;
1166
- }
1167
- const src = source;
1168
- const sourceType = src.type;
1169
- if (sourceType === "image" || sourceType === "video" || sourceType === "canvas") {
1170
- userAddedSources.add(sourceId);
1171
- continue;
1172
- }
1173
- if (sourceType === "geojson") {
1174
- if (src.data && typeof src.data === "object") {
1175
- userAddedSources.add(sourceId);
1176
- } else if (src.data && typeof src.data === "string") {
1177
- try {
1178
- const url = new URL(src.data);
1179
- const isBasemap = knownBasemapProviders.some((p) => url.hostname.includes(p)) || basemapDomains.has(url.hostname);
1180
- if (!isBasemap) {
1181
- userAddedSources.add(sourceId);
1182
- }
1183
- } catch {
1184
- userAddedSources.add(sourceId);
1185
- }
1186
- }
1187
- continue;
1188
- }
1189
- if (sourceType === "raster" || sourceType === "raster-dem" || sourceType === "vector") {
1190
- const tileUrl = src.url || src.tiles && src.tiles[0] || "";
1191
- if (tileUrl) {
1192
- try {
1193
- const url = new URL(tileUrl.replace(/{[^}]+}/g, "0"));
1194
- const hostname = url.hostname;
1195
- const isKnownBasemap = knownBasemapProviders.some(
1196
- (provider) => hostname === provider || hostname.endsWith("." + provider)
1197
- );
1198
- const matchesBasemapDomain = basemapDomains.has(hostname);
1199
- if (!isKnownBasemap && !matchesBasemapDomain) {
1200
- userAddedSources.add(sourceId);
1201
- }
1202
- } catch {
1203
- userAddedSources.add(sourceId);
1204
- }
1205
- }
1206
- }
1207
- }
1208
- return userAddedSources;
1209
- }
1210
- /**
1211
- * Generate a friendly display name from a layer ID
1212
- */
1213
- generateFriendlyName(layerId) {
1214
- let name = layerId.replace(/^(layer[-_]?|gl[-_]?)/, "");
1215
- name = name.replace(/[-_]/g, " ");
1216
- name = name.replace(/\b\w/g, (char) => char.toUpperCase());
1217
- return name || layerId;
1218
- }
1219
- /**
1220
- * Merge auto-detected layer state with user-provided initial state.
1221
- * User-provided values take precedence over detected values.
1222
- */
1223
- mergeWithUserState(layerId, detected) {
1224
- const userState = this.initialLayerStates[layerId];
1225
- if (!userState) return detected;
1226
- return {
1227
- visible: userState.visible ?? detected.visible,
1228
- opacity: userState.opacity ?? detected.opacity,
1229
- name: userState.name ?? detected.name,
1230
- ...userState.isCustomLayer !== void 0 && {
1231
- isCustomLayer: userState.isCustomLayer
1232
- },
1233
- ...userState.customLayerType !== void 0 && {
1234
- customLayerType: userState.customLayerType
1235
- }
1236
- };
1237
- }
1238
- /**
1239
- * Check if a layer ID belongs to a drawing library (Geoman, Mapbox GL Draw, etc.)
1240
- * @param layerId The layer ID to check
1241
- * @returns true if the layer is from a drawing library
1242
- */
1243
- isDrawnLayer(layerId) {
1244
- const drawnLayerPatterns = [
1245
- // Drawing libraries
1246
- /^gm[-_\s]/i,
1247
- // Geoman (gm-main-*, gm_*, Gm Temporary...)
1248
- /^gl-draw[-_]/i,
1249
- // Mapbox GL Draw
1250
- /^mapbox-gl-draw[-_]/i,
1251
- // Mapbox GL Draw alternative
1252
- /^terra-draw[-_]/i,
1253
- // Terra Draw
1254
- /^maplibre-gl-draw[-_]/i,
1255
- // MapLibre GL Draw
1256
- /^draw[-_]layer/i,
1257
- // Generic draw layers
1258
- // maplibre-gl-components internal layers
1259
- /^measure-/i,
1260
- // MeasureControl (measure-{id}-fill, measure-{id}-line)
1261
- /^pmtiles-source-/i,
1262
- // PMTilesLayerControl (managed via adapter)
1263
- /^stac-search-footprints/i
1264
- // StacSearchControl footprint layers
1265
- ];
1266
- return drawnLayerPatterns.some((pattern) => pattern.test(layerId));
1267
- }
1268
- /**
1269
- * Convert wildcard patterns (e.g., '*-temp-*', 'debug-*') to RegExp objects
1270
- */
1271
- wildcardPatternsToRegex(patterns) {
1272
- return patterns.map((pattern) => {
1273
- const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
1274
- const regexStr = escaped.replace(/\*/g, ".*");
1275
- return new RegExp(`^${regexStr}$`, "i");
1276
- });
1277
- }
1278
- /**
1279
- * Check if a layer matches any of the user-defined exclusion patterns
1280
- */
1281
- isExcludedByPattern(layerId) {
1282
- return this.excludeLayerPatterns.some((pattern) => pattern.test(layerId));
1283
- }
1284
- /**
1285
- * Create the main container element
1286
- */
1287
- createContainer() {
1288
- const container = document.createElement("div");
1289
- container.className = "maplibregl-ctrl maplibregl-ctrl-group maplibregl-ctrl-layer-control";
1290
- return container;
1291
- }
1292
- /**
1293
- * Create the toggle button
1294
- */
1295
- createToggleButton() {
1296
- const button = document.createElement("button");
1297
- button.type = "button";
1298
- button.title = "Layer Control";
1299
- button.setAttribute("aria-label", "Layer Control");
1300
- const icon = document.createElement("span");
1301
- icon.className = "layer-control-icon";
1302
- icon.innerHTML = '<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="12 3 3 8.25 12 13.5 21 8.25 12 3"></polygon><polyline points="3 12.75 12 18 21 12.75"></polyline><polyline points="3 17.25 12 22 21 17.25"></polyline></svg>';
1303
- button.appendChild(icon);
1304
- return button;
1305
- }
1306
- /**
1307
- * Create the panel element
1308
- */
1309
- createPanel() {
1310
- const panel = document.createElement("div");
1311
- panel.className = "layer-control-panel";
1312
- panel.style.width = `${this.state.panelWidth}px`;
1313
- if (this.maxPanelHeight != null) {
1314
- panel.style.maxHeight = `${this.maxPanelHeight}px`;
1315
- }
1316
- if (!this.state.collapsed) {
1317
- panel.classList.add("expanded");
1318
- }
1319
- const header = this.createPanelHeader();
1320
- panel.appendChild(header);
1321
- const actionButtons = this.createActionButtons();
1322
- panel.appendChild(actionButtons);
1323
- panel.appendChild(this.createResizeHandle("left"));
1324
- panel.appendChild(this.createResizeHandle("right"));
1325
- return panel;
1326
- }
1327
- /**
1328
- * Create a draggable edge handle for resizing the panel width. A handle is
1329
- * added on each side so the panel can be resized by dragging either edge,
1330
- * like a conventional resizable window.
1331
- *
1332
- * @param side Which physical edge of the panel the handle sits on
1333
- */
1334
- createResizeHandle(side) {
1335
- const handle = document.createElement("div");
1336
- handle.className = `layer-control-resize-handle layer-control-resize-handle-${side}`;
1337
- handle.title = "Drag to resize panel";
1338
- handle.setAttribute("role", "separator");
1339
- handle.setAttribute("aria-orientation", "vertical");
1340
- this.resizeHandleEls.push(handle);
1341
- this.setupResizeHandleEvents(handle, side);
1342
- return handle;
1343
- }
1344
- /**
1345
- * Wire pointer events for an edge resize handle.
1346
- *
1347
- * @param handle The handle element
1348
- * @param side Which physical edge of the panel the handle sits on
1349
- */
1350
- setupResizeHandleEvents(handle, side) {
1351
- handle.addEventListener("pointerdown", (event) => {
1352
- event.preventDefault();
1353
- event.stopPropagation();
1354
- this.isPanelResizing = true;
1355
- this.panelResizeEdge = side;
1356
- this.panelResizeStartX = event.clientX;
1357
- this.panelResizeStartWidth = this.state.panelWidth;
1358
- this.panelResizeStartOffset = parseFloat(this.panel.style[this.panelAnchorSide]) || 0;
1359
- handle.setPointerCapture(event.pointerId);
1360
- this.panel.classList.add("resizing-active");
1361
- });
1362
- handle.addEventListener("pointermove", (event) => {
1363
- if (!this.isPanelResizing) return;
1364
- this.resizePanelFromPointer(event.clientX);
1365
- });
1366
- const endResize = (event) => {
1367
- if (!this.isPanelResizing) return;
1368
- if (event.pointerId !== void 0) {
1369
- try {
1370
- handle.releasePointerCapture(event.pointerId);
1371
- } catch {
1372
- }
1373
- }
1374
- this.isPanelResizing = false;
1375
- this.panelResizeStartX = null;
1376
- this.panelResizeStartWidth = null;
1377
- this.panel.classList.remove("resizing-active");
1378
- };
1379
- handle.addEventListener("pointerup", endResize);
1380
- handle.addEventListener("pointercancel", endResize);
1381
- handle.addEventListener("lostpointercapture", endResize);
1382
- handle.addEventListener("dblclick", (event) => {
1383
- event.preventDefault();
1384
- event.stopPropagation();
1385
- this.applyPanelWidth(this.initialPanelWidth, true);
1386
- });
1387
- }
1388
- /**
1389
- * Compute and apply a new panel width from the pointer position during an
1390
- * edge drag. Dragging the free edge changes the width while the anchored
1391
- * edge stays put; dragging the anchored edge shifts the anchor so the free
1392
- * edge stays put — both feel like resizing a normal window.
1393
- */
1394
- resizePanelFromPointer(clientX) {
1395
- const dx = clientX - (this.panelResizeStartX ?? clientX);
1396
- const startWidth = this.panelResizeStartWidth ?? this.state.panelWidth;
1397
- const desiredWidth = this.panelResizeEdge === "left" ? startWidth - dx : startWidth + dx;
1398
- const clamped = Math.round(
1399
- Math.min(this.maxPanelWidth, Math.max(this.minPanelWidth, desiredWidth))
1400
- );
1401
- if (this.panelResizeEdge === this.panelAnchorSide) {
1402
- let appliedDelta = clamped - startWidth;
1403
- let newOffset = this.panelResizeStartOffset - appliedDelta;
1404
- if (newOffset < 0) {
1405
- newOffset = 0;
1406
- appliedDelta = this.panelResizeStartOffset;
1407
- }
1408
- const finalWidth = Math.round(
1409
- Math.min(
1410
- this.maxPanelWidth,
1411
- Math.max(this.minPanelWidth, startWidth + appliedDelta)
1412
- )
1413
- );
1414
- this.applyPanelWidth(finalWidth, true);
1415
- this.panel.style[this.panelAnchorSide] = `${newOffset}px`;
1416
- } else {
1417
- this.applyPanelWidth(clamped, true);
1418
- }
1419
- }
1420
- /**
1421
- * Record which panel edge is anchored to the control corner, based on the
1422
- * corner the control occupies. Right corners anchor the right edge (panel
1423
- * grows leftward); left corners anchor the left edge (panel grows rightward).
1424
- */
1425
- updatePanelAnchorSide(position) {
1426
- this.panelAnchorSide = position === "top-right" || position === "bottom-right" ? "right" : "left";
1427
- }
1428
- /**
1429
- * Detect which corner the control is positioned in
1430
- * @returns The position: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'
1431
- */
1432
- getControlPosition() {
1433
- const parent = this.container.parentElement;
1434
- if (!parent) return "top-right";
1435
- if (parent.classList.contains("maplibregl-ctrl-top-left"))
1436
- return "top-left";
1437
- if (parent.classList.contains("maplibregl-ctrl-top-right"))
1438
- return "top-right";
1439
- if (parent.classList.contains("maplibregl-ctrl-bottom-left"))
1440
- return "bottom-left";
1441
- if (parent.classList.contains("maplibregl-ctrl-bottom-right"))
1442
- return "bottom-right";
1443
- return "top-right";
1444
- }
1445
- /**
1446
- * Update the panel position based on button location and control corner
1447
- * Positions the panel next to the button, expanding in the appropriate direction
1448
- */
1449
- updatePanelPosition() {
1450
- if (!this.button || !this.panel || !this.mapContainer) return;
1451
- const buttonRect = this.button.getBoundingClientRect();
1452
- const mapRect = this.mapContainer.getBoundingClientRect();
1453
- const position = this.getControlPosition();
1454
- this.updatePanelAnchorSide(position);
1455
- const buttonTop = buttonRect.top - mapRect.top;
1456
- const buttonBottom = mapRect.bottom - buttonRect.bottom;
1457
- const buttonLeft = buttonRect.left - mapRect.left;
1458
- const buttonRight = mapRect.right - buttonRect.right;
1459
- const panelGap = 5;
1460
- this.panel.style.top = "";
1461
- this.panel.style.bottom = "";
1462
- this.panel.style.left = "";
1463
- this.panel.style.right = "";
1464
- switch (position) {
1465
- case "top-left":
1466
- this.panel.style.top = `${buttonTop + buttonRect.height + panelGap}px`;
1467
- this.panel.style.left = `${buttonLeft}px`;
1468
- break;
1469
- case "top-right":
1470
- this.panel.style.top = `${buttonTop + buttonRect.height + panelGap}px`;
1471
- this.panel.style.right = `${buttonRight}px`;
1472
- break;
1473
- case "bottom-left":
1474
- this.panel.style.bottom = `${buttonBottom + buttonRect.height + panelGap}px`;
1475
- this.panel.style.left = `${buttonLeft}px`;
1476
- break;
1477
- case "bottom-right":
1478
- this.panel.style.bottom = `${buttonBottom + buttonRect.height + panelGap}px`;
1479
- this.panel.style.right = `${buttonRight}px`;
1480
- break;
1481
- }
1482
- const edgeMargin = 8;
1483
- const isTopAnchored = position === "top-left" || position === "top-right";
1484
- const occupiedFromEdge = isTopAnchored ? buttonTop + buttonRect.height + panelGap : buttonBottom + buttonRect.height + panelGap;
1485
- const availableHeight = Math.max(
1486
- 120,
1487
- Math.round(mapRect.height - occupiedFromEdge - edgeMargin)
1488
- );
1489
- const maxHeight = this.maxPanelHeight != null ? Math.min(this.maxPanelHeight, availableHeight) : availableHeight;
1490
- this.panel.style.maxHeight = `${maxHeight}px`;
1491
- }
1492
- /**
1493
- * Create action buttons for Show All / Hide All
1494
- */
1495
- createActionButtons() {
1496
- const container = document.createElement("div");
1497
- container.className = "layer-control-actions";
1498
- const showAllBtn = document.createElement("button");
1499
- showAllBtn.type = "button";
1500
- showAllBtn.className = "layer-control-action-btn";
1501
- showAllBtn.textContent = "Show All";
1502
- showAllBtn.title = "Show all layers";
1503
- showAllBtn.addEventListener(
1504
- "click",
1505
- () => this.setAllLayersVisibility(true)
1506
- );
1507
- const hideAllBtn = document.createElement("button");
1508
- hideAllBtn.type = "button";
1509
- hideAllBtn.className = "layer-control-action-btn";
1510
- hideAllBtn.textContent = "Hide All";
1511
- hideAllBtn.title = "Hide all layers";
1512
- hideAllBtn.addEventListener(
1513
- "click",
1514
- () => this.setAllLayersVisibility(false)
1515
- );
1516
- container.appendChild(showAllBtn);
1517
- container.appendChild(hideAllBtn);
1518
- return container;
1519
- }
1520
- /**
1521
- * Set visibility of all layers
1522
- */
1523
- setAllLayersVisibility(visible) {
1524
- this.groupStates.forEach((_group, groupId) => {
1525
- this.setGroupVisibility(groupId, visible);
1526
- });
1527
- Object.keys(this.state.layerStates).forEach((layerId) => {
1528
- this.toggleLayerVisibility(layerId, visible);
1529
- const itemEl = this.panel.querySelector(`[data-layer-id="${layerId}"]`);
1530
- if (itemEl) {
1531
- const checkbox = itemEl.querySelector(
1532
- ".layer-control-checkbox"
1533
- );
1534
- if (checkbox) {
1535
- checkbox.checked = visible;
1536
- checkbox.indeterminate = false;
1537
- }
1538
- }
1539
- });
1540
- }
1541
- /**
1542
- * Create the panel header with the title. Panel width is adjusted by
1543
- * dragging either edge of the panel (see createResizeHandle).
1544
- */
1545
- createPanelHeader() {
1546
- const header = document.createElement("div");
1547
- header.className = "layer-control-panel-header";
1548
- const title = document.createElement("span");
1549
- title.className = "layer-control-panel-title";
1550
- title.textContent = "Layers";
1551
- header.appendChild(title);
1552
- return header;
1553
- }
1554
- /**
1555
- * Apply panel width (clamped to min/max)
1556
- */
1557
- applyPanelWidth(width, immediate = false) {
1558
- const clamped = Math.round(
1559
- Math.min(this.maxPanelWidth, Math.max(this.minPanelWidth, width))
1560
- );
1561
- const applyWidth = () => {
1562
- this.state.panelWidth = clamped;
1563
- const px = `${clamped}px`;
1564
- this.panel.style.width = px;
1565
- };
1566
- if (immediate) {
1567
- applyWidth();
1568
- return;
1569
- }
1570
- if (this.widthFrame) {
1571
- cancelAnimationFrame(this.widthFrame);
1572
- }
1573
- this.widthFrame = requestAnimationFrame(() => {
1574
- applyWidth();
1575
- this.widthFrame = null;
1576
- });
1577
- }
1578
- /**
1579
- * Setup main event listeners
1580
- */
1581
- setupEventListeners() {
1582
- this.button.addEventListener("click", () => this.toggle());
1583
- document.addEventListener("click", (e) => {
1584
- const target = e.target;
1585
- if (this.contextMenuEl && this.state.contextMenu.visible) {
1586
- if (!this.contextMenuEl.contains(target)) {
1587
- this.hideContextMenu();
1588
- }
1589
- }
1590
- if (!this.container.contains(target) && !this.panel.contains(target)) {
1591
- this.collapse();
1592
- }
1593
- });
1594
- this.resizeHandler = () => {
1595
- if (!this.state.collapsed) {
1596
- this.updatePanelPosition();
1597
- }
1598
- };
1599
- window.addEventListener("resize", this.resizeHandler);
1600
- this.mapResizeHandler = () => {
1601
- if (!this.state.collapsed) {
1602
- this.updatePanelPosition();
1603
- }
1604
- };
1605
- this.map.on("resize", this.mapResizeHandler);
1606
- this.setupLayerChangeListeners();
1607
- }
1608
- /**
1609
- * Setup listeners for map layer changes
1610
- */
1611
- setupLayerChangeListeners() {
1612
- this.map.on("styledata", () => {
1613
- setTimeout(() => {
1614
- this.updateLayerStatesFromMap();
1615
- this.checkForNewLayers();
1616
- }, 100);
1617
- });
1618
- this.map.on("data", (e) => {
1619
- if (e.sourceDataType === "content") {
1620
- setTimeout(() => {
1621
- this.updateLayerStatesFromMap();
1622
- this.checkForNewLayers();
1623
- }, 100);
1624
- }
1625
- });
1626
- this.map.on("sourcedata", (e) => {
1627
- if (e.sourceDataType === "metadata") {
1628
- setTimeout(() => {
1629
- this.checkForNewLayers();
1630
- }, 150);
1631
- }
1632
- });
1633
- if (this.customLayerRegistry) {
1634
- this.customLayerUnsubscribe = this.customLayerRegistry.onChange(
1635
- (event, layerId) => {
1636
- if (event === "add" && layerId) {
1637
- this.removedCustomLayerIds.delete(layerId);
1638
- }
1639
- setTimeout(() => this.checkForNewLayers(), 100);
1640
- }
1641
- );
1642
- }
1643
- }
1644
- /**
1645
- * Toggle panel expanded/collapsed state
1646
- */
1647
- toggle() {
1648
- if (this.state.collapsed) {
1649
- this.expand();
1650
- } else {
1651
- this.collapse();
1652
- }
1653
- }
1654
- /**
1655
- * Expand the panel
1656
- */
1657
- expand() {
1658
- this.state.collapsed = false;
1659
- this.panel.classList.add("expanded");
1660
- this.updatePanelPosition();
1661
- }
1662
- /**
1663
- * Collapse the panel
1664
- */
1665
- collapse() {
1666
- this.state.collapsed = true;
1667
- this.panel.classList.remove("expanded");
1668
- }
1669
- /**
1670
- * Build layer items (called initially and when layers change)
1671
- */
1672
- buildLayerItems() {
1673
- var _a;
1674
- const existingItems = this.panel.querySelectorAll(
1675
- ".layer-control-item, .layer-control-group"
1676
- );
1677
- existingItems.forEach((item) => item.remove());
1678
- this.styleEditors.clear();
1679
- const orderedLayerIds = this.getUserLayerIdsInMapOrder();
1680
- const captured = new Set(orderedLayerIds);
1681
- for (const layerId of Object.keys(this.state.layerStates)) {
1682
- if (layerId !== "Background" && !captured.has(layerId)) {
1683
- orderedLayerIds.push(layerId);
1684
- }
1685
- }
1686
- if (this.state.layerStates["Background"]) {
1687
- orderedLayerIds.push("Background");
1688
- }
1689
- this.groupStates = new Map(
1690
- (((_a = this.customLayerRegistry) == null ? void 0 : _a.getGroups()) ?? []).map((group) => [
1691
- group.id,
1692
- { ...group }
1693
- ])
1694
- );
1695
- this.groupStructureKey = this.computeGroupStructureKey(this.groupStates);
1696
- const groupContainers = /* @__PURE__ */ new Map();
1697
- orderedLayerIds.forEach((layerId) => {
1698
- const state = this.state.layerStates[layerId];
1699
- if (!state) {
1700
- return;
1701
- }
1702
- if (layerId === "Background" || this.targetLayers.length === 0 || this.targetLayers.includes(layerId)) {
1703
- const container = layerId === "Background" ? this.panel : this.getGroupContainer(
1704
- this.getLayerGroupIdOf(layerId),
1705
- groupContainers,
1706
- /* @__PURE__ */ new Set()
1707
- );
1708
- this.addLayerItem(layerId, state, container);
1709
- }
1710
- });
1711
- }
1712
- /**
1713
- * Get the ID of the group a layer belongs to, ignoring a group ID that no
1714
- * adapter defines.
1715
- * @param layerId The layer ID
1716
- * @returns The group ID, or undefined when the layer is ungrouped
1717
- */
1718
- getLayerGroupIdOf(layerId) {
1719
- var _a;
1720
- if (this.groupStates.size === 0) return void 0;
1721
- const groupId = (_a = this.customLayerRegistry) == null ? void 0 : _a.getLayerGroupId(layerId);
1722
- return groupId !== void 0 && this.groupStates.has(groupId) ? groupId : void 0;
1723
- }
1724
- /**
1725
- * Get the element a group's rows go into, creating the group (and any
1726
- * enclosing groups) on first use.
1727
- * @param groupId The group ID, or undefined for the panel's top level
1728
- * @param containers Group child containers already created in this build
1729
- * @param visiting Groups on the current parent chain, to stop on a cycle
1730
- * @returns The element to append the group's rows to
1731
- */
1732
- getGroupContainer(groupId, containers, visiting) {
1733
- if (groupId === void 0) return this.panel;
1734
- const existing = containers.get(groupId);
1735
- if (existing) return existing;
1736
- const group = this.groupStates.get(groupId);
1737
- if (!group || visiting.has(groupId)) return this.panel;
1738
- visiting.add(groupId);
1739
- const parentId = group.parentId !== void 0 && this.groupStates.has(group.parentId) ? group.parentId : void 0;
1740
- const parent = this.getGroupContainer(parentId, containers, visiting);
1741
- const { element, children } = this.createGroupItem(group);
1742
- parent.appendChild(element);
1743
- containers.set(groupId, children);
1744
- return children;
1745
- }
1746
- /**
1747
- * Summarize the group structure the panel is built from: each group's ID
1748
- * and parent, and each layer's group. A change to any of these needs a
1749
- * rebuild; a change to a group's name, visibility, opacity, or collapsed
1750
- * state does not.
1751
- * @param groups The groups to summarize
1752
- * @returns A string that changes whenever the structure does
1753
- */
1754
- computeGroupStructureKey(groups) {
1755
- if (groups.size === 0) return "";
1756
- const memberships = Object.keys(this.state.layerStates).filter((layerId) => layerId !== "Background").map((layerId) => {
1757
- var _a;
1758
- return [
1759
- layerId,
1760
- ((_a = this.customLayerRegistry) == null ? void 0 : _a.getLayerGroupId(layerId)) ?? null
1761
- ];
1762
- });
1763
- return JSON.stringify({
1764
- groups: Array.from(groups.values(), (group) => [
1765
- group.id,
1766
- group.parentId ?? null
1767
- ]),
1768
- memberships
1769
- });
1770
- }
1771
- /**
1772
- * Create the element for a layer group: a header row with a collapse
1773
- * toggle, visibility checkbox, name, and opacity slider, followed by a
1774
- * container for the group's layers and nested groups.
1775
- * @param group The group to render
1776
- * @returns The group element and its child container
1777
- */
1778
- createGroupItem(group) {
1779
- const element = document.createElement("div");
1780
- element.className = "layer-control-group";
1781
- element.setAttribute("data-group-id", group.id);
1782
- const row = document.createElement("div");
1783
- row.className = "layer-control-row layer-control-group-row";
1784
- if (this.enableDragAndDrop) {
1785
- row.appendChild(this.createDisabledDragHandle());
1786
- }
1787
- const checkbox = document.createElement("input");
1788
- checkbox.type = "checkbox";
1789
- checkbox.className = "layer-control-checkbox layer-control-group-checkbox";
1790
- checkbox.addEventListener("change", () => {
1791
- this.setGroupVisibility(group.id, checkbox.checked);
1792
- });
1793
- row.appendChild(checkbox);
1794
- if (this.showLayerSymbol) {
1795
- const symbol = document.createElement("span");
1796
- symbol.className = "layer-control-symbol layer-control-group-symbol";
1797
- symbol.innerHTML = `<svg viewBox="0 0 16 16" aria-hidden="true">
1798
- <path d="M1.5 3.5h4.5l1.5 1.5h7v8.5h-13z" fill="#f2c94c" stroke="#b8902a" stroke-width="1"/>
1799
- </svg>`;
1800
- symbol.title = "Layer group";
1801
- row.appendChild(symbol);
1802
- }
1803
- const name = document.createElement("span");
1804
- name.className = "layer-control-name layer-control-group-name";
1805
- row.appendChild(name);
1806
- if (this.showOpacitySlider) {
1807
- const opacity = document.createElement("input");
1808
- opacity.type = "range";
1809
- opacity.className = "layer-control-opacity layer-control-group-opacity";
1810
- opacity.min = "0";
1811
- opacity.max = "1";
1812
- opacity.step = "0.01";
1813
- opacity.addEventListener("mousedown", () => {
1814
- this.state.userInteractingWithSlider = true;
1815
- });
1816
- opacity.addEventListener("mouseup", () => {
1817
- this.state.userInteractingWithSlider = false;
1818
- });
1819
- opacity.addEventListener("input", () => {
1820
- this.setGroupOpacity(group.id, parseFloat(opacity.value));
1821
- });
1822
- row.appendChild(opacity);
1823
- }
1824
- const toggle = document.createElement("button");
1825
- toggle.type = "button";
1826
- toggle.className = "layer-control-group-toggle";
1827
- toggle.innerHTML = `<svg viewBox="0 0 16 16" fill="currentColor" aria-hidden="true">
1828
- <path d="M6 4l4 4-4 4z"/>
1829
- </svg>`;
1830
- toggle.addEventListener("click", (e) => {
1831
- var _a;
1832
- e.stopPropagation();
1833
- this.setGroupCollapsed(group.id, !((_a = this.groupStates.get(group.id)) == null ? void 0 : _a.collapsed));
1834
- });
1835
- row.appendChild(toggle);
1836
- const children = document.createElement("div");
1837
- children.className = "layer-control-group-children";
1838
- element.appendChild(row);
1839
- element.appendChild(children);
1840
- this.updateGroupElement(element, group);
1841
- return { element, children };
1842
- }
1843
- /**
1844
- * Show a group's state on its element.
1845
- * @param element The group element
1846
- * @param group The group state to show
1847
- */
1848
- updateGroupElement(element, group) {
1849
- element.classList.toggle("collapsed", group.collapsed);
1850
- element.classList.toggle("layer-control-group-hidden", !group.visible);
1851
- const row = element.querySelector(":scope > .layer-control-group-row");
1852
- if (!row) return;
1853
- const toggle = row.querySelector(
1854
- ".layer-control-group-toggle"
1855
- );
1856
- if (toggle) {
1857
- toggle.setAttribute("aria-expanded", String(!group.collapsed));
1858
- toggle.title = group.collapsed ? "Expand group" : "Collapse group";
1859
- toggle.setAttribute(
1860
- "aria-label",
1861
- `${group.collapsed ? "Expand" : "Collapse"} ${group.name}`
1862
- );
1863
- }
1864
- const checkbox = row.querySelector(
1865
- ".layer-control-group-checkbox"
1866
- );
1867
- if (checkbox) checkbox.checked = group.visible;
1868
- const name = row.querySelector(".layer-control-group-name");
1869
- if (name) {
1870
- name.textContent = group.name;
1871
- name.title = group.name;
1872
- }
1873
- const opacity = row.querySelector(
1874
- ".layer-control-group-opacity"
1875
- );
1876
- if (opacity) {
1877
- opacity.value = String(group.opacity);
1878
- opacity.title = `Opacity: ${Math.round(group.opacity * 100)}%`;
1879
- }
1880
- }
1881
- /**
1882
- * Get the element of a rendered group.
1883
- * @param groupId The group ID
1884
- * @returns The group element, or null when the group is not rendered
1885
- */
1886
- getGroupElement(groupId) {
1887
- const groups = this.panel.querySelectorAll(".layer-control-group");
1888
- for (const element of Array.from(groups)) {
1889
- if (element.dataset.groupId === groupId) {
1890
- return element;
1891
- }
1892
- }
1893
- return null;
1894
- }
1895
- /**
1896
- * Remove group elements left without any layer row, e.g. after their last
1897
- * layer was removed.
1898
- */
1899
- pruneEmptyGroups() {
1900
- const groups = Array.from(this.panel.querySelectorAll(".layer-control-group"));
1901
- for (const element of groups.reverse()) {
1902
- if (!element.querySelector(".layer-control-item")) element.remove();
1903
- }
1904
- }
1905
- /**
1906
- * Set a group's visibility from the panel and report it to its adapter.
1907
- * @param groupId The group ID
1908
- * @param visible Whether the group should be visible
1909
- */
1910
- setGroupVisibility(groupId, visible) {
1911
- var _a;
1912
- const group = this.groupStates.get(groupId);
1913
- if (!group) return;
1914
- group.visible = visible;
1915
- const element = this.getGroupElement(groupId);
1916
- if (element) this.updateGroupElement(element, group);
1917
- this.state.isStyleOperationInProgress = true;
1918
- (_a = this.customLayerRegistry) == null ? void 0 : _a.setGroupVisibility(groupId, visible);
1919
- setTimeout(() => {
1920
- this.state.isStyleOperationInProgress = false;
1921
- }, 200);
1922
- }
1923
- /**
1924
- * Set a group's opacity from the panel and report it to its adapter.
1925
- * @param groupId The group ID
1926
- * @param opacity The opacity value (0-1)
1927
- */
1928
- setGroupOpacity(groupId, opacity) {
1929
- var _a;
1930
- const group = this.groupStates.get(groupId);
1931
- if (!group) return;
1932
- group.opacity = opacity;
1933
- const element = this.getGroupElement(groupId);
1934
- if (element) this.updateGroupElement(element, group);
1935
- this.state.isStyleOperationInProgress = true;
1936
- (_a = this.customLayerRegistry) == null ? void 0 : _a.setGroupOpacity(groupId, opacity);
1937
- setTimeout(() => {
1938
- this.state.isStyleOperationInProgress = false;
1939
- }, 200);
1940
- }
1941
- /**
1942
- * Collapse or expand a group in the panel and report it to its adapter.
1943
- * @param groupId The group ID
1944
- * @param collapsed Whether the group should be collapsed
1945
- */
1946
- setGroupCollapsed(groupId, collapsed) {
1947
- var _a;
1948
- const group = this.groupStates.get(groupId);
1949
- if (!group) return;
1950
- group.collapsed = collapsed;
1951
- const element = this.getGroupElement(groupId);
1952
- if (element) this.updateGroupElement(element, group);
1953
- (_a = this.customLayerRegistry) == null ? void 0 : _a.setGroupCollapsed(groupId, collapsed);
1954
- }
1955
- /**
1956
- * Re-read the layer groups from the custom layer adapters. Call this after
1957
- * groups change outside the control. The panel is rebuilt when a group was
1958
- * added, removed, or re-parented, or a layer changed group; otherwise the
1959
- * group rows' name, visibility, opacity, and collapsed state are updated in
1960
- * place.
1961
- */
1962
- refreshGroups() {
1963
- var _a;
1964
- if (!this.panel) return;
1965
- const next = new Map(
1966
- (((_a = this.customLayerRegistry) == null ? void 0 : _a.getGroups()) ?? []).map((group) => [
1967
- group.id,
1968
- { ...group }
1969
- ])
1970
- );
1971
- if (this.computeGroupStructureKey(next) !== this.groupStructureKey) {
1972
- this.buildLayerItems();
1973
- return;
1974
- }
1975
- this.groupStates = next;
1976
- next.forEach((group, groupId) => {
1977
- const element = this.getGroupElement(groupId);
1978
- if (element) this.updateGroupElement(element, group);
1979
- });
1980
- }
1981
- /**
1982
- * Add a single layer item to the panel
1983
- */
1984
- addLayerItem(layerId, state, container = this.panel) {
1985
- const item = document.createElement("div");
1986
- item.className = "layer-control-item";
1987
- item.setAttribute("data-layer-id", layerId);
1988
- const row = document.createElement("div");
1989
- row.className = "layer-control-row";
1990
- if (this.enableDragAndDrop) {
1991
- if (layerId === "Background") {
1992
- const disabledHandle = this.createDisabledDragHandle();
1993
- row.appendChild(disabledHandle);
1994
- } else {
1995
- const dragHandle = this.createDragHandle(layerId);
1996
- row.appendChild(dragHandle);
1997
- }
1998
- }
1999
- const checkbox = document.createElement("input");
2000
- checkbox.type = "checkbox";
2001
- checkbox.className = "layer-control-checkbox";
2002
- checkbox.checked = state.visible;
2003
- checkbox.addEventListener("change", () => {
2004
- this.toggleLayerVisibility(layerId, checkbox.checked);
2005
- });
2006
- const displayName = this.state.customLayerNames.get(layerId) || state.name || layerId;
2007
- const name = document.createElement("span");
2008
- name.className = "layer-control-name";
2009
- name.textContent = displayName;
2010
- name.title = displayName;
2011
- row.appendChild(checkbox);
2012
- if (this.showLayerSymbol) {
2013
- if (layerId === "Background") {
2014
- const symbol = this.createBackgroundGroupSymbol();
2015
- row.appendChild(symbol);
2016
- } else {
2017
- const symbol = this.createLayerSymbol(layerId);
2018
- if (symbol) {
2019
- row.appendChild(symbol);
2020
- }
2021
- }
2022
- }
2023
- row.appendChild(name);
2024
- if (this.showOpacitySlider) {
2025
- const opacity = document.createElement("input");
2026
- opacity.type = "range";
2027
- opacity.className = "layer-control-opacity";
2028
- opacity.min = "0";
2029
- opacity.max = "1";
2030
- opacity.step = "0.01";
2031
- opacity.value = String(state.opacity);
2032
- opacity.title = `Opacity: ${Math.round(state.opacity * 100)}%`;
2033
- opacity.addEventListener("mousedown", () => {
2034
- this.state.userInteractingWithSlider = true;
2035
- });
2036
- opacity.addEventListener("mouseup", () => {
2037
- this.state.userInteractingWithSlider = false;
2038
- });
2039
- opacity.addEventListener("input", () => {
2040
- this.changeLayerOpacity(layerId, parseFloat(opacity.value));
2041
- opacity.title = `Opacity: ${Math.round(parseFloat(opacity.value) * 100)}%`;
2042
- });
2043
- opacity.addEventListener("dblclick", (event) => {
2044
- event.preventDefault();
2045
- this.showOpacityInput(layerId, opacity);
2046
- });
2047
- row.appendChild(opacity);
2048
- }
2049
- if (this.showStyleEditor) {
2050
- if (layerId === "Background") {
2051
- const legendButton = this.createBackgroundLegendButton();
2052
- row.appendChild(legendButton);
2053
- } else {
2054
- const styleButton = this.createStyleButton(layerId);
2055
- if (styleButton) {
2056
- row.appendChild(styleButton);
2057
- }
2058
- }
2059
- }
2060
- item.appendChild(row);
2061
- if (this.enableContextMenu && layerId !== "Background") {
2062
- row.addEventListener("contextmenu", (e) => {
2063
- e.preventDefault();
2064
- e.stopPropagation();
2065
- this.showContextMenu(layerId, e.clientX, e.clientY);
2066
- });
2067
- }
2068
- container.appendChild(item);
2069
- }
2070
- /**
2071
- * Create a symbol element for a layer
2072
- * @param layerId The layer ID
2073
- * @returns The symbol HTML element, or null if layer not found
2074
- */
2075
- createLayerSymbol(layerId) {
2076
- const layerState = this.state.layerStates[layerId];
2077
- if (layerState == null ? void 0 : layerState.isCustomLayer) {
2078
- const symbolType = layerState.customLayerType || "custom-raster";
2079
- const color2 = "#4a90d9";
2080
- const svgMarkup2 = createLayerSymbolSVG(symbolType, color2);
2081
- const symbolContainer2 = document.createElement("span");
2082
- symbolContainer2.className = "layer-control-symbol";
2083
- symbolContainer2.innerHTML = svgMarkup2;
2084
- symbolContainer2.title = `Layer type: ${symbolType}`;
2085
- return symbolContainer2;
2086
- }
2087
- const layer = this.map.getLayer(layerId);
2088
- if (!layer) return null;
2089
- const layerType = layer.type;
2090
- const color = getLayerColor(this.map, layerId, layerType);
2091
- const svgMarkup = createLayerSymbolSVG(layerType, color);
2092
- const symbolContainer = document.createElement("span");
2093
- symbolContainer.className = "layer-control-symbol";
2094
- symbolContainer.innerHTML = svgMarkup;
2095
- symbolContainer.title = `Layer type: ${layerType}`;
2096
- return symbolContainer;
2097
- }
2098
- /**
2099
- * Create a symbol element for a background layer
2100
- * @param layer The layer specification
2101
- * @returns The symbol HTML element
2102
- */
2103
- createBackgroundLayerSymbol(layer) {
2104
- const color = getLayerColorFromSpec(layer);
2105
- const svgMarkup = createLayerSymbolSVG(layer.type, color, { size: 14 });
2106
- const symbolContainer = document.createElement("span");
2107
- symbolContainer.className = "background-legend-layer-symbol";
2108
- symbolContainer.innerHTML = svgMarkup;
2109
- symbolContainer.title = `Layer type: ${layer.type}`;
2110
- return symbolContainer;
2111
- }
2112
- /**
2113
- * Create a symbol element for the Background layer group
2114
- * Shows a stacked layers icon to represent multiple background layers
2115
- * @returns The symbol HTML element
2116
- */
2117
- createBackgroundGroupSymbol() {
2118
- const svgMarkup = createBackgroundGroupSymbolSVG(16);
2119
- const symbolContainer = document.createElement("span");
2120
- symbolContainer.className = "layer-control-symbol";
2121
- symbolContainer.innerHTML = svgMarkup;
2122
- symbolContainer.title = "Background layers";
2123
- return symbolContainer;
2124
- }
2125
- /**
2126
- * Toggle layer visibility
2127
- */
2128
- toggleLayerVisibility(layerId, visible) {
2129
- var _a;
2130
- if (layerId === "Background") {
2131
- this.toggleBackgroundVisibility(visible);
2132
- return;
2133
- }
2134
- this.state.isStyleOperationInProgress = true;
2135
- if (this.state.layerStates[layerId]) {
2136
- this.state.layerStates[layerId].visible = visible;
2137
- }
2138
- if ((_a = this.customLayerRegistry) == null ? void 0 : _a.setVisibility(layerId, visible)) {
2139
- setTimeout(() => {
2140
- this.state.isStyleOperationInProgress = false;
2141
- }, 200);
2142
- return;
2143
- }
2144
- this.map.setLayoutProperty(
2145
- layerId,
2146
- "visibility",
2147
- visible ? "visible" : "none"
2148
- );
2149
- setTimeout(() => {
2150
- this.state.isStyleOperationInProgress = false;
2151
- }, 200);
2152
- }
2153
- /**
2154
- * Show a small popup that lets the user type an exact opacity percentage
2155
- * (0-100) for a layer. Triggered by double-clicking the opacity slider.
2156
- *
2157
- * @param layerId The layer ID whose opacity is being edited
2158
- * @param slider The opacity range input associated with the layer row
2159
- */
2160
- showOpacityInput(layerId, slider) {
2161
- this.hideOpacityInput();
2162
- const popup = document.createElement("div");
2163
- popup.className = "layer-control-opacity-input";
2164
- const label = document.createElement("span");
2165
- label.className = "layer-control-opacity-input-label";
2166
- label.textContent = "Opacity";
2167
- const field = document.createElement("div");
2168
- field.className = "layer-control-opacity-input-field";
2169
- const input = document.createElement("input");
2170
- input.type = "number";
2171
- input.min = "0";
2172
- input.max = "100";
2173
- input.step = "1";
2174
- input.value = String(Math.round(parseFloat(slider.value) * 100));
2175
- const suffix = document.createElement("span");
2176
- suffix.className = "layer-control-opacity-input-suffix";
2177
- suffix.textContent = "%";
2178
- field.appendChild(input);
2179
- field.appendChild(suffix);
2180
- popup.appendChild(label);
2181
- popup.appendChild(field);
2182
- popup.addEventListener("click", (event) => event.stopPropagation());
2183
- popup.addEventListener("pointerdown", (event) => event.stopPropagation());
2184
- let settled = false;
2185
- const apply = () => {
2186
- if (settled) return;
2187
- settled = true;
2188
- const pct = clamp(Math.round(parseFloat(input.value)), 0, 100);
2189
- if (!Number.isNaN(pct)) {
2190
- const opacity = pct / 100;
2191
- slider.value = String(opacity);
2192
- slider.title = `Opacity: ${pct}%`;
2193
- this.changeLayerOpacity(layerId, opacity);
2194
- }
2195
- this.hideOpacityInput();
2196
- };
2197
- const cancel = () => {
2198
- if (settled) return;
2199
- settled = true;
2200
- this.hideOpacityInput();
2201
- };
2202
- input.addEventListener("keydown", (event) => {
2203
- if (event.key === "Enter") {
2204
- event.preventDefault();
2205
- apply();
2206
- slider.focus();
2207
- } else if (event.key === "Escape") {
2208
- event.preventDefault();
2209
- cancel();
2210
- slider.focus();
2211
- }
2212
- });
2213
- input.addEventListener("blur", apply);
2214
- this.mapContainer.appendChild(popup);
2215
- this.opacityInputEl = popup;
2216
- const sliderRect = slider.getBoundingClientRect();
2217
- const mapRect = this.mapContainer.getBoundingClientRect();
2218
- const popupRect = popup.getBoundingClientRect();
2219
- let left = sliderRect.left - mapRect.left;
2220
- let top = sliderRect.bottom - mapRect.top + 4;
2221
- if (left + popupRect.width > mapRect.width) {
2222
- left = Math.max(0, mapRect.width - popupRect.width - 5);
2223
- }
2224
- if (top + popupRect.height > mapRect.height) {
2225
- top = sliderRect.top - mapRect.top - popupRect.height - 4;
2226
- }
2227
- popup.style.left = `${Math.max(0, left)}px`;
2228
- popup.style.top = `${Math.max(0, top)}px`;
2229
- input.focus();
2230
- input.select();
2231
- }
2232
- /**
2233
- * Remove the exact-opacity input popup if it is open.
2234
- */
2235
- hideOpacityInput() {
2236
- if (this.opacityInputEl) {
2237
- this.opacityInputEl.remove();
2238
- this.opacityInputEl = null;
2239
- }
2240
- }
2241
- /**
2242
- * Change layer opacity
2243
- */
2244
- changeLayerOpacity(layerId, opacity) {
2245
- var _a;
2246
- if (layerId === "Background") {
2247
- this.changeBackgroundOpacity(opacity);
2248
- return;
2249
- }
2250
- this.state.isStyleOperationInProgress = true;
2251
- if (this.state.layerStates[layerId]) {
2252
- this.state.layerStates[layerId].opacity = opacity;
2253
- }
2254
- if ((_a = this.customLayerRegistry) == null ? void 0 : _a.setOpacity(layerId, opacity)) {
2255
- setTimeout(() => {
2256
- this.state.isStyleOperationInProgress = false;
2257
- }, 200);
2258
- return;
2259
- }
2260
- const layerType = getLayerType(this.map, layerId);
2261
- if (layerType) {
2262
- setLayerOpacity(this.map, layerId, layerType, opacity);
2263
- }
2264
- setTimeout(() => {
2265
- this.state.isStyleOperationInProgress = false;
2266
- }, 200);
2267
- }
2268
- /**
2269
- * Check if a layer is a user-added layer (vs basemap layer)
2270
- * Used primarily for the background legend to determine which layers are background
2271
- */
2272
- isUserAddedLayer(layerId) {
2273
- if (this.state.layerStates[layerId] !== void 0 && layerId !== "Background") {
2274
- return true;
2275
- }
2276
- if (this.basemapLayerIds !== null && this.basemapLayerIds.size > 0) {
2277
- return !this.basemapLayerIds.has(layerId);
2278
- }
2279
- if (this.initialLayerIds !== null && !this.initialLayerIds.has(layerId)) {
2280
- return true;
2281
- }
2282
- const layer = this.map.getLayer(layerId);
2283
- if (layer) {
2284
- const sourceId = layer.source;
2285
- if (sourceId) {
2286
- const userAddedSourceIds = this.detectUserAddedSources();
2287
- return userAddedSourceIds.has(sourceId);
2288
- }
2289
- }
2290
- return false;
2291
- }
2292
- /**
2293
- * Toggle visibility for all background layers (basemap layers)
2294
- */
2295
- toggleBackgroundVisibility(visible) {
2296
- var _a;
2297
- if (this.state.layerStates["Background"]) {
2298
- this.state.layerStates["Background"].visible = visible;
2299
- }
2300
- const styleLayers = this.map.getStyle().layers || [];
2301
- styleLayers.forEach((layer) => {
2302
- if (!this.isUserAddedLayer(layer.id)) {
2303
- this.state.backgroundLayerVisibility.set(layer.id, visible);
2304
- this.map.setLayoutProperty(
2305
- layer.id,
2306
- "visibility",
2307
- visible ? "visible" : "none"
2308
- );
2309
- }
2310
- });
2311
- if (this.state.backgroundLegendOpen) {
2312
- const legendPanel = this.panel.querySelector(
2313
- ".layer-control-background-legend"
2314
- );
2315
- if (legendPanel) {
2316
- const checkboxes = legendPanel.querySelectorAll(
2317
- ".background-legend-checkbox"
2318
- );
2319
- checkboxes.forEach((checkbox) => {
2320
- checkbox.checked = visible;
2321
- });
2322
- }
2323
- }
2324
- (_a = this.onBackgroundVisibilityChange) == null ? void 0 : _a.call(this, visible);
2325
- }
2326
- /**
2327
- * Change opacity for all background layers (basemap layers)
2328
- */
2329
- changeBackgroundOpacity(opacity) {
2330
- var _a;
2331
- if (this.state.layerStates["Background"]) {
2332
- this.state.layerStates["Background"].opacity = opacity;
2333
- }
2334
- const styleLayers = this.map.getStyle().layers || [];
2335
- styleLayers.forEach((styleLayer) => {
2336
- if (!this.isUserAddedLayer(styleLayer.id)) {
2337
- const layerType = getLayerType(this.map, styleLayer.id);
2338
- if (layerType) {
2339
- setLayerOpacity(this.map, styleLayer.id, layerType, opacity);
2340
- }
2341
- }
2342
- });
2343
- (_a = this.onBackgroundOpacityChange) == null ? void 0 : _a.call(this, opacity);
2344
- }
2345
- // ===== Background Legend Methods =====
2346
- /**
2347
- * Create legend button for Background layer
2348
- */
2349
- createBackgroundLegendButton() {
2350
- const button = document.createElement("button");
2351
- button.className = "layer-control-style-button layer-control-background-legend-button";
2352
- button.innerHTML = "&#9881;";
2353
- button.title = "Show background layer details";
2354
- button.setAttribute(
2355
- "aria-label",
2356
- "Show background layer visibility controls"
2357
- );
2358
- button.setAttribute(
2359
- "aria-expanded",
2360
- String(this.state.backgroundLegendOpen)
2361
- );
2362
- button.addEventListener("click", (e) => {
2363
- e.stopPropagation();
2364
- this.toggleBackgroundLegend();
2365
- });
2366
- return button;
2367
- }
2368
- /**
2369
- * Toggle background legend panel visibility
2370
- */
2371
- toggleBackgroundLegend() {
2372
- if (this.state.backgroundLegendOpen) {
2373
- this.closeBackgroundLegend();
2374
- } else {
2375
- this.openBackgroundLegend();
2376
- }
2377
- }
2378
- /**
2379
- * Open background legend panel
2380
- */
2381
- openBackgroundLegend() {
2382
- if (this.state.activeStyleEditor) {
2383
- this.closeStyleEditor(this.state.activeStyleEditor);
2384
- }
2385
- const itemEl = this.panel.querySelector('[data-layer-id="Background"]');
2386
- if (!itemEl) return;
2387
- let legendPanel = itemEl.querySelector(".layer-control-background-legend");
2388
- if (legendPanel) {
2389
- const layerList = legendPanel.querySelector(
2390
- ".background-legend-layer-list"
2391
- );
2392
- if (layerList) {
2393
- this.populateBackgroundLayerList(layerList);
2394
- }
2395
- } else {
2396
- legendPanel = this.createBackgroundLegendPanel();
2397
- itemEl.appendChild(legendPanel);
2398
- }
2399
- this.state.backgroundLegendOpen = true;
2400
- const button = itemEl.querySelector(
2401
- ".layer-control-background-legend-button"
2402
- );
2403
- if (button) {
2404
- button.setAttribute("aria-expanded", "true");
2405
- button.classList.add("active");
2406
- }
2407
- setTimeout(() => {
2408
- legendPanel == null ? void 0 : legendPanel.scrollIntoView({ behavior: "smooth", block: "nearest" });
2409
- }, 50);
2410
- }
2411
- /**
2412
- * Close background legend panel
2413
- */
2414
- closeBackgroundLegend() {
2415
- const itemEl = this.panel.querySelector('[data-layer-id="Background"]');
2416
- if (!itemEl) return;
2417
- const legendPanel = itemEl.querySelector(
2418
- ".layer-control-background-legend"
2419
- );
2420
- if (legendPanel) {
2421
- legendPanel.remove();
2422
- }
2423
- this.state.backgroundLegendOpen = false;
2424
- const button = itemEl.querySelector(
2425
- ".layer-control-background-legend-button"
2426
- );
2427
- if (button) {
2428
- button.setAttribute("aria-expanded", "false");
2429
- button.classList.remove("active");
2430
- }
2431
- }
2432
- /**
2433
- * Create the background legend panel with individual layer controls
2434
- */
2435
- createBackgroundLegendPanel() {
2436
- const panel = document.createElement("div");
2437
- panel.className = "layer-control-background-legend";
2438
- const header = document.createElement("div");
2439
- header.className = "background-legend-header";
2440
- const title = document.createElement("span");
2441
- title.className = "background-legend-title";
2442
- title.textContent = "Background Layers";
2443
- const closeBtn = document.createElement("button");
2444
- closeBtn.className = "background-legend-close";
2445
- closeBtn.innerHTML = "&times;";
2446
- closeBtn.title = "Close";
2447
- closeBtn.addEventListener("click", (e) => {
2448
- e.stopPropagation();
2449
- this.closeBackgroundLegend();
2450
- });
2451
- header.appendChild(title);
2452
- header.appendChild(closeBtn);
2453
- const actionsRow = document.createElement("div");
2454
- actionsRow.className = "background-legend-actions";
2455
- const showAllBtn = document.createElement("button");
2456
- showAllBtn.className = "background-legend-action-btn";
2457
- showAllBtn.textContent = "Show All";
2458
- showAllBtn.addEventListener(
2459
- "click",
2460
- () => this.setAllBackgroundLayersVisibility(true)
2461
- );
2462
- const hideAllBtn = document.createElement("button");
2463
- hideAllBtn.className = "background-legend-action-btn";
2464
- hideAllBtn.textContent = "Hide All";
2465
- hideAllBtn.addEventListener(
2466
- "click",
2467
- () => this.setAllBackgroundLayersVisibility(false)
2468
- );
2469
- actionsRow.appendChild(showAllBtn);
2470
- actionsRow.appendChild(hideAllBtn);
2471
- const filterRow = document.createElement("div");
2472
- filterRow.className = "background-legend-filter";
2473
- const filterCheckbox = document.createElement("input");
2474
- filterCheckbox.type = "checkbox";
2475
- filterCheckbox.className = "background-legend-filter-checkbox";
2476
- filterCheckbox.id = "background-legend-only-rendered";
2477
- filterCheckbox.checked = this.state.onlyRenderedFilter;
2478
- filterCheckbox.addEventListener("change", () => {
2479
- this.state.onlyRenderedFilter = filterCheckbox.checked;
2480
- const layerList2 = panel.querySelector(".background-legend-layer-list");
2481
- if (layerList2) {
2482
- this.populateBackgroundLayerList(layerList2);
2483
- }
2484
- });
2485
- const filterLabel = document.createElement("label");
2486
- filterLabel.className = "background-legend-filter-label";
2487
- filterLabel.htmlFor = "background-legend-only-rendered";
2488
- filterLabel.textContent = "Only rendered";
2489
- filterRow.appendChild(filterCheckbox);
2490
- filterRow.appendChild(filterLabel);
2491
- const layerList = document.createElement("div");
2492
- layerList.className = "background-legend-layer-list";
2493
- this.populateBackgroundLayerList(layerList);
2494
- panel.appendChild(header);
2495
- panel.appendChild(actionsRow);
2496
- panel.appendChild(filterRow);
2497
- panel.appendChild(layerList);
2498
- if (this.enableBackgroundPresets) {
2499
- panel.appendChild(this.createBackgroundPresetsRow());
2500
- }
2501
- return panel;
2502
- }
2503
- /**
2504
- * Build the "Saved configurations" controls: a dropdown of saved presets with
2505
- * Apply/Delete actions, plus a name field and Save button to capture the
2506
- * current basemap element visibility as a reusable, persisted preset.
2507
- */
2508
- createBackgroundPresetsRow() {
2509
- const section = document.createElement("div");
2510
- section.className = "background-legend-presets";
2511
- const label = document.createElement("div");
2512
- label.className = "background-legend-presets-label";
2513
- label.textContent = "Saved configurations";
2514
- section.appendChild(label);
2515
- const selectRow = document.createElement("div");
2516
- selectRow.className = "background-legend-presets-row";
2517
- const select = document.createElement("select");
2518
- select.className = "background-legend-presets-select";
2519
- select.title = "Saved configurations";
2520
- const applyBtn = document.createElement("button");
2521
- applyBtn.className = "background-legend-action-btn";
2522
- applyBtn.textContent = "Apply";
2523
- applyBtn.title = "Apply the selected configuration";
2524
- const deleteBtn = document.createElement("button");
2525
- deleteBtn.className = "background-legend-action-btn";
2526
- deleteBtn.textContent = "Delete";
2527
- deleteBtn.title = "Delete the selected configuration";
2528
- const refreshSelect = (selected) => {
2529
- const presets = this.getBackgroundPresets();
2530
- const names = Object.keys(presets).sort(
2531
- (a, b) => a.localeCompare(b, void 0, { sensitivity: "base" })
2532
- );
2533
- select.innerHTML = "";
2534
- const placeholder = document.createElement("option");
2535
- placeholder.value = "";
2536
- placeholder.textContent = names.length ? "Select a configuration…" : "No saved configurations";
2537
- placeholder.disabled = names.length > 0;
2538
- select.appendChild(placeholder);
2539
- names.forEach((name) => {
2540
- const option = document.createElement("option");
2541
- option.value = name;
2542
- option.textContent = name;
2543
- select.appendChild(option);
2544
- });
2545
- select.value = selected && names.includes(selected) ? selected : "";
2546
- const hasSelection = select.value !== "";
2547
- applyBtn.disabled = !hasSelection;
2548
- deleteBtn.disabled = !hasSelection;
2549
- };
2550
- select.addEventListener("change", () => {
2551
- const hasSelection = select.value !== "";
2552
- applyBtn.disabled = !hasSelection;
2553
- deleteBtn.disabled = !hasSelection;
2554
- });
2555
- applyBtn.addEventListener("click", (e) => {
2556
- e.stopPropagation();
2557
- if (select.value) this.applyBackgroundPreset(select.value);
2558
- });
2559
- deleteBtn.addEventListener("click", (e) => {
2560
- e.stopPropagation();
2561
- if (select.value) {
2562
- this.deleteBackgroundPreset(select.value);
2563
- refreshSelect();
2564
- }
2565
- });
2566
- selectRow.appendChild(select);
2567
- selectRow.appendChild(applyBtn);
2568
- selectRow.appendChild(deleteBtn);
2569
- const saveRow = document.createElement("div");
2570
- saveRow.className = "background-legend-presets-row";
2571
- const nameInput = document.createElement("input");
2572
- nameInput.type = "text";
2573
- nameInput.className = "background-legend-presets-input";
2574
- nameInput.placeholder = "Configuration name…";
2575
- nameInput.maxLength = 60;
2576
- const saveBtn = document.createElement("button");
2577
- saveBtn.className = "background-legend-action-btn";
2578
- saveBtn.textContent = "Save";
2579
- saveBtn.title = "Save the current visibility as a configuration";
2580
- const commitSave = () => {
2581
- const name = nameInput.value.trim();
2582
- if (!name) return;
2583
- this.saveBackgroundPreset(name);
2584
- nameInput.value = "";
2585
- refreshSelect(name);
2586
- };
2587
- saveBtn.addEventListener("click", (e) => {
2588
- e.stopPropagation();
2589
- commitSave();
2590
- });
2591
- nameInput.addEventListener("keydown", (e) => {
2592
- if (e.key === "Enter") {
2593
- e.preventDefault();
2594
- commitSave();
2595
- }
2596
- });
2597
- saveRow.appendChild(nameInput);
2598
- saveRow.appendChild(saveBtn);
2599
- section.appendChild(selectRow);
2600
- section.appendChild(saveRow);
2601
- refreshSelect();
2602
- return section;
2603
- }
2604
- /**
2605
- * Check if a layer is currently rendered in the map viewport
2606
- */
2607
- isLayerRendered(layerId) {
2608
- try {
2609
- const layer = this.map.getLayer(layerId);
2610
- if (!layer) return false;
2611
- const visibility = this.map.getLayoutProperty(layerId, "visibility");
2612
- if (visibility === "none") return false;
2613
- if (layer.type === "raster" || layer.type === "hillshade") {
2614
- return true;
2615
- }
2616
- if (layer.type === "background") {
2617
- return true;
2618
- }
2619
- const features = this.map.queryRenderedFeatures({ layers: [layerId] });
2620
- return features.length > 0;
2621
- } catch (error) {
2622
- return true;
2623
- }
2624
- }
2625
- /**
2626
- * Populate the background layer list with individual layers
2627
- */
2628
- populateBackgroundLayerList(container) {
2629
- container.innerHTML = "";
2630
- const styleLayers = this.map.getStyle().layers || [];
2631
- styleLayers.forEach((layer) => {
2632
- if (!this.isUserAddedLayer(layer.id)) {
2633
- if (this.excludeDrawnLayers && this.isDrawnLayer(layer.id)) {
2634
- return;
2635
- }
2636
- if (this.isExcludedByPattern(layer.id)) {
2637
- return;
2638
- }
2639
- if (this.state.onlyRenderedFilter && !this.isLayerRendered(layer.id)) {
2640
- return;
2641
- }
2642
- const layerRow = document.createElement("div");
2643
- layerRow.className = "background-legend-layer-row";
2644
- layerRow.setAttribute("data-background-layer-id", layer.id);
2645
- const checkbox = document.createElement("input");
2646
- checkbox.type = "checkbox";
2647
- checkbox.className = "background-legend-checkbox";
2648
- const visibility = this.map.getLayoutProperty(layer.id, "visibility");
2649
- const isVisible = visibility !== "none";
2650
- checkbox.checked = isVisible;
2651
- this.state.backgroundLayerVisibility.set(layer.id, isVisible);
2652
- checkbox.addEventListener("change", () => {
2653
- this.toggleIndividualBackgroundLayer(layer.id, checkbox.checked);
2654
- });
2655
- const name = document.createElement("span");
2656
- name.className = "background-legend-layer-name";
2657
- name.textContent = this.generateFriendlyName(layer.id);
2658
- name.title = layer.id;
2659
- const typeIndicator = document.createElement("span");
2660
- typeIndicator.className = "background-legend-layer-type";
2661
- typeIndicator.textContent = layer.type;
2662
- layerRow.appendChild(checkbox);
2663
- if (this.showLayerSymbol) {
2664
- const symbol = this.createBackgroundLayerSymbol(layer);
2665
- if (symbol) {
2666
- layerRow.appendChild(symbol);
2667
- }
2668
- }
2669
- layerRow.appendChild(name);
2670
- layerRow.appendChild(typeIndicator);
2671
- container.appendChild(layerRow);
2672
- }
2673
- });
2674
- if (container.children.length === 0) {
2675
- const emptyMsg = document.createElement("p");
2676
- emptyMsg.className = "background-legend-empty";
2677
- emptyMsg.textContent = this.state.onlyRenderedFilter ? "No rendered layers in current view." : "No background layers found.";
2678
- container.appendChild(emptyMsg);
2679
- }
2680
- }
2681
- /**
2682
- * Toggle visibility of an individual background layer
2683
- */
2684
- toggleIndividualBackgroundLayer(layerId, visible) {
2685
- this.state.backgroundLayerVisibility.set(layerId, visible);
2686
- this.map.setLayoutProperty(
2687
- layerId,
2688
- "visibility",
2689
- visible ? "visible" : "none"
2690
- );
2691
- this.updateBackgroundCheckboxState();
2692
- }
2693
- /**
2694
- * Set visibility for all background layers
2695
- */
2696
- setAllBackgroundLayersVisibility(visible) {
2697
- const styleLayers = this.map.getStyle().layers || [];
2698
- styleLayers.forEach((layer) => {
2699
- if (!this.isUserAddedLayer(layer.id)) {
2700
- this.state.backgroundLayerVisibility.set(layer.id, visible);
2701
- this.map.setLayoutProperty(
2702
- layer.id,
2703
- "visibility",
2704
- visible ? "visible" : "none"
2705
- );
2706
- }
2707
- });
2708
- const legendPanel = this.panel.querySelector(
2709
- ".layer-control-background-legend"
2710
- );
2711
- if (legendPanel) {
2712
- const checkboxes = legendPanel.querySelectorAll(
2713
- ".background-legend-checkbox"
2714
- );
2715
- checkboxes.forEach((checkbox) => {
2716
- checkbox.checked = visible;
2717
- });
2718
- }
2719
- this.updateBackgroundCheckboxState();
2720
- }
2721
- /**
2722
- * Update the main Background checkbox based on individual layer states
2723
- */
2724
- updateBackgroundCheckboxState() {
2725
- const styleLayers = this.map.getStyle().layers || [];
2726
- let anyVisible = false;
2727
- let allVisible = true;
2728
- styleLayers.forEach((layer) => {
2729
- if (!this.isUserAddedLayer(layer.id)) {
2730
- const visible = this.state.backgroundLayerVisibility.get(layer.id);
2731
- if (visible === true) anyVisible = true;
2732
- if (visible === false) allVisible = false;
2733
- }
2734
- });
2735
- const backgroundItem = this.panel.querySelector(
2736
- '[data-layer-id="Background"]'
2737
- );
2738
- if (backgroundItem) {
2739
- const checkbox = backgroundItem.querySelector(
2740
- ".layer-control-checkbox"
2741
- );
2742
- if (checkbox) {
2743
- checkbox.checked = anyVisible;
2744
- checkbox.indeterminate = anyVisible && !allVisible;
2745
- }
2746
- }
2747
- if (this.state.layerStates["Background"]) {
2748
- this.state.layerStates["Background"].visible = anyVisible;
2749
- }
2750
- }
2751
- /**
2752
- * Return the IDs of the background (basemap) style layers the control can
2753
- * toggle, honoring the drawn-layer and user-defined exclusion filters but not
2754
- * the transient "only rendered" view filter.
2755
- */
2756
- getControllableBackgroundLayerIds() {
2757
- const styleLayers = this.map.getStyle().layers || [];
2758
- return styleLayers.filter((layer) => {
2759
- if (this.isUserAddedLayer(layer.id)) return false;
2760
- if (this.excludeDrawnLayers && this.isDrawnLayer(layer.id))
2761
- return false;
2762
- if (this.isExcludedByPattern(layer.id)) return false;
2763
- return true;
2764
- }).map((layer) => layer.id);
2765
- }
2766
- /**
2767
- * Get the current visibility of every controllable background (basemap) layer.
2768
- *
2769
- * @returns A map of style-layer ID to whether it is currently visible.
2770
- */
2771
- getBackgroundLayerVisibility() {
2772
- const visibility = {};
2773
- for (const layerId of this.getControllableBackgroundLayerIds()) {
2774
- const value = this.map.getLayoutProperty(layerId, "visibility");
2775
- visibility[layerId] = value !== "none";
2776
- }
2777
- return visibility;
2778
- }
2779
- /**
2780
- * Apply a saved background-layer visibility configuration to the map. Only
2781
- * layers that currently exist in the style are affected, so a configuration
2782
- * captured on one basemap degrades gracefully when applied to another.
2783
- *
2784
- * @param visibility - Map of style-layer ID to desired visibility.
2785
- */
2786
- applyBackgroundLayerVisibility(visibility) {
2787
- for (const [layerId, visible] of Object.entries(visibility)) {
2788
- if (this.isUserAddedLayer(layerId)) continue;
2789
- if (!this.map.getLayer(layerId)) continue;
2790
- this.state.backgroundLayerVisibility.set(layerId, visible);
2791
- this.map.setLayoutProperty(
2792
- layerId,
2793
- "visibility",
2794
- visible ? "visible" : "none"
2795
- );
2796
- }
2797
- const legendPanel = this.panel.querySelector(
2798
- ".background-legend-layer-list"
2799
- );
2800
- if (legendPanel) {
2801
- this.populateBackgroundLayerList(legendPanel);
2802
- }
2803
- this.updateBackgroundCheckboxState();
2804
- }
2805
- /**
2806
- * Read all saved background-layer presets from localStorage. Returns an empty
2807
- * object when storage is unavailable or the stored value is malformed.
2808
- */
2809
- getBackgroundPresets() {
2810
- try {
2811
- const raw = typeof localStorage !== "undefined" ? localStorage.getItem(this.backgroundPresetStorageKey) : null;
2812
- if (!raw) return {};
2813
- const parsed = JSON.parse(raw);
2814
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
2815
- return {};
2816
- }
2817
- const presets = {};
2818
- for (const [name, value] of Object.entries(parsed)) {
2819
- if (this.isUnsafePresetKey(name)) continue;
2820
- if (value && typeof value === "object" && !Array.isArray(value)) {
2821
- presets[name] = value;
2822
- }
2823
- }
2824
- return presets;
2825
- } catch {
2826
- return {};
2827
- }
2828
- }
2829
- /**
2830
- * Reject preset names that, used as object keys, could pollute the prototype
2831
- * chain or otherwise alias built-in object members.
2832
- */
2833
- isUnsafePresetKey(name) {
2834
- return name === "__proto__" || name === "constructor" || name === "prototype";
2835
- }
2836
- /**
2837
- * Persist the full preset map to localStorage and notify listeners.
2838
- */
2839
- writeBackgroundPresets(presets) {
2840
- var _a;
2841
- try {
2842
- if (typeof localStorage !== "undefined") {
2843
- localStorage.setItem(
2844
- this.backgroundPresetStorageKey,
2845
- JSON.stringify(presets)
2846
- );
2847
- }
2848
- } catch {
2849
- }
2850
- (_a = this.onBackgroundPresetsChange) == null ? void 0 : _a.call(this, presets);
2851
- }
2852
- /**
2853
- * Save the current background-layer visibility as a named preset. Reusing an
2854
- * existing name overwrites that preset.
2855
- *
2856
- * @param name - Preset name; whitespace is trimmed. Empty names are ignored.
2857
- * @returns The updated preset map.
2858
- */
2859
- saveBackgroundPreset(name) {
2860
- const trimmed = name.trim();
2861
- const presets = this.getBackgroundPresets();
2862
- if (!trimmed || this.isUnsafePresetKey(trimmed)) return presets;
2863
- presets[trimmed] = this.getBackgroundLayerVisibility();
2864
- this.writeBackgroundPresets(presets);
2865
- return presets;
2866
- }
2867
- /**
2868
- * Apply a previously saved preset to the map.
2869
- *
2870
- * @param name - The preset name to apply.
2871
- * @returns `true` if a preset with that name existed and was applied.
2872
- */
2873
- applyBackgroundPreset(name) {
2874
- const presets = this.getBackgroundPresets();
2875
- if (!Object.prototype.hasOwnProperty.call(presets, name)) return false;
2876
- this.applyBackgroundLayerVisibility(presets[name]);
2877
- return true;
2878
- }
2879
- /**
2880
- * Delete a saved preset.
2881
- *
2882
- * @param name - The preset name to remove.
2883
- * @returns The updated preset map.
2884
- */
2885
- deleteBackgroundPreset(name) {
2886
- const presets = this.getBackgroundPresets();
2887
- if (Object.prototype.hasOwnProperty.call(presets, name)) {
2888
- delete presets[name];
2889
- this.writeBackgroundPresets(presets);
2890
- }
2891
- return presets;
2892
- }
2893
- /**
2894
- * Create style button for a layer
2895
- */
2896
- createStyleButton(layerId) {
2897
- if (layerId === "Background") {
2898
- return null;
2899
- }
2900
- const layerState = this.state.layerStates[layerId];
2901
- const isCustomLayer = (layerState == null ? void 0 : layerState.isCustomLayer) === true;
2902
- const button = document.createElement("button");
2903
- button.className = "layer-control-style-button";
2904
- button.innerHTML = "&#9881;";
2905
- if (isCustomLayer) {
2906
- button.title = "Layer info (style editing not available)";
2907
- button.setAttribute("aria-label", `Layer info for ${layerId}`);
2908
- } else {
2909
- button.title = "Edit layer style";
2910
- button.setAttribute("aria-label", `Edit style for ${layerId}`);
2911
- }
2912
- button.addEventListener("click", (e) => {
2913
- e.stopPropagation();
2914
- this.toggleStyleEditor(layerId);
2915
- });
2916
- return button;
2917
- }
2918
- /**
2919
- * Toggle style editor for a layer
2920
- */
2921
- toggleStyleEditor(layerId) {
2922
- if (this.state.activeStyleEditor === layerId) {
2923
- this.closeStyleEditor(layerId);
2924
- return;
2925
- }
2926
- if (this.state.activeStyleEditor) {
2927
- this.closeStyleEditor(this.state.activeStyleEditor);
2928
- }
2929
- this.openStyleEditor(layerId);
2930
- }
2931
- /**
2932
- * Open style editor for a layer
2933
- */
2934
- openStyleEditor(layerId) {
2935
- var _a;
2936
- const itemEl = this.panel.querySelector(`[data-layer-id="${layerId}"]`);
2937
- if (!itemEl) return;
2938
- const layerState = this.state.layerStates[layerId];
2939
- if (layerState == null ? void 0 : layerState.isCustomLayer) {
2940
- const nativeLayerIds = (_a = this.customLayerRegistry) == null ? void 0 : _a.getNativeLayerIds(layerId);
2941
- if (nativeLayerIds && nativeLayerIds.length > 0) {
2942
- for (const nativeId of nativeLayerIds) {
2943
- if (!this.state.originalStyles.has(nativeId)) {
2944
- const nativeLayer = this.map.getLayer(nativeId);
2945
- if (nativeLayer) {
2946
- cacheOriginalLayerStyle(
2947
- this.map,
2948
- nativeId,
2949
- this.state.originalStyles
2950
- );
2951
- }
2952
- }
2953
- }
2954
- const editor3 = this.createNativeSubLayerStyleEditor(
2955
- layerId,
2956
- nativeLayerIds
2957
- );
2958
- if (editor3) {
2959
- itemEl.appendChild(editor3);
2960
- this.styleEditors.set(layerId, editor3);
2961
- this.state.activeStyleEditor = layerId;
2962
- setTimeout(() => {
2963
- editor3.scrollIntoView({ behavior: "smooth", block: "nearest" });
2964
- }, 50);
2965
- return;
2966
- }
2967
- }
2968
- const editor2 = this.createCustomLayerInfoPanel(layerId);
2969
- itemEl.appendChild(editor2);
2970
- this.styleEditors.set(layerId, editor2);
2971
- this.state.activeStyleEditor = layerId;
2972
- setTimeout(() => {
2973
- editor2.scrollIntoView({ behavior: "smooth", block: "nearest" });
2974
- }, 50);
2975
- return;
2976
- }
2977
- if (!this.state.originalStyles.has(layerId)) {
2978
- const layer = this.map.getLayer(layerId);
2979
- if (layer) {
2980
- cacheOriginalLayerStyle(this.map, layerId, this.state.originalStyles);
2981
- }
2982
- }
2983
- const editor = this.createStyleEditor(layerId);
2984
- if (!editor) return;
2985
- itemEl.appendChild(editor);
2986
- this.styleEditors.set(layerId, editor);
2987
- this.state.activeStyleEditor = layerId;
2988
- setTimeout(() => {
2989
- editor.scrollIntoView({ behavior: "smooth", block: "nearest" });
2990
- }, 50);
2991
- }
2992
- /**
2993
- * Create info panel for custom layers (style editing not supported)
2994
- */
2995
- createCustomLayerInfoPanel(layerId) {
2996
- const editor = document.createElement("div");
2997
- editor.className = "layer-control-style-editor layer-control-custom-info";
2998
- const header = document.createElement("div");
2999
- header.className = "style-editor-header";
3000
- const title = document.createElement("span");
3001
- title.className = "style-editor-title";
3002
- title.textContent = "Layer Info";
3003
- const closeBtn = document.createElement("button");
3004
- closeBtn.className = "style-editor-close";
3005
- closeBtn.innerHTML = "&times;";
3006
- closeBtn.title = "Close";
3007
- closeBtn.addEventListener("click", (e) => {
3008
- e.stopPropagation();
3009
- this.closeStyleEditor(layerId);
3010
- });
3011
- header.appendChild(title);
3012
- header.appendChild(closeBtn);
3013
- const content = document.createElement("div");
3014
- content.className = "style-editor-controls";
3015
- const infoText = document.createElement("p");
3016
- infoText.className = "layer-control-custom-info-text";
3017
- infoText.textContent = `This is a custom layer. Style editing is not available for this layer type. Use the visibility toggle and opacity slider to control the layer.`;
3018
- content.appendChild(infoText);
3019
- const actions = document.createElement("div");
3020
- actions.className = "style-editor-actions";
3021
- const removeBtn = document.createElement("button");
3022
- removeBtn.className = "style-editor-button style-editor-button-remove";
3023
- removeBtn.textContent = "Remove Layer";
3024
- removeBtn.title = "Remove layer from map";
3025
- removeBtn.addEventListener("click", (e) => {
3026
- e.stopPropagation();
3027
- this.showRemoveConfirmation(editor, () => {
3028
- this.closeStyleEditor(layerId);
3029
- this.removeLayer(layerId);
3030
- });
3031
- });
3032
- const closeActionBtn = document.createElement("button");
3033
- closeActionBtn.className = "style-editor-button style-editor-button-close";
3034
- closeActionBtn.textContent = "Close";
3035
- closeActionBtn.addEventListener("click", (e) => {
3036
- e.stopPropagation();
3037
- this.closeStyleEditor(layerId);
3038
- });
3039
- actions.appendChild(removeBtn);
3040
- actions.appendChild(closeActionBtn);
3041
- editor.appendChild(header);
3042
- editor.appendChild(content);
3043
- editor.appendChild(actions);
3044
- return editor;
3045
- }
3046
- /**
3047
- * Create a combined style editor for custom layers with native MapLibre sublayers.
3048
- * Groups controls by sublayer type (fill, line, circle, etc.).
3049
- */
3050
- createNativeSubLayerStyleEditor(layerId, nativeLayerIds) {
3051
- const layersByType = /* @__PURE__ */ new Map();
3052
- for (const nativeId of nativeLayerIds) {
3053
- const layer = this.map.getLayer(nativeId);
3054
- if (layer) {
3055
- const type = layer.type;
3056
- if (!layersByType.has(type)) {
3057
- layersByType.set(type, []);
3058
- }
3059
- layersByType.get(type).push(nativeId);
3060
- }
3061
- }
3062
- if (layersByType.size === 0) return null;
3063
- const editor = document.createElement("div");
3064
- editor.className = "layer-control-style-editor";
3065
- const header = document.createElement("div");
3066
- header.className = "style-editor-header";
3067
- const title = document.createElement("span");
3068
- title.className = "style-editor-title";
3069
- title.textContent = "Edit Style";
3070
- const closeBtn = document.createElement("button");
3071
- closeBtn.className = "style-editor-close";
3072
- closeBtn.innerHTML = "&times;";
3073
- closeBtn.title = "Close";
3074
- closeBtn.addEventListener("click", (e) => {
3075
- e.stopPropagation();
3076
- this.closeStyleEditor(layerId);
3077
- });
3078
- header.appendChild(title);
3079
- header.appendChild(closeBtn);
3080
- editor.appendChild(header);
3081
- const controls = document.createElement("div");
3082
- controls.className = "style-editor-controls";
3083
- const typeLabels = {
3084
- fill: "Fill",
3085
- line: "Line",
3086
- circle: "Circle",
3087
- symbol: "Symbol",
3088
- raster: "Raster"
3089
- };
3090
- for (const [type, ids] of layersByType) {
3091
- if (layersByType.size > 1) {
3092
- const sectionHeader = document.createElement("div");
3093
- sectionHeader.className = "style-editor-section-header";
3094
- sectionHeader.textContent = typeLabels[type] || type;
3095
- controls.appendChild(sectionHeader);
3096
- }
3097
- const primaryId = ids[0];
3098
- this.addStyleControlsForNativeGroup(controls, ids, primaryId, type);
3099
- }
3100
- const actions = document.createElement("div");
3101
- actions.className = "style-editor-actions";
3102
- const resetBtn = document.createElement("button");
3103
- resetBtn.className = "style-editor-button style-editor-button-reset";
3104
- resetBtn.textContent = "Reset Style";
3105
- resetBtn.addEventListener("click", (e) => {
3106
- e.stopPropagation();
3107
- for (const nativeId of nativeLayerIds) {
3108
- restoreOriginalStyle(this.map, nativeId, this.state.originalStyles);
3109
- }
3110
- if (this.onLayerStyleChange) {
3111
- editor.querySelectorAll("[data-property]").forEach((el) => {
3112
- const control = el;
3113
- const property = control.dataset.property;
3114
- const sourceId = control.dataset.layerId;
3115
- if (!property || !sourceId) return;
3116
- const value = this.map.getPaintProperty(sourceId, property);
3117
- if (value !== void 0) {
3118
- this.notifyLayerStyleChange(
3119
- property,
3120
- typeof value === "number" ? value : normalizeColor(value)
3121
- );
3122
- }
3123
- });
3124
- }
3125
- this.closeStyleEditor(layerId);
3126
- this.openStyleEditor(layerId);
3127
- });
3128
- const removeBtn = document.createElement("button");
3129
- removeBtn.className = "style-editor-button style-editor-button-remove";
3130
- removeBtn.textContent = "Remove Layer";
3131
- removeBtn.title = "Remove layer from map";
3132
- removeBtn.addEventListener("click", (e) => {
3133
- e.stopPropagation();
3134
- this.showRemoveConfirmation(editor, () => {
3135
- this.closeStyleEditor(layerId);
3136
- this.removeLayer(layerId);
3137
- });
3138
- });
3139
- const closeActionBtn = document.createElement("button");
3140
- closeActionBtn.className = "style-editor-button style-editor-button-close";
3141
- closeActionBtn.textContent = "Close";
3142
- closeActionBtn.addEventListener("click", (e) => {
3143
- e.stopPropagation();
3144
- this.closeStyleEditor(layerId);
3145
- });
3146
- actions.appendChild(resetBtn);
3147
- actions.appendChild(removeBtn);
3148
- actions.appendChild(closeActionBtn);
3149
- editor.appendChild(controls);
3150
- editor.appendChild(actions);
3151
- return editor;
3152
- }
3153
- /**
3154
- * Add style controls for a group of native layers of the same type.
3155
- * Changes to any control are applied to all layers in the group.
3156
- */
3157
- addStyleControlsForNativeGroup(container, layerIds, primaryLayerId, layerType) {
3158
- this.nativeLayerGroups.set(primaryLayerId, layerIds);
3159
- this.addStyleControlsForLayerType(container, primaryLayerId, layerType);
3160
- }
3161
- /**
3162
- * Close style editor for a layer
3163
- */
3164
- closeStyleEditor(layerId) {
3165
- const editor = this.styleEditors.get(layerId);
3166
- if (editor) {
3167
- editor.remove();
3168
- this.styleEditors.delete(layerId);
3169
- }
3170
- this.nativeLayerGroups.clear();
3171
- if (this.state.activeStyleEditor === layerId) {
3172
- this.state.activeStyleEditor = null;
3173
- }
3174
- }
3175
- /**
3176
- * Create style editor UI
3177
- */
3178
- createStyleEditor(layerId) {
3179
- const layer = this.map.getLayer(layerId);
3180
- if (!layer) return null;
3181
- const editor = document.createElement("div");
3182
- editor.className = "layer-control-style-editor";
3183
- const header = document.createElement("div");
3184
- header.className = "style-editor-header";
3185
- const title = document.createElement("span");
3186
- title.className = "style-editor-title";
3187
- title.textContent = "Edit Style";
3188
- const closeBtn = document.createElement("button");
3189
- closeBtn.className = "style-editor-close";
3190
- closeBtn.innerHTML = "&times;";
3191
- closeBtn.title = "Close";
3192
- closeBtn.addEventListener("click", (e) => {
3193
- e.stopPropagation();
3194
- this.closeStyleEditor(layerId);
3195
- });
3196
- header.appendChild(title);
3197
- header.appendChild(closeBtn);
3198
- const controls = document.createElement("div");
3199
- controls.className = "style-editor-controls";
3200
- const layerType = layer.type;
3201
- this.addStyleControlsForLayerType(controls, layerId, layerType);
3202
- const actions = document.createElement("div");
3203
- actions.className = "style-editor-actions";
3204
- const resetBtn = document.createElement("button");
3205
- resetBtn.className = "style-editor-button style-editor-button-reset";
3206
- resetBtn.textContent = "Reset Style";
3207
- resetBtn.addEventListener("click", (e) => {
3208
- e.stopPropagation();
3209
- this.resetLayerStyle(layerId);
3210
- });
3211
- const removeBtn = document.createElement("button");
3212
- removeBtn.className = "style-editor-button style-editor-button-remove";
3213
- removeBtn.textContent = "Remove Layer";
3214
- removeBtn.title = "Remove layer from map";
3215
- removeBtn.addEventListener("click", (e) => {
3216
- e.stopPropagation();
3217
- this.showRemoveConfirmation(editor, () => {
3218
- this.closeStyleEditor(layerId);
3219
- this.removeLayer(layerId);
3220
- });
3221
- });
3222
- const closeActionBtn = document.createElement("button");
3223
- closeActionBtn.className = "style-editor-button style-editor-button-close";
3224
- closeActionBtn.textContent = "Close";
3225
- closeActionBtn.addEventListener("click", (e) => {
3226
- e.stopPropagation();
3227
- this.closeStyleEditor(layerId);
3228
- });
3229
- actions.appendChild(resetBtn);
3230
- actions.appendChild(removeBtn);
3231
- actions.appendChild(closeActionBtn);
3232
- editor.appendChild(header);
3233
- editor.appendChild(controls);
3234
- editor.appendChild(actions);
3235
- return editor;
3236
- }
3237
- /**
3238
- * Add style controls based on layer type
3239
- */
3240
- addStyleControlsForLayerType(container, layerId, layerType) {
3241
- switch (layerType) {
3242
- case "fill":
3243
- this.addFillControls(container, layerId);
3244
- break;
3245
- case "line":
3246
- this.addLineControls(container, layerId);
3247
- break;
3248
- case "circle":
3249
- this.addCircleControls(container, layerId);
3250
- break;
3251
- case "raster":
3252
- this.addRasterControls(container, layerId);
3253
- break;
3254
- case "symbol":
3255
- this.addSymbolControls(container, layerId);
3256
- break;
3257
- default:
3258
- container.textContent = `Style controls for ${layerType} layers not yet implemented.`;
3259
- }
3260
- }
3261
- /**
3262
- * Add controls for fill layers
3263
- */
3264
- addFillControls(container, layerId) {
3265
- var _a;
3266
- const style = this.map.getStyle();
3267
- const layer = (_a = style.layers) == null ? void 0 : _a.find((l) => l.id === layerId);
3268
- let fillColor = void 0;
3269
- if (layer && "paint" in layer && layer.paint && "fill-color" in layer.paint) {
3270
- fillColor = layer.paint["fill-color"];
3271
- }
3272
- if (!fillColor) {
3273
- fillColor = this.map.getPaintProperty(layerId, "fill-color");
3274
- }
3275
- this.createColorControl(
3276
- container,
3277
- layerId,
3278
- "fill-color",
3279
- "Fill Color",
3280
- normalizeColor(fillColor || "#088")
3281
- );
3282
- const fillOpacity = this.map.getPaintProperty(layerId, "fill-opacity");
3283
- if (fillOpacity !== void 0 && typeof fillOpacity === "number") {
3284
- this.createSliderControl(
3285
- container,
3286
- layerId,
3287
- "fill-opacity",
3288
- "Fill Opacity",
3289
- fillOpacity,
3290
- 0,
3291
- 1,
3292
- 0.05
3293
- );
3294
- }
3295
- const outlineColor = this.map.getPaintProperty(
3296
- layerId,
3297
- "fill-outline-color"
3298
- );
3299
- if (outlineColor !== void 0) {
3300
- this.createColorControl(
3301
- container,
3302
- layerId,
3303
- "fill-outline-color",
3304
- "Outline Color",
3305
- normalizeColor(outlineColor)
3306
- );
3307
- }
3308
- }
3309
- /**
3310
- * Add controls for line layers
3311
- */
3312
- addLineControls(container, layerId) {
3313
- var _a;
3314
- const style = this.map.getStyle();
3315
- const layer = (_a = style.layers) == null ? void 0 : _a.find((l) => l.id === layerId);
3316
- let lineColor = void 0;
3317
- if (layer && "paint" in layer && layer.paint && "line-color" in layer.paint) {
3318
- lineColor = layer.paint["line-color"];
3319
- }
3320
- if (!lineColor) {
3321
- lineColor = this.map.getPaintProperty(layerId, "line-color");
3322
- }
3323
- this.createColorControl(
3324
- container,
3325
- layerId,
3326
- "line-color",
3327
- "Line Color",
3328
- normalizeColor(lineColor || "#000")
3329
- );
3330
- const lineWidth = this.map.getPaintProperty(layerId, "line-width");
3331
- this.createSliderControl(
3332
- container,
3333
- layerId,
3334
- "line-width",
3335
- "Line Width",
3336
- typeof lineWidth === "number" ? lineWidth : 1,
3337
- 0,
3338
- 20,
3339
- 0.5
3340
- );
3341
- const lineOpacity = this.map.getPaintProperty(layerId, "line-opacity");
3342
- if (lineOpacity !== void 0 && typeof lineOpacity === "number") {
3343
- this.createSliderControl(
3344
- container,
3345
- layerId,
3346
- "line-opacity",
3347
- "Line Opacity",
3348
- lineOpacity,
3349
- 0,
3350
- 1,
3351
- 0.05
3352
- );
3353
- }
3354
- const lineBlur = this.map.getPaintProperty(layerId, "line-blur");
3355
- if (lineBlur !== void 0 && typeof lineBlur === "number") {
3356
- this.createSliderControl(
3357
- container,
3358
- layerId,
3359
- "line-blur",
3360
- "Line Blur",
3361
- lineBlur,
3362
- 0,
3363
- 5,
3364
- 0.1
3365
- );
3366
- }
3367
- }
3368
- /**
3369
- * Add controls for circle layers
3370
- */
3371
- addCircleControls(container, layerId) {
3372
- var _a;
3373
- const style = this.map.getStyle();
3374
- const layer = (_a = style.layers) == null ? void 0 : _a.find((l) => l.id === layerId);
3375
- let circleColor = void 0;
3376
- if (layer && "paint" in layer && layer.paint && "circle-color" in layer.paint) {
3377
- circleColor = layer.paint["circle-color"];
3378
- }
3379
- if (!circleColor) {
3380
- circleColor = this.map.getPaintProperty(layerId, "circle-color");
3381
- }
3382
- this.createColorControl(
3383
- container,
3384
- layerId,
3385
- "circle-color",
3386
- "Circle Color",
3387
- normalizeColor(circleColor || "#000")
3388
- );
3389
- const circleRadius = this.map.getPaintProperty(layerId, "circle-radius");
3390
- this.createSliderControl(
3391
- container,
3392
- layerId,
3393
- "circle-radius",
3394
- "Radius",
3395
- typeof circleRadius === "number" ? circleRadius : 5,
3396
- 0,
3397
- 40,
3398
- 0.5
3399
- );
3400
- const circleOpacity = this.map.getPaintProperty(layerId, "circle-opacity");
3401
- if (circleOpacity !== void 0 && typeof circleOpacity === "number") {
3402
- this.createSliderControl(
3403
- container,
3404
- layerId,
3405
- "circle-opacity",
3406
- "Opacity",
3407
- circleOpacity,
3408
- 0,
3409
- 1,
3410
- 0.05
3411
- );
3412
- }
3413
- const strokeColor = this.map.getPaintProperty(
3414
- layerId,
3415
- "circle-stroke-color"
3416
- );
3417
- if (strokeColor !== void 0) {
3418
- this.createColorControl(
3419
- container,
3420
- layerId,
3421
- "circle-stroke-color",
3422
- "Stroke Color",
3423
- normalizeColor(strokeColor)
3424
- );
3425
- }
3426
- const strokeWidth = this.map.getPaintProperty(
3427
- layerId,
3428
- "circle-stroke-width"
3429
- );
3430
- if (strokeWidth !== void 0 && typeof strokeWidth === "number") {
3431
- this.createSliderControl(
3432
- container,
3433
- layerId,
3434
- "circle-stroke-width",
3435
- "Stroke Width",
3436
- strokeWidth,
3437
- 0,
3438
- 10,
3439
- 0.1
3440
- );
3441
- }
3442
- }
3443
- /**
3444
- * Add controls for raster layers
3445
- */
3446
- addRasterControls(container, layerId) {
3447
- const rasterOpacity = this.map.getPaintProperty(layerId, "raster-opacity");
3448
- this.createSliderControl(
3449
- container,
3450
- layerId,
3451
- "raster-opacity",
3452
- "Opacity",
3453
- typeof rasterOpacity === "number" ? rasterOpacity : 1,
3454
- 0,
3455
- 1,
3456
- 0.05
3457
- );
3458
- const brightnessMin = this.map.getPaintProperty(
3459
- layerId,
3460
- "raster-brightness-min"
3461
- );
3462
- this.createSliderControl(
3463
- container,
3464
- layerId,
3465
- "raster-brightness-min",
3466
- "Brightness Min",
3467
- typeof brightnessMin === "number" ? brightnessMin : 0,
3468
- -1,
3469
- 1,
3470
- 0.05
3471
- );
3472
- const brightnessMax = this.map.getPaintProperty(
3473
- layerId,
3474
- "raster-brightness-max"
3475
- );
3476
- this.createSliderControl(
3477
- container,
3478
- layerId,
3479
- "raster-brightness-max",
3480
- "Brightness Max",
3481
- typeof brightnessMax === "number" ? brightnessMax : 1,
3482
- -1,
3483
- 1,
3484
- 0.05
3485
- );
3486
- const saturation = this.map.getPaintProperty(layerId, "raster-saturation");
3487
- this.createSliderControl(
3488
- container,
3489
- layerId,
3490
- "raster-saturation",
3491
- "Saturation",
3492
- typeof saturation === "number" ? saturation : 0,
3493
- -1,
3494
- 1,
3495
- 0.05
3496
- );
3497
- const contrast = this.map.getPaintProperty(layerId, "raster-contrast");
3498
- this.createSliderControl(
3499
- container,
3500
- layerId,
3501
- "raster-contrast",
3502
- "Contrast",
3503
- typeof contrast === "number" ? contrast : 0,
3504
- -1,
3505
- 1,
3506
- 0.05
3507
- );
3508
- const hueRotate = this.map.getPaintProperty(layerId, "raster-hue-rotate");
3509
- this.createSliderControl(
3510
- container,
3511
- layerId,
3512
- "raster-hue-rotate",
3513
- "Hue Rotate",
3514
- typeof hueRotate === "number" ? hueRotate : 0,
3515
- 0,
3516
- 350,
3517
- 5
3518
- );
3519
- }
3520
- /**
3521
- * Add controls for symbol layers
3522
- */
3523
- addSymbolControls(container, layerId) {
3524
- const textColor = this.map.getPaintProperty(layerId, "text-color");
3525
- if (textColor !== void 0) {
3526
- this.createColorControl(
3527
- container,
3528
- layerId,
3529
- "text-color",
3530
- "Text Color",
3531
- normalizeColor(textColor)
3532
- );
3533
- }
3534
- const textOpacity = this.map.getPaintProperty(layerId, "text-opacity");
3535
- if (textOpacity !== void 0 && typeof textOpacity === "number") {
3536
- this.createSliderControl(
3537
- container,
3538
- layerId,
3539
- "text-opacity",
3540
- "Text Opacity",
3541
- textOpacity,
3542
- 0,
3543
- 1,
3544
- 0.05
3545
- );
3546
- }
3547
- const iconOpacity = this.map.getPaintProperty(layerId, "icon-opacity");
3548
- if (iconOpacity !== void 0 && typeof iconOpacity === "number") {
3549
- this.createSliderControl(
3550
- container,
3551
- layerId,
3552
- "icon-opacity",
3553
- "Icon Opacity",
3554
- iconOpacity,
3555
- 0,
3556
- 1,
3557
- 0.05
3558
- );
3559
- }
3560
- }
3561
- /**
3562
- * Notify the host that a paint property changed through the style editor.
3563
- * Reports the layer the active style editor belongs to (`activeStyleEditor`),
3564
- * not the internal native sub-layer id a control may edit, so consumers can
3565
- * map the change back to their own layer model.
3566
- */
3567
- notifyLayerStyleChange(property, value) {
3568
- const layerId = this.state.activeStyleEditor;
3569
- if (layerId && this.onLayerStyleChange) {
3570
- this.onLayerStyleChange(layerId, property, value);
3571
- }
3572
- }
3573
- /**
3574
- * Re-read an open style editor's controls from the current map paint so they
3575
- * reflect changes made elsewhere (e.g. an external sidebar writing the same
3576
- * paint properties). Setting input `.value` programmatically does not
3577
- * dispatch an `input` event, so this never re-triggers
3578
- * {@link LayerControlOptions.onLayerStyleChange}. The control the user is
3579
- * actively dragging (the focused input) is left untouched so the refresh
3580
- * does not fight an in-progress drag.
3581
- *
3582
- * @param layerId Restrict the refresh to one layer's editor. Defaults to the
3583
- * currently active editor. No-op when that editor is not open.
3584
- */
3585
- refreshStyleEditor(layerId) {
3586
- const targetId = layerId ?? this.state.activeStyleEditor;
3587
- if (!targetId) return;
3588
- const editor = this.styleEditors.get(targetId);
3589
- if (editor) {
3590
- this.syncStyleEditorControlsFromMap(editor);
3591
- }
3592
- }
3593
- /**
3594
- * Update every slider/color control in a style editor from the layer's
3595
- * current map paint. Each control records the layer it reads from in
3596
- * `dataset.layerId` (see createSliderControl/createColorControl).
3597
- */
3598
- syncStyleEditorControlsFromMap(editor) {
3599
- const active = document.activeElement;
3600
- const sliders = editor.querySelectorAll(
3601
- ".style-control-slider"
3602
- );
3603
- sliders.forEach((slider) => {
3604
- var _a;
3605
- if (slider === active) return;
3606
- const property = slider.dataset.property;
3607
- const sourceId = slider.dataset.layerId;
3608
- if (!property || !sourceId) return;
3609
- const value = this.map.getPaintProperty(sourceId, property);
3610
- if (typeof value === "number") {
3611
- slider.value = String(value);
3612
- const valueDisplay = (_a = slider.parentElement) == null ? void 0 : _a.querySelector(
3613
- ".style-control-value"
3614
- );
3615
- if (valueDisplay) {
3616
- const step = parseFloat(slider.step);
3617
- valueDisplay.textContent = formatNumericValue(value, step);
3618
- }
3619
- }
3620
- });
3621
- const colorPickers = editor.querySelectorAll(
3622
- ".style-control-color-picker"
3623
- );
3624
- colorPickers.forEach((picker) => {
3625
- var _a;
3626
- if (picker === active) return;
3627
- const property = picker.dataset.property;
3628
- const sourceId = picker.dataset.layerId;
3629
- if (!property || !sourceId) return;
3630
- const value = this.map.getPaintProperty(sourceId, property);
3631
- if (value !== void 0) {
3632
- const hexColor = normalizeColor(value);
3633
- picker.value = hexColor;
3634
- const hexDisplay = (_a = picker.parentElement) == null ? void 0 : _a.querySelector(
3635
- ".style-control-color-value"
3636
- );
3637
- if (hexDisplay) hexDisplay.value = hexColor;
3638
- }
3639
- });
3640
- }
3641
- /**
3642
- * Create a color control
3643
- */
3644
- createColorControl(container, layerId, property, label, initialValue) {
3645
- const controlGroup = document.createElement("div");
3646
- controlGroup.className = "style-control-group";
3647
- const labelEl = document.createElement("label");
3648
- labelEl.className = "style-control-label";
3649
- labelEl.textContent = label;
3650
- const inputWrapper = document.createElement("div");
3651
- inputWrapper.className = "style-control-color-group";
3652
- const colorInput = document.createElement("input");
3653
- colorInput.type = "color";
3654
- colorInput.className = "style-control-color-picker";
3655
- colorInput.value = initialValue;
3656
- colorInput.dataset.property = property;
3657
- colorInput.dataset.layerId = layerId;
3658
- const hexDisplay = document.createElement("input");
3659
- hexDisplay.type = "text";
3660
- hexDisplay.className = "style-control-color-value";
3661
- hexDisplay.value = initialValue;
3662
- hexDisplay.readOnly = true;
3663
- colorInput.addEventListener("input", () => {
3664
- const color = colorInput.value;
3665
- hexDisplay.value = color;
3666
- const targetIds = this.nativeLayerGroups.get(layerId) || [layerId];
3667
- for (const id of targetIds) {
3668
- this.map.setPaintProperty(id, property, color);
3669
- }
3670
- this.notifyLayerStyleChange(property, color);
3671
- });
3672
- inputWrapper.appendChild(colorInput);
3673
- inputWrapper.appendChild(hexDisplay);
3674
- controlGroup.appendChild(labelEl);
3675
- controlGroup.appendChild(inputWrapper);
3676
- container.appendChild(controlGroup);
3677
- }
3678
- /**
3679
- * Create a slider control
3680
- */
3681
- createSliderControl(container, layerId, property, label, initialValue, min, max, step) {
3682
- const controlGroup = document.createElement("div");
3683
- controlGroup.className = "style-control-group";
3684
- const labelEl = document.createElement("label");
3685
- labelEl.className = "style-control-label";
3686
- labelEl.textContent = label;
3687
- const inputWrapper = document.createElement("div");
3688
- inputWrapper.className = "style-control-input-wrapper";
3689
- const slider = document.createElement("input");
3690
- slider.type = "range";
3691
- slider.className = "style-control-slider";
3692
- slider.min = String(min);
3693
- slider.max = String(max);
3694
- slider.step = String(step);
3695
- slider.value = String(initialValue);
3696
- slider.dataset.property = property;
3697
- slider.dataset.layerId = layerId;
3698
- const valueDisplay = document.createElement("span");
3699
- valueDisplay.className = "style-control-value";
3700
- valueDisplay.textContent = formatNumericValue(initialValue, step);
3701
- slider.addEventListener("input", () => {
3702
- const value = parseFloat(slider.value);
3703
- valueDisplay.textContent = formatNumericValue(value, step);
3704
- const targetIds = this.nativeLayerGroups.get(layerId) || [layerId];
3705
- for (const id of targetIds) {
3706
- this.map.setPaintProperty(id, property, value);
3707
- }
3708
- this.notifyLayerStyleChange(property, value);
3709
- });
3710
- inputWrapper.appendChild(slider);
3711
- inputWrapper.appendChild(valueDisplay);
3712
- controlGroup.appendChild(labelEl);
3713
- controlGroup.appendChild(inputWrapper);
3714
- container.appendChild(controlGroup);
3715
- }
3716
- /**
3717
- * Reset layer style to original
3718
- */
3719
- resetLayerStyle(layerId) {
3720
- const originalStyle = this.state.originalStyles.get(layerId);
3721
- if (!originalStyle) return;
3722
- restoreOriginalStyle(this.map, layerId, this.state.originalStyles);
3723
- const editor = this.styleEditors.get(layerId);
3724
- if (editor) {
3725
- const sliders = editor.querySelectorAll(
3726
- ".style-control-slider"
3727
- );
3728
- sliders.forEach((slider) => {
3729
- var _a;
3730
- const property = slider.dataset.property;
3731
- if (property) {
3732
- const value = this.map.getPaintProperty(layerId, property);
3733
- if (value !== void 0 && typeof value === "number") {
3734
- slider.value = String(value);
3735
- const valueDisplay = (_a = slider.parentElement) == null ? void 0 : _a.querySelector(
3736
- ".style-control-value"
3737
- );
3738
- if (valueDisplay) {
3739
- const step = parseFloat(slider.step);
3740
- valueDisplay.textContent = formatNumericValue(value, step);
3741
- }
3742
- this.notifyLayerStyleChange(property, value);
3743
- }
3744
- }
3745
- });
3746
- const colorPickers = editor.querySelectorAll(
3747
- ".style-control-color-picker"
3748
- );
3749
- colorPickers.forEach((picker) => {
3750
- var _a;
3751
- const property = picker.dataset.property;
3752
- if (property) {
3753
- const value = this.map.getPaintProperty(layerId, property);
3754
- if (value !== void 0) {
3755
- const hexColor = normalizeColor(value);
3756
- picker.value = hexColor;
3757
- const hexDisplay = (_a = picker.parentElement) == null ? void 0 : _a.querySelector(
3758
- ".style-control-color-value"
3759
- );
3760
- if (hexDisplay) {
3761
- hexDisplay.value = hexColor;
3762
- }
3763
- this.notifyLayerStyleChange(property, hexColor);
3764
- }
3765
- }
3766
- });
3767
- }
3768
- }
3769
- /**
3770
- * Update layer states from map (sync UI with map)
3771
- */
3772
- updateLayerStatesFromMap() {
3773
- if (this.state.userInteractingWithSlider) {
3774
- return;
3775
- }
3776
- Object.keys(this.state.layerStates).forEach((layerId) => {
3777
- var _a;
3778
- try {
3779
- if ((_a = this.state.layerStates[layerId]) == null ? void 0 : _a.isCustomLayer) {
3780
- return;
3781
- }
3782
- if (layerId === "Background") {
3783
- return;
3784
- }
3785
- const layer = this.map.getLayer(layerId);
3786
- if (!layer) return;
3787
- const visibility = this.map.getLayoutProperty(layerId, "visibility");
3788
- const isVisible = visibility !== "none";
3789
- const layerType = layer.type;
3790
- const opacity = getLayerOpacity(this.map, layerId, layerType);
3791
- if (this.state.layerStates[layerId]) {
3792
- this.state.layerStates[layerId].visible = isVisible;
3793
- this.state.layerStates[layerId].opacity = opacity;
3794
- }
3795
- this.updateUIForLayer(layerId, isVisible, opacity);
3796
- } catch (error) {
3797
- console.warn(`Failed to update state for layer ${layerId}:`, error);
3798
- }
3799
- });
3800
- }
3801
- /**
3802
- * Update UI elements for a specific layer
3803
- */
3804
- updateUIForLayer(layerId, visible, opacity) {
3805
- const layerItems = this.panel.querySelectorAll(".layer-control-item");
3806
- layerItems.forEach((item) => {
3807
- if (item.dataset.layerId === layerId) {
3808
- const checkbox = item.querySelector(
3809
- ".layer-control-checkbox"
3810
- );
3811
- const opacitySlider = item.querySelector(
3812
- ".layer-control-opacity"
3813
- );
3814
- if (checkbox) {
3815
- checkbox.checked = visible;
3816
- }
3817
- if (opacitySlider) {
3818
- opacitySlider.value = String(opacity);
3819
- opacitySlider.title = `Opacity: ${Math.round(opacity * 100)}%`;
3820
- }
3821
- }
3822
- });
3823
- }
3824
- /**
3825
- * Check for new layers and add them to the control, remove deleted layers
3826
- */
3827
- checkForNewLayers() {
3828
- if (this.state.isStyleOperationInProgress) {
3829
- return;
3830
- }
3831
- try {
3832
- const style = this.map.getStyle();
3833
- if (!style || !style.layers) {
3834
- return;
3835
- }
3836
- const currentMapLayerIds = new Set(style.layers.map((layer) => layer.id));
3837
- const isAutoDetectMode = this.targetLayers.length === 0 || this.targetLayers.length === 1 && this.targetLayers[0] === "Background" || this.targetLayers.every(
3838
- (id) => id === "Background" || this.state.layerStates[id]
3839
- );
3840
- let layersAdded = false;
3841
- const newLayers = [];
3842
- const useBasemapStyleDetection = this.basemapLayerIds !== null && this.basemapLayerIds.size > 0;
3843
- const useInitialLayerDetection = !useBasemapStyleDetection && this.initialLayerIds !== null && this.initialLayerIds.size > 0;
3844
- currentMapLayerIds.forEach((layerId) => {
3845
- if (layerId !== "Background" && !this.state.layerStates[layerId]) {
3846
- const layer = this.map.getLayer(layerId);
3847
- if (layer) {
3848
- if (this.initialLayerIds !== null && this.initialLayerIds.has(layerId)) {
3849
- return;
3850
- }
3851
- if (isAutoDetectMode) {
3852
- if (this.excludeDrawnLayers && this.isDrawnLayer(layerId)) {
3853
- return;
3854
- }
3855
- if (this.isExcludedByPattern(layerId)) {
3856
- return;
3857
- }
3858
- if (!this.isUserAddedLayer(layerId)) {
3859
- return;
3860
- }
3861
- if (useBasemapStyleDetection) {
3862
- if (this.basemapLayerIds.has(layerId)) {
3863
- return;
3864
- }
3865
- } else if (useInitialLayerDetection) {
3866
- if (this.initialLayerIds.has(layerId)) {
3867
- const userAddedSourceIds = this.detectUserAddedSources();
3868
- const sourceId = layer.source;
3869
- if (!sourceId || !userAddedSourceIds.has(sourceId)) {
3870
- return;
3871
- }
3872
- }
3873
- } else {
3874
- const userAddedSourceIds = this.detectUserAddedSources();
3875
- const sourceId = layer.source;
3876
- if (!sourceId || !userAddedSourceIds.has(sourceId)) {
3877
- return;
3878
- }
3879
- }
3880
- }
3881
- newLayers.push(layerId);
3882
- }
3883
- }
3884
- });
3885
- const removedLayers = [];
3886
- Object.keys(this.state.layerStates).forEach((layerId) => {
3887
- const state = this.state.layerStates[layerId];
3888
- if (layerId !== "Background" && !state.isCustomLayer && !currentMapLayerIds.has(layerId)) {
3889
- removedLayers.push(layerId);
3890
- }
3891
- });
3892
- if (removedLayers.length > 0) {
3893
- removedLayers.forEach((layerId) => {
3894
- delete this.state.layerStates[layerId];
3895
- const itemEl = this.panel.querySelector(
3896
- `[data-layer-id="${layerId}"]`
3897
- );
3898
- if (itemEl) {
3899
- itemEl.remove();
3900
- }
3901
- if (this.state.activeStyleEditor === layerId) {
3902
- this.state.activeStyleEditor = null;
3903
- }
3904
- this.styleEditors.delete(layerId);
3905
- });
3906
- }
3907
- if (newLayers.length > 0) {
3908
- newLayers.forEach((layerId) => {
3909
- const layer = this.map.getLayer(layerId);
3910
- if (!layer) return;
3911
- const layerType = layer.type;
3912
- const opacity = getLayerOpacity(this.map, layerId, layerType);
3913
- const visibility = this.map.getLayoutProperty(layerId, "visibility");
3914
- const isVisible = visibility !== "none";
3915
- this.state.layerStates[layerId] = {
3916
- visible: isVisible,
3917
- opacity,
3918
- name: this.generateFriendlyName(layerId)
3919
- };
3920
- if (this.targetLayers.length > 0 && !this.targetLayers.includes(layerId)) {
3921
- this.targetLayers.push(layerId);
3922
- }
3923
- layersAdded = true;
3924
- });
3925
- }
3926
- if (this.customLayerRegistry) {
3927
- const customLayerIds = this.customLayerRegistry.getAllLayerIds();
3928
- customLayerIds.forEach((layerId) => {
3929
- if (!this.state.layerStates[layerId] && !this.removedCustomLayerIds.has(layerId)) {
3930
- const customState = this.customLayerRegistry.getLayerState(layerId);
3931
- if (customState) {
3932
- this.state.layerStates[layerId] = {
3933
- visible: customState.visible,
3934
- opacity: customState.opacity,
3935
- name: customState.name,
3936
- isCustomLayer: true,
3937
- customLayerType: this.customLayerRegistry.getSymbolType(layerId) || void 0
3938
- };
3939
- if (this.targetLayers.length > 0 && !this.targetLayers.includes(layerId)) {
3940
- this.targetLayers.push(layerId);
3941
- }
3942
- layersAdded = true;
3943
- }
3944
- }
3945
- });
3946
- Object.keys(this.state.layerStates).forEach((layerId) => {
3947
- const state = this.state.layerStates[layerId];
3948
- if (state.isCustomLayer && !customLayerIds.includes(layerId)) {
3949
- delete this.state.layerStates[layerId];
3950
- const itemEl = this.panel.querySelector(
3951
- `[data-layer-id="${layerId}"]`
3952
- );
3953
- if (itemEl) {
3954
- itemEl.remove();
3955
- }
3956
- if (this.state.activeStyleEditor === layerId) {
3957
- this.state.activeStyleEditor = null;
3958
- }
3959
- this.styleEditors.delete(layerId);
3960
- }
3961
- });
3962
- }
3963
- if (layersAdded) {
3964
- this.buildLayerItems();
3965
- } else {
3966
- this.pruneEmptyGroups();
3967
- }
3968
- } catch (error) {
3969
- console.warn("Failed to check for new layers:", error);
3970
- }
3971
- }
3972
- /**
3973
- * Register a custom layer adapter dynamically.
3974
- * This allows adding adapters after the LayerControl has been initialized.
3975
- * @param adapter The custom layer adapter to register
3976
- */
3977
- registerCustomAdapter(adapter) {
3978
- if (!this.customLayerRegistry) {
3979
- this.customLayerRegistry = new CustomLayerRegistry();
3980
- this.customLayerUnsubscribe = this.customLayerRegistry.onChange(
3981
- (event, layerId) => {
3982
- if (event === "add" && layerId) {
3983
- this.removedCustomLayerIds.delete(layerId);
3984
- }
3985
- this.checkForNewLayers();
3986
- }
3987
- );
3988
- }
3989
- this.customLayerRegistry.register(adapter);
3990
- if (this.panel) {
3991
- this.checkForNewLayers();
3992
- }
3993
- }
3994
- // ===== Context Menu Methods =====
3995
- /**
3996
- * Create context menu element
3997
- */
3998
- createContextMenu() {
3999
- const menu = document.createElement("div");
4000
- menu.className = "layer-control-context-menu";
4001
- menu.style.display = "none";
4002
- const renameItem = this.createContextMenuItem("Rename", "✏️", () => {
4003
- if (this.state.contextMenu.targetLayerId) {
4004
- this.startRenaming(this.state.contextMenu.targetLayerId);
4005
- }
4006
- this.hideContextMenu();
4007
- });
4008
- const zoomItem = this.createContextMenuItem("Zoom to Layer", "🔍", () => {
4009
- if (this.state.contextMenu.targetLayerId) {
4010
- this.zoomToLayer(this.state.contextMenu.targetLayerId);
4011
- }
4012
- this.hideContextMenu();
4013
- });
4014
- const sep1 = document.createElement("div");
4015
- sep1.className = "context-menu-separator";
4016
- const moveUpItem = this.createContextMenuItem("Move Up", "↑", () => {
4017
- if (this.state.contextMenu.targetLayerId) {
4018
- this.moveLayerUp(this.state.contextMenu.targetLayerId);
4019
- }
4020
- this.hideContextMenu();
4021
- });
4022
- const moveTopItem = this.createContextMenuItem("Move to Top", "⤒", () => {
4023
- if (this.state.contextMenu.targetLayerId) {
4024
- this.moveLayerToTop(this.state.contextMenu.targetLayerId);
4025
- }
4026
- this.hideContextMenu();
4027
- });
4028
- const moveDownItem = this.createContextMenuItem("Move Down", "↓", () => {
4029
- if (this.state.contextMenu.targetLayerId) {
4030
- this.moveLayerDown(this.state.contextMenu.targetLayerId);
4031
- }
4032
- this.hideContextMenu();
4033
- });
4034
- const moveBottomItem = this.createContextMenuItem(
4035
- "Move to Bottom",
4036
- "⤓",
4037
- () => {
4038
- if (this.state.contextMenu.targetLayerId) {
4039
- this.moveLayerToBottom(this.state.contextMenu.targetLayerId);
4040
- }
4041
- this.hideContextMenu();
4042
- }
4043
- );
4044
- const sep2 = document.createElement("div");
4045
- sep2.className = "context-menu-separator";
4046
- const removeItem = this.createContextMenuItem(
4047
- "Remove Layer",
4048
- "🗑️",
4049
- () => {
4050
- if (this.state.contextMenu.targetLayerId) {
4051
- this.removeLayer(this.state.contextMenu.targetLayerId);
4052
- }
4053
- this.hideContextMenu();
4054
- },
4055
- true
4056
- );
4057
- menu.appendChild(renameItem);
4058
- menu.appendChild(zoomItem);
4059
- menu.appendChild(sep1);
4060
- menu.appendChild(moveUpItem);
4061
- menu.appendChild(moveTopItem);
4062
- menu.appendChild(moveDownItem);
4063
- menu.appendChild(moveBottomItem);
4064
- menu.appendChild(sep2);
4065
- menu.appendChild(removeItem);
4066
- return menu;
4067
- }
4068
- /**
4069
- * Create a context menu item
4070
- */
4071
- createContextMenuItem(label, icon, onClick, isDanger = false) {
4072
- const item = document.createElement("div");
4073
- item.className = "context-menu-item" + (isDanger ? " context-menu-item-danger" : "");
4074
- const iconEl = document.createElement("span");
4075
- iconEl.className = "context-menu-item-icon";
4076
- iconEl.textContent = icon;
4077
- const labelEl = document.createElement("span");
4078
- labelEl.className = "context-menu-item-label";
4079
- labelEl.textContent = label;
4080
- item.appendChild(iconEl);
4081
- item.appendChild(labelEl);
4082
- item.addEventListener("click", (e) => {
4083
- e.stopPropagation();
4084
- onClick();
4085
- });
4086
- return item;
4087
- }
4088
- /**
4089
- * Show context menu at position
4090
- */
4091
- showContextMenu(layerId, x, y) {
4092
- if (!this.contextMenuEl) return;
4093
- this.state.contextMenu = {
4094
- visible: true,
4095
- targetLayerId: layerId,
4096
- x,
4097
- y
4098
- };
4099
- const mapRect = this.mapContainer.getBoundingClientRect();
4100
- let menuX = x - mapRect.left;
4101
- let menuY = y - mapRect.top;
4102
- this.contextMenuEl.style.display = "block";
4103
- const menuRect = this.contextMenuEl.getBoundingClientRect();
4104
- if (menuX + menuRect.width > mapRect.width) {
4105
- menuX = mapRect.width - menuRect.width - 5;
4106
- }
4107
- if (menuY + menuRect.height > mapRect.height) {
4108
- menuY = mapRect.height - menuRect.height - 5;
4109
- }
4110
- this.contextMenuEl.style.left = `${menuX}px`;
4111
- this.contextMenuEl.style.top = `${menuY}px`;
4112
- }
4113
- /**
4114
- * Hide context menu
4115
- */
4116
- hideContextMenu() {
4117
- if (!this.contextMenuEl) return;
4118
- this.state.contextMenu = {
4119
- visible: false,
4120
- targetLayerId: null,
4121
- x: 0,
4122
- y: 0
4123
- };
4124
- this.contextMenuEl.style.display = "none";
4125
- }
4126
- /**
4127
- * Start renaming a layer
4128
- */
4129
- startRenaming(layerId) {
4130
- var _a;
4131
- const itemEl = this.panel.querySelector(`[data-layer-id="${layerId}"]`);
4132
- if (!itemEl) return;
4133
- const nameEl = itemEl.querySelector(".layer-control-name");
4134
- if (!nameEl) return;
4135
- this.state.renamingLayerId = layerId;
4136
- const currentName = this.state.customLayerNames.get(layerId) || ((_a = this.state.layerStates[layerId]) == null ? void 0 : _a.name) || layerId;
4137
- const input = document.createElement("input");
4138
- input.type = "text";
4139
- input.className = "layer-control-name-input";
4140
- input.value = currentName;
4141
- const finishRename = () => {
4142
- var _a2;
4143
- const newName = input.value.trim() || currentName;
4144
- const oldName = currentName;
4145
- if (newName !== oldName) {
4146
- this.state.customLayerNames.set(layerId, newName);
4147
- if (this.state.layerStates[layerId]) {
4148
- this.state.layerStates[layerId].name = newName;
4149
- }
4150
- (_a2 = this.onLayerRename) == null ? void 0 : _a2.call(this, layerId, oldName, newName);
4151
- }
4152
- const newNameEl = document.createElement("span");
4153
- newNameEl.className = "layer-control-name";
4154
- newNameEl.textContent = newName;
4155
- newNameEl.title = newName;
4156
- input.replaceWith(newNameEl);
4157
- this.state.renamingLayerId = null;
4158
- };
4159
- input.addEventListener("blur", finishRename);
4160
- input.addEventListener("keydown", (e) => {
4161
- if (e.key === "Enter") {
4162
- e.preventDefault();
4163
- finishRename();
4164
- } else if (e.key === "Escape") {
4165
- e.preventDefault();
4166
- const newNameEl = document.createElement("span");
4167
- newNameEl.className = "layer-control-name";
4168
- newNameEl.textContent = currentName;
4169
- newNameEl.title = currentName;
4170
- input.replaceWith(newNameEl);
4171
- this.state.renamingLayerId = null;
4172
- }
4173
- });
4174
- nameEl.replaceWith(input);
4175
- input.focus();
4176
- input.select();
4177
- }
4178
- /**
4179
- * Zoom to a layer's bounds
4180
- */
4181
- zoomToLayer(layerId) {
4182
- const layerState = this.state.layerStates[layerId];
4183
- if ((layerState == null ? void 0 : layerState.isCustomLayer) && this.customLayerRegistry) {
4184
- const bounds = this.customLayerRegistry.getBounds(layerId);
4185
- if (bounds) {
4186
- this.map.fitBounds(bounds, {
4187
- padding: 50
4188
- });
4189
- return;
4190
- }
4191
- }
4192
- const layer = this.map.getLayer(layerId);
4193
- if (!layer) return;
4194
- try {
4195
- const sourceId = layer.source;
4196
- let features = sourceId ? this.map.querySourceFeatures(sourceId) : [];
4197
- if (features.length === 0) {
4198
- features = this.map.queryRenderedFeatures({ layers: [layerId] });
4199
- }
4200
- if (features.length === 0) return;
4201
- let minLng = Infinity, minLat = Infinity, maxLng = -Infinity, maxLat = -Infinity;
4202
- features.forEach((feature) => {
4203
- if (!feature.geometry) return;
4204
- const processCoords = (coords) => {
4205
- if (typeof coords[0] === "number") {
4206
- const [lng, lat] = coords;
4207
- minLng = Math.min(minLng, lng);
4208
- minLat = Math.min(minLat, lat);
4209
- maxLng = Math.max(maxLng, lng);
4210
- maxLat = Math.max(maxLat, lat);
4211
- } else {
4212
- coords.forEach(processCoords);
4213
- }
4214
- };
4215
- if (feature.geometry.type === "Point") {
4216
- processCoords(feature.geometry.coordinates);
4217
- } else if (feature.geometry.type === "LineString" || feature.geometry.type === "MultiPoint") {
4218
- feature.geometry.coordinates.forEach(processCoords);
4219
- } else if (feature.geometry.type === "Polygon" || feature.geometry.type === "MultiLineString") {
4220
- feature.geometry.coordinates.forEach(
4221
- (ring) => ring.forEach(processCoords)
4222
- );
4223
- } else if (feature.geometry.type === "MultiPolygon") {
4224
- feature.geometry.coordinates.forEach(
4225
- (polygon) => polygon.forEach((ring) => ring.forEach(processCoords))
4226
- );
4227
- }
4228
- });
4229
- if (minLng !== Infinity && minLat !== Infinity && maxLng !== -Infinity && maxLat !== -Infinity) {
4230
- this.map.fitBounds(
4231
- [
4232
- [minLng, minLat],
4233
- [maxLng, maxLat]
4234
- ],
4235
- { padding: 50 }
4236
- );
4237
- }
4238
- } catch (error) {
4239
- console.warn(`Failed to zoom to layer ${layerId}:`, error);
4240
- }
4241
- }
4242
- /**
4243
- * Get user layer IDs in current map order (top to bottom in UI = high z-index to low)
4244
- * Includes both MapLibre layers and custom layers managed by adapters.
4245
- */
4246
- getUserLayerIdsInMapOrder() {
4247
- var _a;
4248
- const style = this.map.getStyle();
4249
- if (!(style == null ? void 0 : style.layers)) return [];
4250
- const mapLayerIds = style.layers.map((l) => l.id);
4251
- const indexById = new Map(mapLayerIds.map((id, i) => [id, i]));
4252
- const userLayerIds = Object.keys(this.state.layerStates).filter(
4253
- (id) => id !== "Background"
4254
- );
4255
- const resolvedIndexOf = (id) => {
4256
- var _a2;
4257
- const direct = indexById.get(id);
4258
- if (direct !== void 0) return direct;
4259
- const nativeIds = (_a2 = this.customLayerRegistry) == null ? void 0 : _a2.getNativeLayerIds(id);
4260
- if (nativeIds && nativeIds.length > 0) {
4261
- let best = -1;
4262
- for (const nativeId of nativeIds) {
4263
- const idx = indexById.get(nativeId);
4264
- if (idx !== void 0 && idx > best) best = idx;
4265
- }
4266
- if (best !== -1) return best;
4267
- }
4268
- return void 0;
4269
- };
4270
- const anchors = /* @__PURE__ */ new Map();
4271
- for (const group of ((_a = this.customLayerRegistry) == null ? void 0 : _a.getLayerIdGroups()) ?? []) {
4272
- const resolved = group.map(resolvedIndexOf);
4273
- const known = resolved.filter((idx) => idx !== void 0);
4274
- if (known.length === 0) continue;
4275
- const ids = known[0] > known[known.length - 1] ? [...group].reverse() : group;
4276
- const indexes = ids === group ? resolved : [...resolved].reverse();
4277
- ids.forEach((id, position) => {
4278
- if (indexes[position] !== void 0) return;
4279
- for (let below = position - 1; below >= 0; below--) {
4280
- const idx = indexes[below];
4281
- if (idx !== void 0) {
4282
- anchors.set(id, { mapIndex: idx, offset: position - below });
4283
- return;
4284
- }
4285
- }
4286
- for (let above = position + 1; above < ids.length; above++) {
4287
- const idx = indexes[above];
4288
- if (idx !== void 0) {
4289
- anchors.set(id, { mapIndex: idx, offset: position - above });
4290
- return;
4291
- }
4292
- }
4293
- });
4294
- }
4295
- const stackKeyOf = (id) => {
4296
- const resolved = resolvedIndexOf(id);
4297
- if (resolved !== void 0) return { mapIndex: resolved, offset: 0 };
4298
- return anchors.get(id) ?? { mapIndex: Number.POSITIVE_INFINITY, offset: 0 };
4299
- };
4300
- return userLayerIds.map((id, insertionIndex) => ({
4301
- id,
4302
- insertionIndex,
4303
- ...stackKeyOf(id)
4304
- })).sort((a, b) => {
4305
- if (a.mapIndex !== b.mapIndex) return a.mapIndex > b.mapIndex ? -1 : 1;
4306
- if (a.offset !== b.offset) return b.offset - a.offset;
4307
- return a.insertionIndex - b.insertionIndex;
4308
- }).map((entry) => entry.id);
4309
- }
4310
- /**
4311
- * Check if a layer is a MapLibre layer (not a custom layer)
4312
- */
4313
- isMapLibreLayer(layerId) {
4314
- return this.map.getLayer(layerId) !== void 0;
4315
- }
4316
- /**
4317
- * Find the next MapLibre layer ID in a direction from a given index
4318
- * @param layerIds Array of layer IDs
4319
- * @param startIndex Index to start searching from
4320
- * @param direction 1 for forward (toward bottom), -1 for backward (toward top)
4321
- * @returns MapLibre layer ID or undefined if not found
4322
- */
4323
- findNextMapLibreLayer(layerIds, startIndex, direction) {
4324
- for (let i = startIndex; direction === 1 ? i < layerIds.length : i >= 0; i += direction) {
4325
- if (this.isMapLibreLayer(layerIds[i])) {
4326
- return layerIds[i];
4327
- }
4328
- }
4329
- return void 0;
4330
- }
4331
- /**
4332
- * Move a layer up in UI (higher rendering order = move to higher z-index)
4333
- */
4334
- moveLayerUp(layerId) {
4335
- var _a, _b;
4336
- if (this.groupStates.size > 0) {
4337
- this.moveLayerWithinGroup(layerId, "up");
4338
- return;
4339
- }
4340
- const layerIds = this.getUserLayerIdsInMapOrder();
4341
- const index = layerIds.indexOf(layerId);
4342
- if (index <= 0) return;
4343
- const isCustom = (_a = this.state.layerStates[layerId]) == null ? void 0 : _a.isCustomLayer;
4344
- if (!isCustom && this.isMapLibreLayer(layerId)) {
4345
- try {
4346
- const targetBeforeId = index >= 2 ? this.findNextMapLibreLayer(layerIds, index - 2, -1) : void 0;
4347
- this.map.moveLayer(layerId, targetBeforeId);
4348
- } catch (e) {
4349
- }
4350
- }
4351
- const newLayerStates = {};
4352
- const orderedIds = [...layerIds];
4353
- [orderedIds[index], orderedIds[index - 1]] = [
4354
- orderedIds[index - 1],
4355
- orderedIds[index]
4356
- ];
4357
- if (this.state.layerStates["Background"]) {
4358
- newLayerStates["Background"] = this.state.layerStates["Background"];
4359
- }
4360
- orderedIds.forEach((id) => {
4361
- if (this.state.layerStates[id]) {
4362
- newLayerStates[id] = this.state.layerStates[id];
4363
- }
4364
- });
4365
- this.state.layerStates = newLayerStates;
4366
- this.buildLayerItems();
4367
- (_b = this.onLayerReorder) == null ? void 0 : _b.call(this, orderedIds);
4368
- }
4369
- /**
4370
- * Move a layer to the top (highest rendering order)
4371
- */
4372
- moveLayerToTop(layerId) {
4373
- var _a, _b;
4374
- if (this.groupStates.size > 0) {
4375
- this.moveLayerWithinGroup(layerId, "top");
4376
- return;
4377
- }
4378
- const layerIds = this.getUserLayerIdsInMapOrder();
4379
- const index = layerIds.indexOf(layerId);
4380
- if (index <= 0) return;
4381
- const isCustom = (_a = this.state.layerStates[layerId]) == null ? void 0 : _a.isCustomLayer;
4382
- if (!isCustom && this.isMapLibreLayer(layerId)) {
4383
- try {
4384
- this.map.moveLayer(layerId);
4385
- } catch (e) {
4386
- }
4387
- }
4388
- const newLayerStates = {};
4389
- const orderedIds = [...layerIds];
4390
- orderedIds.splice(index, 1);
4391
- orderedIds.unshift(layerId);
4392
- if (this.state.layerStates["Background"]) {
4393
- newLayerStates["Background"] = this.state.layerStates["Background"];
4394
- }
4395
- orderedIds.forEach((id) => {
4396
- if (this.state.layerStates[id]) {
4397
- newLayerStates[id] = this.state.layerStates[id];
4398
- }
4399
- });
4400
- this.state.layerStates = newLayerStates;
4401
- this.buildLayerItems();
4402
- (_b = this.onLayerReorder) == null ? void 0 : _b.call(this, orderedIds);
4403
- }
4404
- /**
4405
- * Move a layer down in UI (lower rendering order = move to lower z-index)
4406
- */
4407
- moveLayerDown(layerId) {
4408
- var _a, _b;
4409
- if (this.groupStates.size > 0) {
4410
- this.moveLayerWithinGroup(layerId, "down");
4411
- return;
4412
- }
4413
- const layerIds = this.getUserLayerIdsInMapOrder();
4414
- const index = layerIds.indexOf(layerId);
4415
- if (index < 0 || index >= layerIds.length - 1) return;
4416
- const isCustom = (_a = this.state.layerStates[layerId]) == null ? void 0 : _a.isCustomLayer;
4417
- if (!isCustom && this.isMapLibreLayer(layerId)) {
4418
- const belowLayerId = this.findNextMapLibreLayer(layerIds, index + 1, 1);
4419
- if (belowLayerId) {
4420
- try {
4421
- this.map.moveLayer(layerId, belowLayerId);
4422
- } catch (e) {
4423
- }
4424
- }
4425
- }
4426
- const newLayerStates = {};
4427
- const orderedIds = [...layerIds];
4428
- [orderedIds[index], orderedIds[index + 1]] = [
4429
- orderedIds[index + 1],
4430
- orderedIds[index]
4431
- ];
4432
- if (this.state.layerStates["Background"]) {
4433
- newLayerStates["Background"] = this.state.layerStates["Background"];
4434
- }
4435
- orderedIds.forEach((id) => {
4436
- if (this.state.layerStates[id]) {
4437
- newLayerStates[id] = this.state.layerStates[id];
4438
- }
4439
- });
4440
- this.state.layerStates = newLayerStates;
4441
- this.buildLayerItems();
4442
- (_b = this.onLayerReorder) == null ? void 0 : _b.call(this, orderedIds);
4443
- }
4444
- /**
4445
- * Move a layer to the bottom (lowest rendering order among user layers)
4446
- */
4447
- moveLayerToBottom(layerId) {
4448
- var _a, _b;
4449
- if (this.groupStates.size > 0) {
4450
- this.moveLayerWithinGroup(layerId, "bottom");
4451
- return;
4452
- }
4453
- const layerIds = this.getUserLayerIdsInMapOrder();
4454
- if (layerIds.length <= 1) return;
4455
- const index = layerIds.indexOf(layerId);
4456
- if (index < 0 || index === layerIds.length - 1) return;
4457
- const isCustom = (_a = this.state.layerStates[layerId]) == null ? void 0 : _a.isCustomLayer;
4458
- if (!isCustom && this.isMapLibreLayer(layerId)) {
4459
- const bottomLayerId = this.findNextMapLibreLayer(
4460
- layerIds,
4461
- layerIds.length - 1,
4462
- -1
4463
- );
4464
- if (bottomLayerId && bottomLayerId !== layerId) {
4465
- try {
4466
- this.map.moveLayer(layerId, bottomLayerId);
4467
- } catch (e) {
4468
- }
4469
- }
4470
- }
4471
- const newLayerStates = {};
4472
- const orderedIds = [...layerIds];
4473
- orderedIds.splice(index, 1);
4474
- orderedIds.push(layerId);
4475
- if (this.state.layerStates["Background"]) {
4476
- newLayerStates["Background"] = this.state.layerStates["Background"];
4477
- }
4478
- orderedIds.forEach((id) => {
4479
- if (this.state.layerStates[id]) {
4480
- newLayerStates[id] = this.state.layerStates[id];
4481
- }
4482
- });
4483
- this.state.layerStates = newLayerStates;
4484
- this.buildLayerItems();
4485
- (_b = this.onLayerReorder) == null ? void 0 : _b.call(this, orderedIds);
4486
- }
4487
- /**
4488
- * Move a layer within its own group (or among the top-level rows), so the
4489
- * context-menu moves never carry it out of its group. A nested group counts
4490
- * as one block: moving up or down steps past the whole block.
4491
- * @param layerId The layer ID
4492
- * @param direction Where to move the layer within its group
4493
- */
4494
- moveLayerWithinGroup(layerId, direction) {
4495
- var _a;
4496
- const order = this.getUserLayerIdsInMapOrder();
4497
- const groupId = this.getLayerGroupIdOf(layerId);
4498
- const blocks = [];
4499
- for (const id of order) {
4500
- const key = this.getChildKeyWithin(id, groupId);
4501
- if (key === null) continue;
4502
- const lastBlock = blocks[blocks.length - 1];
4503
- if (lastBlock && lastBlock.key === key && key !== `layer:${id}`) {
4504
- lastBlock.ids.push(id);
4505
- } else {
4506
- blocks.push({ key, ids: [id] });
4507
- }
4508
- }
4509
- const position = blocks.findIndex((block2) => block2.key === `layer:${layerId}`);
4510
- const last = blocks.length - 1;
4511
- if (position < 0) return;
4512
- if ((direction === "up" || direction === "top") && position === 0) return;
4513
- if ((direction === "down" || direction === "bottom") && position === last) {
4514
- return;
4515
- }
4516
- const above = direction === "up" || direction === "top";
4517
- const block = {
4518
- up: blocks[position - 1],
4519
- top: blocks[0],
4520
- down: blocks[position + 1],
4521
- bottom: blocks[last]
4522
- }[direction];
4523
- const anchor = above ? block.ids[0] : block.ids[block.ids.length - 1];
4524
- const next = order.filter((id) => id !== layerId);
4525
- const anchorIndex = next.indexOf(anchor);
4526
- next.splice(above ? anchorIndex : anchorIndex + 1, 0, layerId);
4527
- const newLayerStates = {};
4528
- if (this.state.layerStates["Background"]) {
4529
- newLayerStates["Background"] = this.state.layerStates["Background"];
4530
- }
4531
- next.forEach((id) => {
4532
- if (this.state.layerStates[id]) {
4533
- newLayerStates[id] = this.state.layerStates[id];
4534
- }
4535
- });
4536
- this.state.layerStates = newLayerStates;
4537
- this.applyLayerOrderToMap(next);
4538
- this.buildLayerItems();
4539
- (_a = this.onLayerReorder) == null ? void 0 : _a.call(this, next);
4540
- }
4541
- /**
4542
- * Identify which row of a group a layer falls under: the layer itself when
4543
- * it belongs to the group directly, or the nested group that holds it.
4544
- * @param layerId The layer ID
4545
- * @param groupId The group, or undefined for the panel's top level
4546
- * @returns `layer:<id>` or `group:<id>`, or null when the layer is not
4547
- * inside the group at all
4548
- */
4549
- getChildKeyWithin(layerId, groupId) {
4550
- var _a;
4551
- let current = this.getLayerGroupIdOf(layerId);
4552
- if (current === groupId) return `layer:${layerId}`;
4553
- const visited = /* @__PURE__ */ new Set();
4554
- while (current !== void 0 && !visited.has(current)) {
4555
- visited.add(current);
4556
- const parentId = (_a = this.groupStates.get(current)) == null ? void 0 : _a.parentId;
4557
- const parent = parentId !== void 0 && this.groupStates.has(parentId) ? parentId : void 0;
4558
- if (parent === groupId) return `group:${current}`;
4559
- current = parent;
4560
- }
4561
- return null;
4562
- }
4563
- /**
4564
- * Show inline remove confirmation instead of browser confirm() dialog.
4565
- * Works in Jupyter notebooks where native dialogs may not appear.
4566
- */
4567
- showRemoveConfirmation(container, onConfirm) {
4568
- const existing = container.querySelector(".layer-control-remove-confirm");
4569
- if (existing) {
4570
- existing.remove();
4571
- }
4572
- const confirmEl = document.createElement("div");
4573
- confirmEl.className = "layer-control-remove-confirm";
4574
- const message = document.createElement("div");
4575
- message.className = "layer-control-remove-confirm-message";
4576
- message.innerHTML = `
4577
- <svg class="layer-control-remove-confirm-icon" viewBox="0 0 20 20" fill="currentColor">
4578
- <path fill-rule="evenodd" d="M8.485 2.495c.673-1.167 2.357-1.167 3.03 0l6.28 10.875c.673 1.167-.17 2.625-1.516 2.625H3.72c-1.347 0-2.189-1.458-1.515-2.625L8.485 2.495zM10 5a.75.75 0 01.75.75v3.5a.75.75 0 01-1.5 0v-3.5A.75.75 0 0110 5zm0 9a1 1 0 100-2 1 1 0 000 2z" clip-rule="evenodd"/>
4579
- </svg>
4580
- <span>Remove this layer?</span>
4581
- `;
4582
- const buttons = document.createElement("div");
4583
- buttons.className = "layer-control-remove-confirm-buttons";
4584
- const cancelBtn = document.createElement("button");
4585
- cancelBtn.className = "layer-control-remove-confirm-btn layer-control-remove-confirm-btn-cancel";
4586
- cancelBtn.textContent = "Cancel";
4587
- cancelBtn.addEventListener("click", (e) => {
4588
- e.stopPropagation();
4589
- confirmEl.remove();
4590
- });
4591
- const confirmBtn = document.createElement("button");
4592
- confirmBtn.className = "layer-control-remove-confirm-btn layer-control-remove-confirm-btn-confirm";
4593
- confirmBtn.textContent = "Remove";
4594
- confirmBtn.addEventListener("click", (e) => {
4595
- e.stopPropagation();
4596
- confirmEl.remove();
4597
- onConfirm();
4598
- });
4599
- buttons.appendChild(cancelBtn);
4600
- buttons.appendChild(confirmBtn);
4601
- confirmEl.appendChild(message);
4602
- confirmEl.appendChild(buttons);
4603
- container.appendChild(confirmEl);
4604
- requestAnimationFrame(() => {
4605
- confirmEl.scrollIntoView({ behavior: "smooth", block: "nearest" });
4606
- });
4607
- }
4608
- /**
4609
- * Remove a layer from the map
4610
- */
4611
- removeLayer(layerId) {
4612
- var _a, _b;
4613
- this.state.isStyleOperationInProgress = true;
4614
- const layerState = this.state.layerStates[layerId];
4615
- if ((layerState == null ? void 0 : layerState.isCustomLayer) && this.customLayerRegistry) {
4616
- this.removedCustomLayerIds.add(layerId);
4617
- this.customLayerRegistry.setVisibility(layerId, false);
4618
- this.customLayerRegistry.removeLayer(layerId);
4619
- }
4620
- try {
4621
- const layer = this.map.getLayer(layerId);
4622
- if (layer) {
4623
- const sourceId = layer.source;
4624
- this.map.removeLayer(layerId);
4625
- if (sourceId) {
4626
- const style = this.map.getStyle();
4627
- const sourceStillUsed = (_a = style == null ? void 0 : style.layers) == null ? void 0 : _a.some(
4628
- (l) => l.source === sourceId
4629
- );
4630
- if (!sourceStillUsed) {
4631
- try {
4632
- this.map.removeSource(sourceId);
4633
- } catch (e) {
4634
- }
4635
- }
4636
- }
4637
- }
4638
- } catch (error) {
4639
- console.warn(`Failed to remove layer ${layerId}:`, error);
4640
- }
4641
- delete this.state.layerStates[layerId];
4642
- this.state.customLayerNames.delete(layerId);
4643
- const itemEl = this.panel.querySelector(`[data-layer-id="${layerId}"]`);
4644
- if (itemEl) {
4645
- itemEl.remove();
4646
- }
4647
- this.pruneEmptyGroups();
4648
- (_b = this.onLayerRemove) == null ? void 0 : _b.call(this, layerId);
4649
- setTimeout(() => {
4650
- this.state.isStyleOperationInProgress = false;
4651
- }, 200);
4652
- }
4653
- // ===== Drag and Drop Methods =====
4654
- /**
4655
- * Create drag handle element
4656
- */
4657
- createDragHandle(layerId) {
4658
- const handle = document.createElement("div");
4659
- handle.className = "layer-control-drag-handle";
4660
- handle.innerHTML = `<svg viewBox="0 0 16 16" fill="currentColor">
4661
- <circle cx="5" cy="3" r="1.5"/>
4662
- <circle cx="11" cy="3" r="1.5"/>
4663
- <circle cx="5" cy="8" r="1.5"/>
4664
- <circle cx="11" cy="8" r="1.5"/>
4665
- <circle cx="5" cy="13" r="1.5"/>
4666
- <circle cx="11" cy="13" r="1.5"/>
4667
- </svg>`;
4668
- handle.title = "Drag to reorder";
4669
- handle.addEventListener("pointerdown", (e) => {
4670
- e.preventDefault();
4671
- e.stopPropagation();
4672
- this.startDrag(layerId, e);
4673
- });
4674
- return handle;
4675
- }
4676
- /**
4677
- * Create a disabled drag handle for alignment (used for Background layer)
4678
- */
4679
- createDisabledDragHandle() {
4680
- const handle = document.createElement("div");
4681
- handle.className = "layer-control-drag-handle layer-control-drag-handle-disabled";
4682
- handle.innerHTML = `<svg viewBox="0 0 16 16" fill="currentColor">
4683
- <circle cx="5" cy="3" r="1.5"/>
4684
- <circle cx="11" cy="3" r="1.5"/>
4685
- <circle cx="5" cy="8" r="1.5"/>
4686
- <circle cx="11" cy="8" r="1.5"/>
4687
- <circle cx="5" cy="13" r="1.5"/>
4688
- <circle cx="11" cy="13" r="1.5"/>
4689
- </svg>`;
4690
- return handle;
4691
- }
4692
- /**
4693
- * Start dragging a layer
4694
- */
4695
- startDrag(layerId, e) {
4696
- var _a;
4697
- const itemEl = this.panel.querySelector(
4698
- `[data-layer-id="${layerId}"]`
4699
- );
4700
- if (!itemEl) return;
4701
- const rect = itemEl.getBoundingClientRect();
4702
- this.state.drag = {
4703
- active: true,
4704
- layerId,
4705
- startY: e.clientY,
4706
- currentY: e.clientY,
4707
- placeholder: null,
4708
- draggedElement: null
4709
- };
4710
- this.panel.classList.add("dragging-active");
4711
- itemEl.classList.add("dragging");
4712
- const placeholder = document.createElement("div");
4713
- placeholder.className = "layer-control-drop-placeholder";
4714
- placeholder.style.height = `${rect.height}px`;
4715
- (_a = itemEl.parentNode) == null ? void 0 : _a.insertBefore(placeholder, itemEl);
4716
- this.state.drag.placeholder = placeholder;
4717
- const clone = itemEl.cloneNode(true);
4718
- clone.classList.remove("dragging");
4719
- clone.className = "layer-control-item layer-control-item-dragging";
4720
- clone.style.width = `${rect.width}px`;
4721
- clone.style.left = `${rect.left}px`;
4722
- clone.style.top = `${rect.top}px`;
4723
- document.body.appendChild(clone);
4724
- this.state.drag.draggedElement = clone;
4725
- const onMove = (moveE) => this.onDragMove(moveE);
4726
- const onEnd = (endE) => {
4727
- document.removeEventListener("pointermove", onMove);
4728
- document.removeEventListener("pointerup", onEnd);
4729
- document.removeEventListener("pointercancel", onEnd);
4730
- this.endDrag(endE);
4731
- };
4732
- document.addEventListener("pointermove", onMove);
4733
- document.addEventListener("pointerup", onEnd);
4734
- document.addEventListener("pointercancel", onEnd);
4735
- }
4736
- /**
4737
- * Handle drag move
4738
- */
4739
- onDragMove(e) {
4740
- var _a, _b;
4741
- if (!this.state.drag.active || !this.state.drag.draggedElement) return;
4742
- const placeholder = this.state.drag.placeholder;
4743
- if (!placeholder) return;
4744
- const deltaY = e.clientY - this.state.drag.startY;
4745
- const clone = this.state.drag.draggedElement;
4746
- const currentTop = parseFloat(clone.style.top) || 0;
4747
- clone.style.top = `${currentTop + deltaY}px`;
4748
- this.state.drag.startY = e.clientY;
4749
- this.state.drag.currentY = e.clientY;
4750
- const scope = placeholder.parentElement;
4751
- const items = Array.from((scope == null ? void 0 : scope.children) ?? []).filter(
4752
- (item) => (item.classList.contains("layer-control-item") || item.classList.contains("layer-control-group")) && !item.classList.contains("dragging") && item.dataset.layerId !== "Background"
4753
- );
4754
- for (const item of items) {
4755
- const itemRect = item.getBoundingClientRect();
4756
- if (e.clientY >= itemRect.top && e.clientY <= itemRect.bottom) {
4757
- const itemMiddle = itemRect.top + itemRect.height / 2;
4758
- if (e.clientY < itemMiddle) {
4759
- if (placeholder.nextSibling !== item) {
4760
- (_a = item.parentNode) == null ? void 0 : _a.insertBefore(placeholder, item);
4761
- }
4762
- } else {
4763
- if (placeholder.previousSibling !== item) {
4764
- (_b = item.parentNode) == null ? void 0 : _b.insertBefore(placeholder, item.nextSibling);
4765
- }
4766
- }
4767
- break;
4768
- }
4769
- }
4770
- }
4771
- /**
4772
- * End dragging
4773
- */
4774
- endDrag(_e) {
4775
- var _a;
4776
- if (!this.state.drag.active) return;
4777
- const layerId = this.state.drag.layerId;
4778
- const placeholder = this.state.drag.placeholder;
4779
- const itemEl = this.panel.querySelector(
4780
- `[data-layer-id="${layerId}"]`
4781
- );
4782
- if (itemEl && placeholder) {
4783
- (_a = placeholder.parentNode) == null ? void 0 : _a.insertBefore(itemEl, placeholder);
4784
- itemEl.classList.remove("dragging");
4785
- }
4786
- this.cleanupDragState();
4787
- this.applyUIOrderToMap();
4788
- }
4789
- /**
4790
- * Clean up drag state
4791
- */
4792
- cleanupDragState() {
4793
- if (this.state.drag.draggedElement) {
4794
- this.state.drag.draggedElement.remove();
4795
- }
4796
- if (this.state.drag.placeholder) {
4797
- this.state.drag.placeholder.remove();
4798
- }
4799
- this.panel.classList.remove("dragging-active");
4800
- this.panel.querySelectorAll(".layer-control-item.dragging").forEach((el) => {
4801
- el.classList.remove("dragging");
4802
- });
4803
- this.state.drag = {
4804
- active: false,
4805
- layerId: null,
4806
- startY: 0,
4807
- currentY: 0,
4808
- placeholder: null,
4809
- draggedElement: null
4810
- };
4811
- }
4812
- /**
4813
- * Apply UI order to map layers
4814
- */
4815
- applyUIOrderToMap() {
4816
- var _a;
4817
- const items = this.panel.querySelectorAll(".layer-control-item");
4818
- const uiLayerIds = [];
4819
- items.forEach((item) => {
4820
- const layerId = item.dataset.layerId;
4821
- if (layerId && layerId !== "Background") {
4822
- uiLayerIds.push(layerId);
4823
- }
4824
- });
4825
- this.applyLayerOrderToMap(uiLayerIds);
4826
- (_a = this.onLayerReorder) == null ? void 0 : _a.call(this, uiLayerIds);
4827
- }
4828
- /**
4829
- * Restack the map's MapLibre layers to match a panel order.
4830
- * @param uiLayerIds User layer IDs top-to-bottom, as the panel lists them
4831
- */
4832
- applyLayerOrderToMap(uiLayerIds) {
4833
- var _a;
4834
- this.state.isStyleOperationInProgress = true;
4835
- const style = this.map.getStyle();
4836
- const mapLibreLayerIds = new Set(((_a = style == null ? void 0 : style.layers) == null ? void 0 : _a.map((l) => l.id)) || []);
4837
- for (let i = 0; i < uiLayerIds.length; i++) {
4838
- const layerId = uiLayerIds[i];
4839
- if (!mapLibreLayerIds.has(layerId)) {
4840
- continue;
4841
- }
4842
- let beforeId = void 0;
4843
- for (let j = i - 1; j >= 0; j--) {
4844
- if (mapLibreLayerIds.has(uiLayerIds[j])) {
4845
- beforeId = uiLayerIds[j];
4846
- break;
4847
- }
4848
- }
4849
- try {
4850
- this.map.moveLayer(layerId, beforeId);
4851
- } catch (e) {
4852
- }
4853
- }
4854
- setTimeout(() => {
4855
- this.state.isStyleOperationInProgress = false;
4856
- }, 200);
4857
- }
4858
- }
1
+ import { C, L, c, l, m, k, o, f, b, d, e, a, h, j, g, i, n, r, s } from "./LayerControl-dS3dARlw.js";
4859
2
  export {
4860
- CustomLayerRegistry,
4861
- LayerControl,
4862
- clamp,
4863
- createBackgroundGroupSymbolSVG,
4864
- createLayerSymbolSVG,
4865
- darkenColor,
4866
- formatNumericValue,
4867
- getLayerColor,
4868
- getLayerColorFromSpec,
4869
- getLayerOpacity,
4870
- getLayerType,
4871
- isStyleableLayerType,
4872
- normalizeColor,
4873
- rgbToHex,
4874
- setLayerOpacity
3
+ C as CustomLayerRegistry,
4
+ L as LayerControl,
5
+ c as clamp,
6
+ l as createBackgroundGroupSymbolSVG,
7
+ m as createCategorizedSymbolSVG,
8
+ k as createLayerSymbolSVG,
9
+ o as darkenColor,
10
+ f as formatNumericValue,
11
+ b as getLayerColor,
12
+ d as getLayerColorCategories,
13
+ e as getLayerColorFromSpec,
14
+ a as getLayerOpacity,
15
+ h as getLayerSymbolStyle,
16
+ j as getLayerSymbolStyleFromSpec,
17
+ g as getLayerType,
18
+ i as isStyleableLayerType,
19
+ n as normalizeColor,
20
+ r as rgbToHex,
21
+ s as setLayerOpacity
4875
22
  };
4876
23
  //# sourceMappingURL=index.mjs.map