diff --git a/src/l-map.js b/src/l-map.js index ac3d160..1cf3553 100644 --- a/src/l-map.js +++ b/src/l-map.js @@ -86,10 +86,19 @@ class LMap extends HTMLElement { this.map.locate(parse(schema, this)); } + const layerConnectedHandlers = { + "l-control-layers": (layer, map) => layer.addTo(map), + "default": (layer, map) => map.addLayer(layer), + }; + this.addEventListener(layerConnected, (ev) => { - const layer = ev.detail.layer; - this.map.addLayer(layer); + const { layer } = ev.detail; + const target = ev.target.localName ; + + const layerConnectedHandler = layerConnectedHandlers[target] || layerConnectedHandlers["default"]; + layerConnectedHandler(layer, this.map); }); + this.addEventListener(layerRemoved, (ev) => { if (this.map !== null) { diff --git a/src/l-map.test.js b/src/l-map.test.js index f22beb7..2facb03 100644 --- a/src/l-map.test.js +++ b/src/l-map.test.js @@ -1,7 +1,7 @@ // @vitest-environment happy-dom import "./index.js"; import { layerRemoved, layerConnected } from "./events" -import { it, expect } from "vitest"; +import { vi, it, expect } from "vitest"; import LTileLayer from "./l-tile-layer"; import LMap from "./l-map.js"; @@ -74,3 +74,41 @@ it("should bubble layer remove events", async () => { const expected = { layer: tileLayer.layer }; expect(actual).toEqual(expected); }) + +it("should handle layerConnected event from l-control-layers correctly", async () => { + // Arrange: create a ... arrangement + const el = /** @type {LMap} */ (document.createElement("l-map")); + el.setAttribute("zoom", "0"); + el.setAttribute("center", JSON.stringify([0, 0])); + + const controlLayers = document.createElement("l-control-layers"); + el.appendChild(controlLayers); + + // Arrange: add a trackable mock layer to the layerConnected event + const mockLayer = { + addTo: vi.fn(), // Mocks layer.addTo method + }; + const event = new CustomEvent(layerConnected, { + bubbles: true, + detail: { layer: mockLayer }, + }); + + // Act: connect to DOM + document.body.appendChild(el); + + // Act: Dispatch the layerConnected event on the control layers + const promise = new Promise((resolve) => { + controlLayers.addEventListener(layerConnected, (ev) => { + resolve(ev.detail); + }); + }); + controlLayers.dispatchEvent(event); + + // Assert: event detail is correctly passed + const actual = await promise; + expect(actual).toEqual({ layer: mockLayer }); + + // Assert: addTo method was called on the map + const map = el.map; // Map instance from + expect(mockLayer.addTo).toHaveBeenCalledWith(map); +});