|
| 1 | +import { loadIcon } from "./utils.mjs"; |
| 2 | +/** |
| 3 | + * Represents tool/action button. |
| 4 | + */ |
| 5 | +export class ToolButton extends HTMLElement { |
| 6 | + constructor({ id, iconUrl, onClick }) { |
| 7 | + super(); |
| 8 | + |
| 9 | + this.#description = id.description; |
| 10 | + this.#iconUrl = iconUrl; |
| 11 | + this.id = id; |
| 12 | + this.#onClick = onClick; |
| 13 | + this.attachShadow({ mode: "open" }); |
| 14 | + } |
| 15 | + |
| 16 | + id = ""; |
| 17 | + #iconUrl = ""; |
| 18 | + #description = ""; |
| 19 | + #onClick = () => {}; |
| 20 | + |
| 21 | + connectedCallback() { |
| 22 | + this.shadowRoot.innerHTML = ` |
| 23 | + <style> |
| 24 | + button { |
| 25 | + width: var(--button-size); |
| 26 | + height: var(--button-size); |
| 27 | + border: 2px solid black; |
| 28 | + border-radius: 6px; |
| 29 | + } |
| 30 | +
|
| 31 | + button[aria-pressed="true"] { |
| 32 | + border: 2px solid white; |
| 33 | + box-shadow: 0px 0px 0px 4px orange; |
| 34 | + } |
| 35 | + </style> |
| 36 | + <button |
| 37 | + data-id="${this.id.description}" |
| 38 | + data-value="${this.#description}" |
| 39 | + aria-label="${this.#description.toLocaleLowerCase()} tool" |
| 40 | + aria-pressed="${this.isActive ? "true" : "false"}" |
| 41 | + > |
| 42 | + </button> |
| 43 | + `; |
| 44 | + |
| 45 | + this.#button.addEventListener("click", this.#handleClick, true); |
| 46 | + this.isActive = false; |
| 47 | + |
| 48 | + loadIcon(this.#iconUrl) |
| 49 | + .then((icon) => { |
| 50 | + this.#button.innerHTML = icon; |
| 51 | + }) |
| 52 | + .catch((error) => { |
| 53 | + console.error(error); |
| 54 | + this.#button.innerText = this.#description; |
| 55 | + }); |
| 56 | + } |
| 57 | + |
| 58 | + click(e) { |
| 59 | + this.#button.dispatchEvent(e); |
| 60 | + } |
| 61 | + |
| 62 | + set isActive(value) { |
| 63 | + if (value) { |
| 64 | + this.#button.setAttribute("aria-pressed", "true"); |
| 65 | + } else { |
| 66 | + this.#button.removeAttribute("aria-pressed", "false"); |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + get #button() { |
| 71 | + return this.shadowRoot.querySelector("button"); |
| 72 | + } |
| 73 | + |
| 74 | + #handleClick = (e) => { |
| 75 | + this.#onClick(e); |
| 76 | + }; |
| 77 | + |
| 78 | + static compare(id, description) { |
| 79 | + return id.description === description; |
| 80 | + } |
| 81 | +} |
0 commit comments