|
| 1 | + |
| 2 | +import { MCComponent } from "./Component.js"; |
| 3 | + |
| 4 | +class MCSwitch extends MCComponent { |
| 5 | + static get componentName() { return "mc-switch"; }; |
| 6 | + static get templateUrl() { return "src/UI/MCSwitch.html" }; |
| 7 | + static observedAttributes = ["disabled", "value", "sep", "checked", "on", "off"]; |
| 8 | + #on = this.shadowRoot.querySelector("slot[name=on]"); |
| 9 | + #off = this.shadowRoot.querySelector("slot[name=off"); |
| 10 | + #refresh(checked = this.checked) { |
| 11 | + this.#on.style.display = checked? null: "none"; |
| 12 | + this.#off.style.display = checked? "none": null; |
| 13 | + }; |
| 14 | + constructor() { |
| 15 | + super(); |
| 16 | + this.#refresh(); |
| 17 | + this.addEventListener("click", e => { |
| 18 | + if (this.disabled) return false; |
| 19 | + this.checked = !this.checked; |
| 20 | + this.dispatchEvent("toggle", { global: true, data: this.checked, }); |
| 21 | + }); |
| 22 | + }; |
| 23 | + attributeChangedCallback(name, oldValue, newValue) { |
| 24 | + if (name === "checked") this.#refresh(newValue !== null); |
| 25 | + else if (name === "disabled") this.disabled = newValue; |
| 26 | + else if (name === "value") |
| 27 | + this.shadowRoot.querySelector("slot").innerHTML = newValue; |
| 28 | + else if (name === "sep") |
| 29 | + this.shadowRoot.querySelector("slot[name=sep]").innerHTML = newValue; |
| 30 | + else if (name === "on") |
| 31 | + this.#on.innerHTML = newValue; |
| 32 | + else if (name === "off") |
| 33 | + this.#off.innerHTML = newValue; |
| 34 | + }; |
| 35 | + get disabled() { return this.hasAttribute("disabled"); }; |
| 36 | + set disabled(val) { |
| 37 | + if (val) this.setAttribute("disabled", ""); |
| 38 | + else this.removeAttribute("disabled"); |
| 39 | + }; |
| 40 | + get checked() { return this.hasAttribute("checked"); }; |
| 41 | + set checked(val) { |
| 42 | + if (this.disabled) return; |
| 43 | + if (val) this.setAttribute("checked", ""); |
| 44 | + else this.removeAttribute("checked"); |
| 45 | + }; |
| 46 | +}; |
| 47 | + |
| 48 | +MCSwitch.setBorderAndWaitImg("button", ":host"); |
| 49 | +MCSwitch.setBorderAndWaitImg("button-hover", ":host(:hover)"); |
| 50 | +MCSwitch.setBorderAndWaitImg("button-active", ":host(:active)"); |
| 51 | +MCSwitch.setBorderAndWaitImg("button-disabled", ":host([disabled])"); |
| 52 | + |
| 53 | +MCSwitch.asyncLoadAndDefine(); |
| 54 | + |
| 55 | +export { |
| 56 | + MCSwitch |
| 57 | +}; |
0 commit comments