Last active
March 19, 2024 14:02
-
-
Save MariusBongarts/557b0d23ed993483c8b9eeb384f24120 to your computer and use it in GitHub Desktop.
MediumHighlighter - Custom element
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MediumHighlighter extends HTMLElement { | |
get markerPosition() { | |
return JSON.parse(this.getAttribute("markerPosition") || "{}"); | |
} | |
get styleElement() { | |
return this.shadowRoot.querySelector("style"); | |
} | |
get highlightTemplate() { | |
return this.shadowRoot.getElementById("highlightTemplate"); | |
} | |
static get observedAttributes() { | |
return ["markerPosition"]; | |
} | |
constructor() { | |
super(); | |
this.render(); | |
} | |
render() { | |
this.attachShadow({ mode: "open" }); | |
const style = document.createElement("style"); | |
style.textContent = styled({}); | |
this.shadowRoot.appendChild(style); | |
this.shadowRoot.innerHTML += template; | |
this.shadowRoot | |
.getElementById("mediumHighlighter") | |
.addEventListener("click", () => this.highlightSelection()); | |
} | |
attributeChangedCallback(name, oldValue, newValue) { | |
if (name === "markerPosition") { | |
this.styleElement.textContent = styled(this.markerPosition); | |
} | |
} | |
highlightSelection() { | |
var userSelection = window.getSelection(); | |
for (let i = 0; i < userSelection.rangeCount; i++) { | |
this.highlightRange(userSelection.getRangeAt(i)); | |
} | |
window.getSelection().empty(); | |
} | |
highlightRange(range) { | |
const clone = | |
this.highlightTemplate.cloneNode(true).content.firstElementChild; | |
clone.appendChild(range.extractContents()); | |
range.insertNode(clone); | |
} | |
} | |
window.customElements.define("medium-highlighter", MediumHighlighter); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment