diff --git a/src/l-tooltip.js b/src/l-tooltip.js index 60d349c..95ebf26 100644 --- a/src/l-tooltip.js +++ b/src/l-tooltip.js @@ -2,20 +2,23 @@ import { tooltip } from "leaflet"; import { tooltipConnected } from "./events"; -import { json, option, parse } from "./parse.js"; class LTooltip extends HTMLElement { - static observedAttributes = ["content", "permanent", "direction"]; + static observedAttributes = ["content", "permanent", "interactive", "direction"]; constructor() { super(); + this.tooltip = null; + } + + connectedCallback() { this.tooltip = tooltip({ permanent: this.hasAttribute("permanent"), + interactive: this.hasAttribute("interactive"), direction: this.getAttribute("direction") ?? "auto" }); - } + this.tooltip.setContent(this.getAttribute("content")); - connectedCallback() { const event = new CustomEvent(tooltipConnected, { cancelable: true, bubbles: true, @@ -31,8 +34,16 @@ class LTooltip extends HTMLElement { * @param {string} newValue */ attributeChangedCallback(attName, _, newValue) { - if (attName === "content") { - this.tooltip.setContent(newValue); + if (this.tooltip) { + if (attName === "content") { + this.tooltip.setContent(newValue); + } else if (attName === "permanent") { + this.tooltip.options.permanent = this.hasAttribute("permanent"); + } else if (attName === "interactive") { + this.tooltip.options.interactive = this.hasAttribute("interactive"); + } else if (attName === "direction") { + this.tooltip.options.direction = newValue; + } } } } diff --git a/src/l-tooltip.test.js b/src/l-tooltip.test.js new file mode 100644 index 0000000..f7daa40 --- /dev/null +++ b/src/l-tooltip.test.js @@ -0,0 +1,47 @@ +// @vitest-environment happy-dom +import { tooltip } from "leaflet"; +import { expect, it } from "vitest"; +import "./index.js"; + +it("should render a tooltip", () => { + const el = document.createElement("l-tooltip"); + el.setAttribute("permanent", ""); + el.setAttribute("interactive", ""); + el.setAttribute("direction", "right"); + el.setAttribute("content", "
Hello, tooltip!
"); + + const expectedTooltip = tooltip( + { + permanent: true, + interactive: true, + direction: "right" + } + ); + expectedTooltip.setContent("
Hello, tooltip!
"); + + document.body.appendChild(el); + + expect(el.tooltip).toEqual(expectedTooltip); +}); + +it("should change attributes after rendering", () => { + const el = document.createElement("l-tooltip"); + el.setAttribute("permanent", ""); + + const expectedTooltip = tooltip( + { + permanent: false, + interactive: true, + direction: "center" + } + ); + expectedTooltip.setContent("Hello there!"); + + document.body.appendChild(el); + el.setAttribute("content", "Hello there!"); + el.setAttribute("direction", "center"); + el.removeAttribute("permanent"); + el.setAttribute("interactive", ""); + + expect(el.tooltip).toEqual(expectedTooltip); +});