maplibre-gl-layer-control 0.18.3 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -241,6 +241,7 @@ function MapComponent() {
241
241
  | `excludeLayers` | `string[]` | `undefined` | Array of wildcard patterns to exclude layers by name (e.g., `['*-temp-*', 'debug-*']`) |
242
242
  | `customLayerAdapters` | `CustomLayerAdapter[]` | `undefined` | Adapters for non-MapLibre layers (deck.gl, Zarr, etc.) |
243
243
  | `basemapStyleUrl` | `string` | `undefined` | URL of basemap style JSON for reliable layer detection (see below) |
244
+ | `basemapLayerIds` | `string[]` | `undefined` | Basemap layer IDs, when you already know them; takes precedence over `basemapStyleUrl`, and an empty array means "no basemap layers" (see below) |
244
245
  | `enableContextMenu` | `boolean` | `true` | Enable the right-click context menu on layers (Rename, Zoom to Layer, Move Up/Down/to Top/to Bottom, Remove Layer) |
245
246
  | `enableDragAndDrop` | `boolean` | `true` | Enable drag-and-drop reordering of layers in the panel |
246
247
  | `onLayerRename` | `(layerId: string, oldName: string, newName: string) => void` | `undefined` | Called when a layer is renamed through the context menu |
@@ -303,6 +304,16 @@ When `basemapStyleUrl` is provided:
303
304
  - All other layers (user-added) are shown individually in the control
304
305
  - New layers added later are automatically detected as user layers
305
306
 
307
+ ### Explicit basemap layer IDs
308
+
309
+ When the application already knows which layers are the basemap (for example, a style built in code with no URL to fetch), pass them directly. Nothing is fetched, and an empty array is honoured as "no basemap layers" instead of falling back to the heuristics below:
310
+
311
+ ```javascript
312
+ const layerControl = new LayerControl({
313
+ basemapLayerIds: map.getStyle().layers.map((layer) => layer.id),
314
+ });
315
+ ```
316
+
306
317
  ### Automatic Detection Without basemapStyleUrl
307
318
 
308
319
  Even without `basemapStyleUrl`, the control uses source-based heuristics to detect user-added layers. Custom MapLibre layers (using `map.addLayer()`) are automatically detected whether they are added **before** or **after** the layer control - no custom adapter is needed for standard MapLibre layer types!
@@ -582,6 +593,16 @@ interface CustomLayerAdapter {
582
593
  - **Show All** / **Hide All** also show or hide every group.
583
594
  - When groups change outside the control, call `layerControl.refreshGroups()`. It rebuilds the panel when a group was added, removed, or re-parented, or a layer changed group, and otherwise updates the group rows in place.
584
595
 
596
+ ### Driving the panel from outside
597
+
598
+ Applications that keep layer state in their own store (and drive the map from it) can mirror that state into the panel without rebuilding it:
599
+
600
+ | Method | Description |
601
+ |--------|-------------|
602
+ | `setLayerState(layerId, { visible?, opacity?, name? })` | Update a row's checkbox, opacity slider and name in place, without touching the map or firing callbacks. Only listed layers are updated, except that `"Background"` adds the Background row when there is none (a style whose basemap lives in style imports). Returns `false` (and does nothing) until the control has listed the map's layers, which is after `onAdd` and after any `basemapStyleUrl` fetch; otherwise `true` when a state was updated or created. |
603
+ | `setLayerOrder(layerIds)` | Set the panel order (top first) for layers with nothing on the map to sort them by, then redraw the rows. Use it to put the panel back after refusing a drag or context-menu move reported through `onLayerReorder`. A hidden custom layer whose adapter has other layers on the map keeps its slot beside them in the adapter's list. |
604
+ | `isCollapsed()` / `expand()` / `collapse()` | Read or change whether the panel is open, for example to remount a control in the state the user left it. |
605
+
585
606
  #### Limitations
586
607
 
587
608
  - **Style Editor**: The style editor (gear icon) is not available for custom layers since they don't use MapLibre's paint properties. Clicking the gear icon will show an info panel explaining this.
@@ -1376,6 +1376,12 @@ class LayerControl {
1376
1376
  __publicField(this, "groupStructureKey", "");
1377
1377
  __publicField(this, "basemapStyleUrl", null);
1378
1378
  __publicField(this, "basemapLayerIds", null);
1379
+ /** True when `basemapLayerIds` came from the option, which is authoritative even when empty. */
1380
+ __publicField(this, "basemapLayerIdsProvided", false);
1381
+ /** Set once onAdd has listed the map's layers (after any basemapStyleUrl fetch). */
1382
+ __publicField(this, "layersListed", false);
1383
+ /** Panel order set through setLayerOrder, used to order layers with nothing on the map. */
1384
+ __publicField(this, "layerOrderHint", null);
1379
1385
  __publicField(this, "widthFrame", null);
1380
1386
  // Exact-opacity input popup
1381
1387
  __publicField(this, "opacityInputEl", null);
@@ -1465,6 +1471,19 @@ class LayerControl {
1465
1471
  });
1466
1472
  }
1467
1473
  this.basemapStyleUrl = options.basemapStyleUrl || null;
1474
+ if (options.basemapLayerIds) {
1475
+ this.basemapLayerIds = new Set(options.basemapLayerIds);
1476
+ this.basemapLayerIdsProvided = true;
1477
+ }
1478
+ }
1479
+ /**
1480
+ * Whether basemap membership is decided by a known list of basemap layer IDs
1481
+ * (the `basemapLayerIds` option, or the layers of `basemapStyleUrl`) rather
1482
+ * than by heuristics. A fetched style only counts when it had layers; an
1483
+ * explicit list counts even when empty.
1484
+ */
1485
+ hasBasemapLayerIds() {
1486
+ return this.basemapLayerIds !== null && (this.basemapLayerIdsProvided || this.basemapLayerIds.size > 0);
1468
1487
  }
1469
1488
  /**
1470
1489
  * Called when the control is added to the map
@@ -1472,6 +1491,7 @@ class LayerControl {
1472
1491
  onAdd(map) {
1473
1492
  this.map = map;
1474
1493
  this.mapContainer = map.getContainer();
1494
+ this.layersListed = false;
1475
1495
  const style = this.map.getStyle();
1476
1496
  if (style && style.sources) {
1477
1497
  this.initialSourceIds = new Set(Object.keys(style.sources));
@@ -1499,6 +1519,7 @@ class LayerControl {
1499
1519
  this.autoDetectLayers();
1500
1520
  }
1501
1521
  this.buildLayerItems();
1522
+ this.layersListed = true;
1502
1523
  }).catch((error) => {
1503
1524
  console.warn(
1504
1525
  "Failed to fetch basemap style, falling back to heuristic detection:",
@@ -1508,12 +1529,14 @@ class LayerControl {
1508
1529
  this.autoDetectLayers();
1509
1530
  }
1510
1531
  this.buildLayerItems();
1532
+ this.layersListed = true;
1511
1533
  });
1512
1534
  } else {
1513
1535
  if (Object.keys(this.state.layerStates).length === 0) {
1514
1536
  this.autoDetectLayers();
1515
1537
  }
1516
1538
  this.buildLayerItems();
1539
+ this.layersListed = true;
1517
1540
  }
1518
1541
  if (!this.state.collapsed) {
1519
1542
  requestAnimationFrame(() => {
@@ -1596,7 +1619,7 @@ class LayerControl {
1596
1619
  if (this.targetLayers.length === 0) {
1597
1620
  const userAddedLayers = [];
1598
1621
  const backgroundLayerIds = [];
1599
- const useBasemapStyleDetection = this.basemapLayerIds !== null && this.basemapLayerIds.size > 0;
1622
+ const useBasemapStyleDetection = this.hasBasemapLayerIds();
1600
1623
  const userAddedSourceIds = useBasemapStyleDetection ? /* @__PURE__ */ new Set() : this.detectUserAddedSources();
1601
1624
  allLayerIds.forEach((layerId) => {
1602
1625
  const layer = this.map.getLayer(layerId);
@@ -2247,19 +2270,122 @@ class LayerControl {
2247
2270
  }
2248
2271
  }
2249
2272
  /**
2250
- * Expand the panel
2273
+ * Whether the panel is collapsed (closed). Before the control is added to a
2274
+ * map this reflects the `collapsed` option.
2275
+ * @returns True while the panel is closed
2276
+ */
2277
+ isCollapsed() {
2278
+ return this.state.collapsed;
2279
+ }
2280
+ /**
2281
+ * Expand (open) the panel. Before the control is added to a map this only
2282
+ * records the state, and the panel opens when it is built.
2251
2283
  */
2252
2284
  expand() {
2253
2285
  this.state.collapsed = false;
2286
+ if (!this.panel) return;
2254
2287
  this.panel.classList.add("expanded");
2255
2288
  this.updatePanelPosition();
2256
2289
  }
2257
2290
  /**
2258
- * Collapse the panel
2291
+ * Collapse (close) the panel.
2259
2292
  */
2260
2293
  collapse() {
2294
+ var _a;
2261
2295
  this.state.collapsed = true;
2262
- this.panel.classList.remove("expanded");
2296
+ (_a = this.panel) == null ? void 0 : _a.classList.remove("expanded");
2297
+ }
2298
+ /**
2299
+ * Update a layer row's visibility, opacity and name in place, without
2300
+ * touching the map or firing any callback. Use it to mirror changes made
2301
+ * outside the control (for example by an application store that owns layer
2302
+ * state) into an already-built panel without rebuilding it.
2303
+ *
2304
+ * Only layers the control already lists are updated, with one exception:
2305
+ * `"Background"` adds the Background row when the control has none (a style
2306
+ * whose basemap lives in style imports has no root basemap layers to detect,
2307
+ * so the control would otherwise show no Background row). It returns false
2308
+ * until the control has listed the map's layers (after `onAdd`, and after a
2309
+ * `basemapStyleUrl` fetch), since seeding state earlier would stop the
2310
+ * control from detecting layers on its own.
2311
+ *
2312
+ * @param layerId The layer ID, or `"Background"` for the basemap row
2313
+ * @param state The fields to change; omitted fields keep their value
2314
+ * @returns True if a layer state was updated or created
2315
+ */
2316
+ setLayerState(layerId, state) {
2317
+ if (!this.panel || !this.layersListed) return false;
2318
+ let current = this.state.layerStates[layerId];
2319
+ if (!current) {
2320
+ if (layerId !== "Background") return false;
2321
+ current = this.state.layerStates.Background = {
2322
+ visible: state.visible ?? true,
2323
+ opacity: state.opacity ?? 1,
2324
+ name: state.name ?? "Background"
2325
+ };
2326
+ this.buildLayerItems();
2327
+ }
2328
+ if (state.visible !== void 0) current.visible = state.visible;
2329
+ if (state.opacity !== void 0) current.opacity = state.opacity;
2330
+ if (state.name !== void 0) {
2331
+ current.name = state.name;
2332
+ if (this.state.customLayerNames.has(layerId)) {
2333
+ this.state.customLayerNames.set(layerId, state.name);
2334
+ }
2335
+ }
2336
+ for (const item of this.rowsByLayerId().get(layerId) ?? []) {
2337
+ const checkbox = item.querySelector(
2338
+ ":scope > .layer-control-row > .layer-control-checkbox"
2339
+ );
2340
+ if (checkbox) checkbox.checked = current.visible;
2341
+ const slider = item.querySelector(
2342
+ ":scope > .layer-control-row > .layer-control-opacity"
2343
+ );
2344
+ if (slider) {
2345
+ slider.value = String(current.opacity);
2346
+ slider.title = `Opacity: ${Math.round(current.opacity * 100)}%`;
2347
+ }
2348
+ const name = item.querySelector(
2349
+ ":scope > .layer-control-row > .layer-control-name"
2350
+ );
2351
+ if (name) {
2352
+ name.textContent = current.name;
2353
+ name.title = current.name;
2354
+ }
2355
+ }
2356
+ return true;
2357
+ }
2358
+ /**
2359
+ * Set the order the panel lists layers in, then redraw the rows.
2360
+ *
2361
+ * Layers whose native MapLibre layers are on the map are always listed in
2362
+ * map stacking order; this order applies to the rest (custom-adapter layers
2363
+ * with nothing on the map yet, such as hidden ones). Use it to put the panel
2364
+ * back after an application refused a drag or context-menu move, since the
2365
+ * control has already moved the row by then. Layers not listed keep their
2366
+ * relative order after the listed ones, and Background stays at the bottom.
2367
+ * A hidden custom layer whose adapter has other layers on the map keeps its
2368
+ * slot beside them in that adapter's list, since the adapter is the source of
2369
+ * truth for where it sits; this order breaks the remaining ties.
2370
+ *
2371
+ * @param layerIds Layer IDs, top of the panel first
2372
+ */
2373
+ setLayerOrder(layerIds) {
2374
+ const states = this.state.layerStates;
2375
+ const order = [];
2376
+ const seen = /* @__PURE__ */ new Set(["Background"]);
2377
+ for (const id of [...layerIds, ...Object.keys(states)]) {
2378
+ if (id in states && !seen.has(id)) {
2379
+ seen.add(id);
2380
+ order.push(id);
2381
+ }
2382
+ }
2383
+ this.layerOrderHint = order;
2384
+ const ordered = {};
2385
+ if ("Background" in states) ordered.Background = states.Background;
2386
+ for (const id of order) ordered[id] = states[id];
2387
+ this.state.layerStates = ordered;
2388
+ if (this.panel) this.buildLayerItems();
2263
2389
  }
2264
2390
  /**
2265
2391
  * Build layer items (called initially and when layers change)
@@ -3019,7 +3145,7 @@ class LayerControl {
3019
3145
  if (this.state.layerStates[layerId] !== void 0 && layerId !== "Background") {
3020
3146
  return true;
3021
3147
  }
3022
- if (this.basemapLayerIds !== null && this.basemapLayerIds.size > 0) {
3148
+ if (this.hasBasemapLayerIds()) {
3023
3149
  return !this.basemapLayerIds.has(layerId);
3024
3150
  }
3025
3151
  if (this.initialLayerIds !== null && !this.initialLayerIds.has(layerId)) {
@@ -5076,7 +5202,7 @@ class LayerControl {
5076
5202
  );
5077
5203
  let layersAdded = false;
5078
5204
  const newLayers = [];
5079
- const useBasemapStyleDetection = this.basemapLayerIds !== null && this.basemapLayerIds.size > 0;
5205
+ const useBasemapStyleDetection = this.hasBasemapLayerIds();
5080
5206
  const useInitialLayerDetection = !useBasemapStyleDetection && this.initialLayerIds !== null && this.initialLayerIds.size > 0;
5081
5207
  currentMapLayerIds.forEach((layerId) => {
5082
5208
  if (layerId !== "Background" && !this.state.layerStates[layerId]) {
@@ -5489,6 +5615,14 @@ class LayerControl {
5489
5615
  const userLayerIds = Object.keys(this.state.layerStates).filter(
5490
5616
  (id) => id !== "Background"
5491
5617
  );
5618
+ const hint = this.layerOrderHint;
5619
+ if (hint) {
5620
+ const rank = new Map(hint.map((id, index) => [id, index]));
5621
+ const keyIndex = new Map(userLayerIds.map((id, index) => [id, index]));
5622
+ userLayerIds.sort(
5623
+ (a, b) => (rank.get(a) ?? hint.length + keyIndex.get(a)) - (rank.get(b) ?? hint.length + keyIndex.get(b))
5624
+ );
5625
+ }
5492
5626
  const resolvedIndexOf = (id) => {
5493
5627
  var _a2;
5494
5628
  const direct = indexById.get(id);
@@ -6114,4 +6248,4 @@ exports.normalizeColor = normalizeColor;
6114
6248
  exports.restoreOriginalStyle = restoreOriginalStyle;
6115
6249
  exports.rgbToHex = rgbToHex;
6116
6250
  exports.setLayerOpacity = setLayerOpacity;
6117
- //# sourceMappingURL=LayerControl-BVcYNnJ3.cjs.map
6251
+ //# sourceMappingURL=LayerControl-BxSfUXK6.cjs.map