Last active
September 18, 2024 23:28
-
-
Save rogie/3e44b2069cc0f5c6590f2f42ac738148 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| /* Dropdown */ | |
| class FigDropdown extends HTMLElement { | |
| constructor() { | |
| super() | |
| this.type = "select" | |
| } | |
| connectedCallback() { | |
| this.trigger = this.querySelector('[slot=trigger]') | |
| if (this.trigger) { | |
| this.append(this.trigger) | |
| } | |
| this.select = document.createElement("select") | |
| this.append(this.select) | |
| Array.from(this.querySelectorAll(":scope > option")).forEach(option => { | |
| this.select.append(option.cloneNode(true)) | |
| }) | |
| this.select.addEventListener("change", this.handleChange.bind(this)) | |
| if (this.getAttribute("type") === "dropdown") { | |
| this.type = "dropdown" | |
| } | |
| this.observer = new MutationObserver(this.childrenChangedCallback.bind(this)) | |
| this.observer.observe(this, { | |
| subtree: true, | |
| childList: true, | |
| }); | |
| } | |
| disconnectedCallback() { | |
| console.log('Observer disconnect') | |
| this.observer.disconnect() | |
| } | |
| childrenChangedCallback(mutationsList, observer) { | |
| console.log("mutation observer: ") | |
| for (const mutation of mutationsList) { | |
| if (mutation.target === this) { | |
| this.select.innerHTML = '' | |
| Array.from(this.querySelectorAll(":scope > option")).forEach(option => { | |
| this.select.append(option.cloneNode(true)) | |
| }) | |
| } | |
| } | |
| } | |
| attributeChangedCallback(name, oldValue, newValue) { | |
| //console.log(name, newValue) | |
| } | |
| handleChange() { | |
| if (this.type === "dropdown") { | |
| this.select.selectedIndex = 0 | |
| } | |
| } | |
| } | |
| window.customElements.define('fig-dropdown', FigDropdown); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment