UNPKG

hologram-web-library

Version:
78 lines (63 loc) 2.17 kB
import HTMLParsedElement from "./hw-common"; export const hsInputCustomAttributes = ["type", "errors", "container-styles", "auto-complete"]; class HWInput extends HTMLParsedElement { input; errorsContainer; constructor() { super(); this.input = document.createElement("input"); this.errorsContainer = document.createElement("div"); } parsedCallback() { this.getAttributeNames().forEach((attr) => { if (hsInputCustomAttributes.indexOf(attr) < 0) { this.input?.setAttribute(attr, this.getAttribute(attr) || ""); this.removeAttribute(attr); } else if (attr === "container-styles") { this.getAttribute("container-styles") ?.split(" ") .forEach((className) => { this.classList.add(className); }); } }); this.classList.add("hw-input-wrapper"); this.input.classList.add("hw-input"); this.errorsContainer.classList.add("hidden"); this.input.classList.add("auto-complete"); this.appendChild(this.input); this.appendChild(this.errorsContainer); } static get observedAttributes() { return hsInputCustomAttributes; } attributeChangedCallback(attrName, oldValue, newValue) { if (attrName === "errors") { // Clear old error messages this.handleError(oldValue, newValue); } if (attrName === "type") { this.input.setAttribute(attrName, newValue); } if (attrName === "auto-complete") { this.input.setAttribute(attrName, newValue); } } handleError(oldValue, newValue) { this.errorsContainer.innerHTML = ""; if (!newValue || oldValue === newValue) { this.errorsContainer.classList.add("hidden"); this.input.classList.remove("has-error"); return; } this.input.classList.add("has-error"); this.errorsContainer.classList.remove("hidden"); const errorMessage = document.createElement("p"); errorMessage.classList.add("hw-input-error-message"); errorMessage.textContent = newValue; this.errorsContainer.appendChild(errorMessage); } } if (!customElements.get("hw-input")) { customElements.define("hw-input", HWInput); }