Skip to content

Commit

Permalink
Merge pull request #58 from mo-martinwilson/resolve-issue-54-control-…
Browse files Browse the repository at this point in the history
…layers

Resolve issue 54 control layers
  • Loading branch information
andrewgryan authored Nov 27, 2024
2 parents 49ba39a + a29941a commit 6a1167c
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 3 deletions.
13 changes: 11 additions & 2 deletions src/l-map.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
40 changes: 39 additions & 1 deletion src/l-map.test.js
Original file line number Diff line number Diff line change
@@ -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";

Expand Down Expand Up @@ -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 <l-map><l-control-layers>... 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 <l-map>
expect(mockLayer.addTo).toHaveBeenCalledWith(map);
});

0 comments on commit 6a1167c

Please sign in to comment.