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