diff --git a/scripts/components.js b/scripts/components.js index f5d2770..99be7bc 100644 --- a/scripts/components.js +++ b/scripts/components.js @@ -2,7 +2,7 @@ // Components downloaded: chips,copy,form,input,menu,notifications,popup,switch,select,spinner,textarea,text-field,theme-toggle const smChips = document.createElement("template"); smChips.innerHTML = '
', customElements.define("sm-chips", class extends HTMLElement { constructor() { super(), this.attachShadow({ mode: "open" }).append(smChips.content.cloneNode(!0)), this.chipsWrapper = this.shadowRoot.querySelector(".sm-chips"), this.coverLeft = this.shadowRoot.querySelector(".cover--left"), this.coverRight = this.shadowRoot.querySelector(".cover--right"), this.navButtonLeft = this.shadowRoot.querySelector(".nav-button--left"), this.navButtonRight = this.shadowRoot.querySelector(".nav-button--right"), this.slottedOptions = void 0, this._value = void 0, this.scrollDistance = 0, this.assignedElements = [], this.scrollLeft = this.scrollLeft.bind(this), this.scrollRight = this.scrollRight.bind(this), this.fireEvent = this.fireEvent.bind(this), this.setSelectedOption = this.setSelectedOption.bind(this) } get value() { return this._value } set value(t) { this.setSelectedOption(t) } scrollLeft() { this.chipsWrapper.scrollBy({ left: -this.scrollDistance, behavior: "smooth" }) } scrollRight() { this.chipsWrapper.scrollBy({ left: this.scrollDistance, behavior: "smooth" }) } setSelectedOption(t) { this._value !== t && (this._value = t, this.assignedElements.forEach(e => { e.value == t ? (e.setAttribute("selected", ""), e.scrollIntoView({ behavior: "smooth", block: "nearest", inline: "center" })) : e.removeAttribute("selected") })) } fireEvent() { this.dispatchEvent(new CustomEvent("change", { bubbles: !0, composed: !0, detail: { value: this._value } })) } connectedCallback() { this.setAttribute("role", "listbox"); const t = this.shadowRoot.querySelector("slot"); t.addEventListener("slotchange", e => { n.disconnect(), i.disconnect(), this.observeSelf.disconnect(), clearTimeout(this.slotChangeTimeout), this.slotChangeTimeout = setTimeout(() => { this.assignedElements = t.assignedElements(), this.assignedElements.forEach(t => { t.hasAttribute("selected") && (this._value = t.value) }), this.observeSelf.observe(this) }, 0) }); const e = new ResizeObserver(t => { t.forEach(t => { if (t.contentBoxSize) { const e = Array.isArray(t.contentBoxSize) ? t.contentBoxSize[0] : t.contentBoxSize; this.scrollDistance = .6 * e.inlineSize } else this.scrollDistance = .6 * t.contentRect.width }) }); e.observe(this), this.observeSelf = new IntersectionObserver((t, e) => { t.forEach(t => { t.isIntersecting && !this.hasAttribute("multiline") && this.assignedElements.length > 0 && (n.observe(this.assignedElements[0]), i.observe(this.assignedElements[this.assignedElements.length - 1]), e.unobserve(this)) }) }, { threshold: 1 }), this.chipsWrapper.addEventListener("option-clicked", t => { this._value !== t.target.value && (this.setSelectedOption(t.target.value), this.fireEvent()) }); const n = new IntersectionObserver(t => { t.forEach(t => { t.isIntersecting ? (this.navButtonLeft.classList.add("hide"), this.coverLeft.classList.add("hide")) : (this.navButtonLeft.classList.remove("hide"), this.coverLeft.classList.remove("hide")) }) }, { threshold: 1, root: this }), i = new IntersectionObserver(t => { t.forEach(t => { t.isIntersecting ? (this.navButtonRight.classList.add("hide"), this.coverRight.classList.add("hide")) : (this.navButtonRight.classList.remove("hide"), this.coverRight.classList.remove("hide")) }) }, { threshold: 1, root: this }); this.navButtonLeft.addEventListener("click", this.scrollLeft), this.navButtonRight.addEventListener("click", this.scrollRight) } disconnectedCallback() { this.navButtonLeft.removeEventListener("click", this.scrollLeft), this.navButtonRight.removeEventListener("click", this.scrollRight) } }); const smChip = document.createElement("template"); smChip.innerHTML = ' ', customElements.define("sm-chip", class extends HTMLElement { constructor() { super(), this.attachShadow({ mode: "open" }).append(smChip.content.cloneNode(!0)), this._value = void 0, this.radioButton = this.shadowRoot.querySelector("input"), this.fireEvent = this.fireEvent.bind(this), this.handleKeyDown = this.handleKeyDown.bind(this) } get value() { return this._value } fireEvent() { this.dispatchEvent(new CustomEvent("option-clicked", { bubbles: !0, composed: !0, detail: { value: this._value } })) } handleKeyDown(t) { "Enter" !== t.key && "Space" !== t.key || this.fireEvent() } connectedCallback() { this.setAttribute("role", "option"), this.setAttribute("tabindex", "0"), this._value = this.getAttribute("value"), this.addEventListener("click", this.fireEvent), this.addEventListener("keydown", this.handleKeyDown) } disconnectedCallback() { this.removeEventListener("click", this.fireEvent), this.removeEventListener("keydown", this.handleKeyDown) } }); const smCopy = document.createElement("template"); smCopy.innerHTML = '

', customElements.define("sm-copy", class extends HTMLElement { constructor() { super(), this.attachShadow({ mode: "open" }).append(smCopy.content.cloneNode(!0)), this.copyContent = this.shadowRoot.querySelector(".copy-content"), this.copyButton = this.shadowRoot.querySelector(".copy-button"), this.copy = this.copy.bind(this) } static get observedAttributes() { return ["value"] } set value(t) { this.setAttribute("value", t) } get value() { return this.getAttribute("value") } fireEvent() { this.dispatchEvent(new CustomEvent("copy", { composed: !0, bubbles: !0, cancelable: !0 })) } copy() { navigator.clipboard.writeText(this.getAttribute("value")).then(t => this.fireEvent()).catch(t => console.error(t)) } connectedCallback() { this.copyButton.addEventListener("click", this.copy) } attributeChangedCallback(t, n, o) { if ("value" === t) { const t = this.copyContent.querySelector("slot"); if (!t) return; const n = t.assignedNodes(); n && n.length || (t.textContent = o) } } disconnectedCallback() { this.copyButton.removeEventListener("click", this.copy) } }); -const smForm = document.createElement("template"); smForm.innerHTML = '
', customElements.define("sm-form", class extends HTMLElement { constructor() { super(), this.attachShadow({ mode: "open" }).append(smForm.content.cloneNode(!0)), this.form = this.shadowRoot.querySelector("form"), this.invalidFieldsCount, this.skipSubmit = !1, this.isFormValid = void 0, this.supportedElements = "input, sm-input, sm-textarea, sm-checkbox, tags-input, file-input, sm-switch, sm-radio", this.formElements = [], this._requiredElements = [] } static get observedAttributes() { return ["skip-submit"] } get validity() { return this.isFormValid } debounce = (callback, wait) => { let timeoutId = null; return (...args) => { window.clearTimeout(timeoutId), timeoutId = window.setTimeout((() => { callback.apply(null, args) }), wait) } }; _checkValidity = () => { this.submitButton && 0 !== this._requiredElements.length && (this.invalidFieldsCount = 0, this._requiredElements.forEach((([elem, isWC]) => { (!elem.disabled && isWC && !elem.isValid || !isWC && !elem.checkValidity()) && this.invalidFieldsCount++ })), this.isFormValid !== (0 === this.invalidFieldsCount) && (this.isFormValid = 0 === this.invalidFieldsCount, this.dispatchEvent(new CustomEvent(this.isFormValid ? "valid" : "invalid", { bubbles: !0, composed: !0 })), this.skipSubmit || (this.submitButton.disabled = !this.isFormValid))) }; handleKeydown = e => { if ("Enter" === e.key && e.target.tagName.includes("INPUT")) if (0 === this.invalidFieldsCount) this.submitButton && this.submitButton.click(), this.dispatchEvent(new CustomEvent("submit", { bubbles: !0, composed: !0 })); else for (const [elem, isWC] of this._requiredElements) { if (isWC ? !elem.isValid : !elem.checkValidity()) { (elem?.shadowRoot?.lastElementChild || elem).animate([{ transform: "translateX(-1rem)" }, { transform: "translateX(1rem)" }, { transform: "translateX(-0.5rem)" }, { transform: "translateX(0.5rem)" }, { transform: "translateX(0)" }], { duration: 300, easing: "ease" }), isWC ? (elem.focusIn(), "SM-INPUT" === elem.tagName && "" === elem.value.trim() && elem.showError()) : elem.focus(); break } } }; reset = () => { this.formElements.forEach((([elem, isWC]) => { if (isWC) elem.reset(); else switch (elem.type) { case "checkbox": case "radio": elem.checked = !1; break; default: elem.value = "" } })), this._checkValidity() }; elementsChanged = () => { this.formElements = [...this.querySelectorAll(this.supportedElements)].map((elem => [elem, elem.tagName.includes("-")])), this._requiredElements = this.formElements.filter((([elem]) => elem.hasAttribute("required"))), this.submitButton = this.querySelector('[variant="primary"], [type="submit"]'), this.resetButton = this.querySelector('[type="reset"]'), this.resetButton && this.resetButton.addEventListener("click", this.reset), this._checkValidity() }; connectedCallback() { const updateFormDecedents = this.debounce(this.elementsChanged, 100); this.addEventListener("input", this.debounce(this._checkValidity, 100)), this.addEventListener("keydown", this.debounce(this.handleKeydown, 100)), this.shadowRoot.querySelector("slot").addEventListener("slotchange", updateFormDecedents), this.mutationObserver = new MutationObserver((mutations => { mutations.forEach((mutation => { ("childList" === mutation.type && [...mutation.addedNodes].some((node => 1 === node.nodeType && node.querySelector(this.supportedElements))) || [...mutation.removedNodes].some((node => 1 === node.nodeType && node.querySelector(this.supportedElements)))) && updateFormDecedents() })) })), this.mutationObserver.observe(this, { childList: !0, subtree: !0 }) } attributeChangedCallback(name, oldValue, newValue) { "skip-submit" === name && (this.skipSubmit = null !== newValue) } disconnectedCallback() { this.removeEventListener("input", this.debounce(this._checkValidity, 100)), this.removeEventListener("keydown", this.debounce(this.handleKeydown, 100)), this.mutationObserver.disconnect() } }); +const smForm = document.createElement("template"); smForm.innerHTML = '
', customElements.define("sm-form", class extends HTMLElement { constructor() { super(), this.attachShadow({ mode: "open" }).append(smForm.content.cloneNode(!0)), this.form = this.shadowRoot.querySelector("form"), this.invalidFieldsCount, this.skipSubmit = !1, this.isFormValid = void 0, this.supportedElements = "input, sm-input, sm-textarea, sm-checkbox, tags-input, file-input, sm-switch, sm-radio", this.formElements = [], this._requiredElements = [] } static get observedAttributes() { return ["skip-submit"] } get validity() { return this.isFormValid } debounce = (callback, wait) => { let timeoutId = null; return (...args) => { window.clearTimeout(timeoutId), timeoutId = window.setTimeout((() => { callback.apply(null, args) }), wait) } }; _checkValidity = () => { this.submitButton && 0 !== this._requiredElements.length && (this.invalidFieldsCount = 0, this._requiredElements.forEach((([elem, isWC]) => { (!elem.disabled && isWC && !elem.isValid || !isWC && !elem.checkValidity()) && this.invalidFieldsCount++ })), this.isFormValid !== (0 === this.invalidFieldsCount) && (this.isFormValid = 0 === this.invalidFieldsCount, this.dispatchEvent(new CustomEvent(this.isFormValid ? "valid" : "invalid", { bubbles: !0, composed: !0 })), this.skipSubmit || (this.submitButton.disabled = !this.isFormValid))) }; handleKeydown = e => { if ("Enter" === e.key && e.target.tagName.includes("INPUT")) if (0 === this.invalidFieldsCount) this.submitButton && this.submitButton.click(), this.dispatchEvent(new CustomEvent("submit", { bubbles: !0, composed: !0 })); else for (const [elem, isWC] of this._requiredElements) { if (isWC ? !elem.isValid : !elem.checkValidity()) { (elem?.shadowRoot?.lastElementChild || elem).animate([{ transform: "translateX(-1rem)" }, { transform: "translateX(1rem)" }, { transform: "translateX(-0.5rem)" }, { transform: "translateX(0.5rem)" }, { transform: "translateX(0)" }], { duration: 300, easing: "ease" }), isWC ? (elem.focusIn(), "SM-INPUT" === elem.tagName && "" === elem.value.trim() && elem.showError()) : elem.focus(); break } } }; reset = () => { this.formElements.forEach((([elem, isWC]) => { if (isWC) elem.reset(); else switch (elem.type) { case "checkbox": case "radio": elem.checked = !1; break; default: elem.value = "" } })), this._checkValidity() }; elementsChanged = () => { this.formElements = [...this.querySelectorAll(this.supportedElements)].map((elem => [elem, elem.tagName.includes("-")])), this._requiredElements = this.formElements.filter((([elem]) => elem.hasAttribute("required"))), this.submitButton = this.querySelector('[variant="primary"], [type="submit"]'), this.resetButton = this.querySelector('[type="reset"]'), this.resetButton && this.resetButton.addEventListener("click", this.reset), this._checkValidity() }; checkIfSupported = elem => 1 === elem.nodeType && (elem.tagName.includes("-") || "input" === elem.tagName || elem.querySelector(this.supportedElements)); connectedCallback() { const updateFormDecedents = this.debounce(this.elementsChanged, 100); this.addEventListener("input", this.debounce(this._checkValidity, 100)), this.addEventListener("keydown", this.debounce(this.handleKeydown, 100)), this.shadowRoot.querySelector("slot").addEventListener("slotchange", updateFormDecedents), this.mutationObserver = new MutationObserver((mutations => { mutations.forEach((mutation => { ("childList" === mutation.type && [...mutation.addedNodes].some((node => this.checkIfSupported(node))) || [...mutation.removedNodes].some((node => this.checkIfSupported(node)))) && updateFormDecedents() })) })), this.mutationObserver.observe(this, { childList: !0, subtree: !0 }) } attributeChangedCallback(name, oldValue, newValue) { "skip-submit" === name && (this.skipSubmit = this.hasAttribute("skip-submit")) } disconnectedCallback() { this.removeEventListener("input", this.debounce(this._checkValidity, 100)), this.removeEventListener("keydown", this.debounce(this.handleKeydown, 100)), this.mutationObserver.disconnect() } }); const smInput = document.createElement("template"); smInput.innerHTML = '

', customElements.define("sm-input", class extends HTMLElement { #validationState = { validatedFor: void 0, isValid: !1, errorMessage: "Please fill out this field." }; constructor() { super(), this.attachShadow({ mode: "open" }).append(smInput.content.cloneNode(!0)), this.inputParent = this.shadowRoot.querySelector(".input"), this.input = this.shadowRoot.querySelector("input"), this.clearBtn = this.shadowRoot.querySelector(".clear"), this.label = this.shadowRoot.querySelector(".label"), this.feedbackText = this.shadowRoot.querySelector(".feedback-text"), this.outerContainer = this.shadowRoot.querySelector(".outer-container"), this.optionList = this.shadowRoot.querySelector(".datalist"), this._helperText = "", this.isRequired = !1, this.datalist = [], this.validationFunction = void 0, this.reflectedAttributes = ["value", "required", "disabled", "type", "inputmode", "readonly", "min", "max", "pattern", "minlength", "maxlength", "step", "list", "autocomplete"] } static get observedAttributes() { return ["value", "placeholder", "required", "disabled", "type", "inputmode", "readonly", "min", "max", "pattern", "minlength", "maxlength", "step", "helper-text", "error-text", "list"] } get value() { return this.input.value } set value(val) { val !== this.input.value && (this.input.value = val, this._value = val, this.checkInput()) } get placeholder() { return this.getAttribute("placeholder") } set placeholder(val) { this.setAttribute("placeholder", val) } get type() { return this.getAttribute("type") } set type(val) { this.setAttribute("type", val) } get validity() { return this.input.validity } get disabled() { return this.hasAttribute("disabled") } set disabled(value) { value ? (this.inputParent.classList.add("disabled"), this.setAttribute("disabled", "")) : (this.inputParent.classList.remove("disabled"), this.removeAttribute("disabled")) } get readOnly() { return this.hasAttribute("readonly") } set readOnly(value) { value ? this.setAttribute("readonly", "") : this.removeAttribute("readonly") } set customValidation(val) { val && (this.validationFunction = val) } set errorText(val) { this.#validationState.errorText = val } showError = (errorText = this.#validationState.errorText) => { this.feedbackText.className = "feedback-text error", this.feedbackText.innerHTML = ` ${errorText}` }; set helperText(val) { this._helperText = val } get isValid() { if (this.#validationState.validatedFor === this.input.value) return this.#validationState.isValid; const _isValid = this.input.checkValidity(); let _validity = { isValid: !0, errorText: "" }; return this.validationFunction && (_validity = this.validationFunction(this.input.value)), _isValid && _validity.isValid ? (this.feedbackText.className = "feedback-text success", this.feedbackText.textContent = "") : "" !== this.value.trim() && (_validity.errorText || this.#validationState.errorText) && this.showError(_validity.errorText || this.#validationState.errorText), this.#validationState.validatedFor = this.input.value, this.#validationState.isValid = _isValid && _validity.isValid, this.#validationState.errorText = _validity.errorText || this.#validationState.errorText, this.#validationState.isValid } reset = () => { this.value = "" }; clear = () => { this.value = "", this.input.focus(), this.fireEvent() }; focusIn = () => { this.input.focus() }; focusOut = () => { this.input.blur() }; fireEvent = () => { let event = new Event("input", { bubbles: !0, cancelable: !0, composed: !0 }); this.dispatchEvent(event) }; searchDatalist = searchKey => { const filteredData = this.datalist.filter((item => item.toLowerCase().includes(searchKey.toLowerCase()))); if (filteredData.sort(((a, b) => a.toLowerCase().indexOf(searchKey.toLowerCase()) - b.toLowerCase().indexOf(searchKey.toLowerCase()))), filteredData.length) { if (this.optionList.children.length > filteredData.length) { const optionsToRemove = this.optionList.children.length - filteredData.length; for (let i = 0; i < optionsToRemove; i++)this.optionList.removeChild(this.optionList.lastChild) } filteredData.forEach(((item, index) => { if (this.optionList.children[index]) this.optionList.children[index].textContent = item; else { const option = document.createElement("li"); option.textContent = item, option.classList.add("datalist-item"), option.setAttribute("tabindex", "0"), this.optionList.appendChild(option) } })), this.optionList.classList.remove("hidden") } else this.optionList.classList.add("hidden") }; checkInput = e => { this.hasAttribute("readonly") || ("" !== this.input.value ? this.clearBtn.classList.remove("hidden") : this.clearBtn.classList.add("hidden")), this.hasAttribute("placeholder") && "" !== this.getAttribute("placeholder").trim() && ("" !== this.input.value ? (this.shouldAnimateLabel && this.inputParent.classList.add("animate-placeholder"), this.label.classList.toggle("hidden", !this.shouldAnimateLabel), this.datalist.length && (this.searchTimeout && clearTimeout(this.searchTimeout), this.searchTimeout = setTimeout((() => { this.searchDatalist(this.input.value.trim()) }), 100))) : (this.shouldAnimateLabel && this.inputParent.classList.remove("animate-placeholder"), this.label.classList.remove("hidden"), this.feedbackText.textContent = "", this.datalist.length && (this.optionList.innerHTML = "", this.optionList.classList.add("hidden")))) }; allowOnlyNum = e => { e.ctrlKey || 1 === e.key.length && (("." !== e.key || !e.target.value.includes(".") && 0 !== e.target.value.length) && ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "."].includes(e.key) || e.preventDefault()) }; handleOptionClick = e => { this.input.value = e.target.textContent, this.optionList.classList.add("hidden"), this.input.focus() }; handleInputNavigation = e => { "ArrowDown" === e.key ? (e.preventDefault(), this.optionList.children.length && this.optionList.children[0].focus()) : "ArrowUp" === e.key && (e.preventDefault(), this.optionList.children.length && this.optionList.children[this.optionList.children.length - 1].focus()) }; handleDatalistNavigation = e => { "ArrowUp" === e.key ? (e.preventDefault(), this.shadowRoot.activeElement.previousElementSibling ? this.shadowRoot.activeElement.previousElementSibling.focus() : this.input.focus()) : "ArrowDown" === e.key ? (e.preventDefault(), this.shadowRoot.activeElement.nextElementSibling ? this.shadowRoot.activeElement.nextElementSibling.focus() : this.input.focus()) : "Enter" !== e.key && " " !== e.key || (e.preventDefault(), this.input.value = e.target.textContent, this.optionList.classList.add("hidden"), this.input.focus()) }; handleFocus = e => { this.datalist.length && this.searchDatalist(this.input.value.trim()) }; handleBlur = e => { this.datalist.length && this.optionList.classList.add("hidden") }; connectedCallback() { const uuid = crypto.randomUUID(); if (this.input.id = uuid, this.label.htmlFor = uuid, this.shouldAnimateLabel = this.hasAttribute("animate"), this.shouldAnimateLabel && "" !== this.placeholder && this.value && (this.inputParent.classList.add("animate-placeholder"), this.label.classList.remove("hidden")), this.setAttribute("role", "textbox"), "undefined" != typeof smCompConfig && smCompConfig["sm-input"]) { const config = smCompConfig["sm-input"].find((config => this.matches(config.selector))); this.customValidation = config?.customValidation } this.input.addEventListener("input", this.checkInput), this.clearBtn.addEventListener("click", this.clear), this.datalist.length && (this.optionList.addEventListener("click", this.handleOptionClick), this.input.addEventListener("keydown", this.handleInputNavigation), this.optionList.addEventListener("keydown", this.handleDatalistNavigation)), this.input.addEventListener("focusin", this.handleFocus), this.addEventListener("focusout", this.handleBlur) } attributeChangedCallback(name, oldValue, newValue) { if (oldValue !== newValue) switch (this.reflectedAttributes.includes(name) && (this.hasAttribute(name) ? this.input.setAttribute(name, this.getAttribute(name) ? this.getAttribute(name) : "") : this.input.removeAttribute(name)), name) { case "placeholder": this.label.textContent = newValue, this.setAttribute("aria-label", newValue); break; case "value": this.checkInput(); break; case "type": this.hasAttribute("type") && "number" === this.getAttribute("type") ? (this.input.setAttribute("inputmode", "decimal"), this.input.addEventListener("keydown", this.allowOnlyNum)) : this.input.removeEventListener("keydown", this.allowOnlyNum); break; case "helper-text": this._helperText = newValue; break; case "error-text": this.#validationState.errorText = newValue; break; case "required": this.isRequired = this.hasAttribute("required"), this.isRequired ? this.setAttribute("aria-required", "true") : this.setAttribute("aria-required", "false"); break; case "readonly": this.hasAttribute("readonly") ? this.inputParent.classList.add("readonly") : this.inputParent.classList.remove("readonly"); break; case "disabled": this.hasAttribute("disabled") ? this.inputParent.classList.add("disabled") : this.inputParent.classList.remove("disabled"); break; case "list": this.hasAttribute("list") && "" !== this.getAttribute("list").trim() && (this.datalist = this.getAttribute("list").split(",")) } } disconnectedCallback() { this.input.removeEventListener("input", this.checkInput), this.clearBtn.removeEventListener("click", this.clear), this.input.removeEventListener("keydown", this.allowOnlyNum), this.optionList.removeEventListener("click", this.handleOptionClick), this.input.removeEventListener("keydown", this.handleInputNavigation), this.optionList.removeEventListener("keydown", this.handleDatalistNavigation), this.input.removeEventListener("focusin", this.handleFocus), this.removeEventListener("focusout", this.handleBlur) } }); const smMenu = document.createElement("template"); smMenu.innerHTML = '
', customElements.define("sm-menu", class extends HTMLElement { constructor() { super(), this.attachShadow({ mode: "open" }).append(smMenu.content.cloneNode(!0)), this.isOpen = !1, this.availableOptions, this.containerDimensions, this.animOptions = { duration: 200, easing: "ease" }, this.optionList = this.shadowRoot.querySelector(".options"), this.menu = this.shadowRoot.querySelector(".menu"), this.icon = this.shadowRoot.querySelector(".icon"), this.expand = this.expand.bind(this), this.collapse = this.collapse.bind(this), this.toggle = this.toggle.bind(this), this.handleKeyDown = this.handleKeyDown.bind(this), this.handleClick = this.handleClick.bind(this), this.handleClickOutside = this.handleClickOutside.bind(this) } static get observedAttributes() { return ["value"] } get value() { return this.getAttribute("value") } set value(n) { this.setAttribute("value", n) } expand() { this.isOpen || (this.optionList.classList.remove("hide"), this.optionList.animate([{ transform: "translateY(-1rem)", opacity: "0" }, { transform: "none", opacity: "1" }], this.animOptions).onfinish = (() => { this.isOpen = !0, this.icon.classList.add("focused"), document.addEventListener("mousedown", this.handleClickOutside); const n = this.optionList.firstElementChild.assignedElements().find(n => "MENU-OPTION" === n.tagName); n && n.focus() })) } collapse() { this.isOpen && (this.optionList.animate([{ transform: "none", opacity: "1" }, { transform: "translateY(-1rem)", opacity: "0" }], this.animOptions).onfinish = (() => { this.isOpen = !1, this.icon.classList.remove("focused"), this.optionList.classList.add("hide"), document.removeEventListener("mousedown", this.handleClickOutside) })) } toggle() { this.isOpen ? this.collapse() : this.expand() } handleClick(n) { n.target === this ? this.toggle() : this.collapse() } handleKeyDown(n) { n.target === this ? "ArrowDown" === n.key ? (n.preventDefault(), this.availableOptions[0].focus()) : " " === n.key && (n.preventDefault(), this.toggle()) : "ArrowUp" === n.key ? (n.preventDefault(), document.activeElement.previousElementSibling ? document.activeElement.previousElementSibling.focus() : this.availableOptions[this.availableOptions.length - 1].focus()) : "ArrowDown" === n.key ? (n.preventDefault(), document.activeElement.nextElementSibling ? document.activeElement.nextElementSibling.focus() : this.availableOptions[0].focus()) : "Enter" !== n.key && " " !== n.key || (n.preventDefault(), n.target.click(), this.collapse(), this.menu.focus()) } handleClickOutside(n) { this.contains(n.target) || 2 === n.button || this.collapse() } connectedCallback() { this.setAttribute("role", "listbox"), this.setAttribute("aria-label", "dropdown menu"); const n = this.shadowRoot.querySelector(".options slot"); n.addEventListener("slotchange", n => { this.availableOptions = n.target.assignedElements(), this.containerDimensions = this.optionList.getBoundingClientRect() }), this.addEventListener("click", this.handleClick), this.addEventListener("keydown", this.handleKeyDown) } disconnectedCallback() { this.removeEventListener("click", this.handleClick), this.removeEventListener("keydown", this.handleKeyDown), document.removeEventListener("mousedown", this.handleClickOutside) } }); const menuOption = document.createElement("template"); menuOption.innerHTML = '
', customElements.define("menu-option", class extends HTMLElement { constructor() { super(), this.attachShadow({ mode: "open" }).append(menuOption.content.cloneNode(!0)) } connectedCallback() { this.setAttribute("role", "option"), this.setAttribute("tabindex", "0"), this.addEventListener("keyup", n => { "Enter" !== n.key && " " !== n.key || (n.preventDefault(), this.click()) }) } }); const smNotifications = document.createElement("template"); smNotifications.innerHTML = "
", customElements.define("sm-notifications", class extends HTMLElement { constructor() { super(), this.shadow = this.attachShadow({ mode: "open" }).append(smNotifications.content.cloneNode(!0)), this.notificationPanel = this.shadowRoot.querySelector(".notification-panel"), this.animationOptions = { duration: 300, fill: "forwards", easing: "cubic-bezier(0.175, 0.885, 0.32, 1.275)" }, this.push = this.push.bind(this), this.createNotification = this.createNotification.bind(this), this.removeNotification = this.removeNotification.bind(this), this.clearAll = this.clearAll.bind(this), this.remove = this.remove.bind(this), this.handleTouchMove = this.handleTouchMove.bind(this), this.startX = 0, this.currentX = 0, this.endX = 0, this.swipeDistance = 0, this.swipeDirection = "", this.swipeThreshold = 0, this.startTime = 0, this.swipeTime = 0, this.swipeTimeThreshold = 200, this.currentTarget = null, this.notificationTimeout = 5e3, this.mediaQuery = window.matchMedia("(min-width: 640px)"), this.handleOrientationChange = this.handleOrientationChange.bind(this), this.isBigViewport = !1 } set timeout(value) { isNaN(value) || (this.notificationTimeout = value) } randString(length) { let result = ""; const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; for (let i = 0; i < length; i++)result += characters.charAt(Math.floor(52 * Math.random())); return result } createNotification(message, options = {}) { const { pinned: pinned = !1, icon: icon, action: action, timeout: timeout = this.notificationTimeout } = options, notification = document.createElement("div"); return notification.id = this.randString(8), notification.className = "notification " + (pinned ? "pinned" : ""), notification.style.setProperty("--timeout", `${timeout}ms`), notification.innerHTML = ` ${icon ? `
${icon}
` : ""} ${message} ${action ? `` : ""} `, action && notification.querySelector(".action").addEventListener("click", action.callback), notification.querySelector(".close").addEventListener("click", (() => { this.removeNotification(notification) })), pinned || setTimeout((() => { this.removeNotification(notification, this.isBigViewport ? "left" : "top") }), timeout), notification } push(message, options = {}) { const notification = this.createNotification(message, options); return this.isBigViewport ? this.notificationPanel.append(notification) : this.notificationPanel.prepend(notification), notification.scrollIntoView({ behavior: "smooth" }), this.notificationPanel.animate([{ transform: `translateY(${this.isBigViewport ? "" : "-"}${notification.clientHeight}px)` }, { transform: "none" }], this.animationOptions), notification.animate([{ transform: "translateY(-1rem)", opacity: "0" }, { transform: "none", opacity: "1" }], this.animationOptions).onfinish = e => { e.target.commitStyles(), e.target.cancel() }, notification.id } removeNotification(notification, direction = "left") { if (!notification) return; const sign = "left" === direction || "top" === direction ? "-" : "+"; this.isBigViewport || "top" !== direction ? notification.animate([{ transform: this.currentX ? `translateX(${this.currentX}px)` : "none", opacity: "1" }, { transform: `translateX(calc(${sign}${Math.abs(this.currentX)}px ${sign} 1rem))`, opacity: "0" }], this.animationOptions).onfinish = () => { notification.remove() } : notification.animate([{ transform: this.currentX ? `translateY(${this.currentX}px)` : "none", opacity: "1" }, { transform: `translateY(calc(${sign}${Math.abs(this.currentX)}px ${sign} 1rem))`, opacity: "0" }], this.animationOptions).onfinish = () => { notification.remove() } } remove(id) { const notification = this.notificationPanel.querySelector(`#${id}`); notification && this.removeNotification(notification) } clearAll() { Array.from(this.notificationPanel.children).forEach((child => { this.removeNotification(child) })) } handleTouchMove(e) { this.currentX = e.touches[0].clientX - this.startX, this.currentTarget.style.transform = `translateX(${this.currentX}px)` } handleOrientationChange(e) { this.isBigViewport = e.matches, e.matches } connectedCallback() { this.handleOrientationChange(this.mediaQuery), this.mediaQuery.addEventListener("change", this.handleOrientationChange), this.notificationPanel.addEventListener("touchstart", (e => { e.target.closest(".close") ? this.removeNotification(e.target.closest(".notification")) : e.target.closest(".notification") && (this.swipeThreshold = e.target.closest(".notification").getBoundingClientRect().width / 2, this.currentTarget = e.target.closest(".notification"), this.startTime = Date.now(), this.startX = e.touches[0].clientX, this.startY = e.touches[0].clientY, this.notificationPanel.addEventListener("touchmove", this.handleTouchMove, { passive: !0 })) }), { passive: !0 }), this.notificationPanel.addEventListener("touchend", (e => { this.endX = e.changedTouches[0].clientX, this.endY = e.changedTouches[0].clientY, this.swipeDistance = Math.abs(this.endX - this.startX), this.swipeTime = Date.now() - this.startTime, this.endX > this.startX ? this.swipeDirection = "right" : this.swipeDirection = "left", this.swipeTime < this.swipeTimeThreshold ? this.swipeDistance > 50 && this.removeNotification(this.currentTarget, this.swipeDirection) : this.swipeDistance > this.swipeThreshold ? this.removeNotification(this.currentTarget, this.swipeDirection) : this.currentTarget.animate([{ transform: `translateX(${this.currentX}px)` }, { transform: "none" }], this.animationOptions).onfinish = e => { e.target.commitStyles(), e.target.cancel() }, this.notificationPanel.removeEventListener("touchmove", this.handleTouchMove), this.currentX = 0 })) } disconnectedCallback() { mediaQueryList.removeEventListener("change", handleOrientationChange) } }); diff --git a/scripts/components.min.js b/scripts/components.min.js index ca116d1..60156f0 100644 --- a/scripts/components.min.js +++ b/scripts/components.min.js @@ -1 +1 @@ -const smChips=document.createElement("template");smChips.innerHTML='
',customElements.define("sm-chips",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).append(smChips.content.cloneNode(!0)),this.chipsWrapper=this.shadowRoot.querySelector(".sm-chips"),this.coverLeft=this.shadowRoot.querySelector(".cover--left"),this.coverRight=this.shadowRoot.querySelector(".cover--right"),this.navButtonLeft=this.shadowRoot.querySelector(".nav-button--left"),this.navButtonRight=this.shadowRoot.querySelector(".nav-button--right"),this.slottedOptions=void 0,this._value=void 0,this.scrollDistance=0,this.assignedElements=[],this.scrollLeft=this.scrollLeft.bind(this),this.scrollRight=this.scrollRight.bind(this),this.fireEvent=this.fireEvent.bind(this),this.setSelectedOption=this.setSelectedOption.bind(this)}get value(){return this._value}set value(t){this.setSelectedOption(t)}scrollLeft(){this.chipsWrapper.scrollBy({left:-this.scrollDistance,behavior:"smooth"})}scrollRight(){this.chipsWrapper.scrollBy({left:this.scrollDistance,behavior:"smooth"})}setSelectedOption(t){this._value!==t&&(this._value=t,this.assignedElements.forEach((e=>{e.value==t?(e.setAttribute("selected",""),e.scrollIntoView({behavior:"smooth",block:"nearest",inline:"center"})):e.removeAttribute("selected")})))}fireEvent(){this.dispatchEvent(new CustomEvent("change",{bubbles:!0,composed:!0,detail:{value:this._value}}))}connectedCallback(){this.setAttribute("role","listbox");const t=this.shadowRoot.querySelector("slot");t.addEventListener("slotchange",(e=>{n.disconnect(),i.disconnect(),this.observeSelf.disconnect(),clearTimeout(this.slotChangeTimeout),this.slotChangeTimeout=setTimeout((()=>{this.assignedElements=t.assignedElements(),this.assignedElements.forEach((t=>{t.hasAttribute("selected")&&(this._value=t.value)})),this.observeSelf.observe(this)}),0)}));const e=new ResizeObserver((t=>{t.forEach((t=>{if(t.contentBoxSize){const e=Array.isArray(t.contentBoxSize)?t.contentBoxSize[0]:t.contentBoxSize;this.scrollDistance=.6*e.inlineSize}else this.scrollDistance=.6*t.contentRect.width}))}));e.observe(this),this.observeSelf=new IntersectionObserver(((t,e)=>{t.forEach((t=>{t.isIntersecting&&!this.hasAttribute("multiline")&&this.assignedElements.length>0&&(n.observe(this.assignedElements[0]),i.observe(this.assignedElements[this.assignedElements.length-1]),e.unobserve(this))}))}),{threshold:1}),this.chipsWrapper.addEventListener("option-clicked",(t=>{this._value!==t.target.value&&(this.setSelectedOption(t.target.value),this.fireEvent())}));const n=new IntersectionObserver((t=>{t.forEach((t=>{t.isIntersecting?(this.navButtonLeft.classList.add("hide"),this.coverLeft.classList.add("hide")):(this.navButtonLeft.classList.remove("hide"),this.coverLeft.classList.remove("hide"))}))}),{threshold:1,root:this}),i=new IntersectionObserver((t=>{t.forEach((t=>{t.isIntersecting?(this.navButtonRight.classList.add("hide"),this.coverRight.classList.add("hide")):(this.navButtonRight.classList.remove("hide"),this.coverRight.classList.remove("hide"))}))}),{threshold:1,root:this});this.navButtonLeft.addEventListener("click",this.scrollLeft),this.navButtonRight.addEventListener("click",this.scrollRight)}disconnectedCallback(){this.navButtonLeft.removeEventListener("click",this.scrollLeft),this.navButtonRight.removeEventListener("click",this.scrollRight)}});const smChip=document.createElement("template");smChip.innerHTML=' ',customElements.define("sm-chip",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).append(smChip.content.cloneNode(!0)),this._value=void 0,this.radioButton=this.shadowRoot.querySelector("input"),this.fireEvent=this.fireEvent.bind(this),this.handleKeyDown=this.handleKeyDown.bind(this)}get value(){return this._value}fireEvent(){this.dispatchEvent(new CustomEvent("option-clicked",{bubbles:!0,composed:!0,detail:{value:this._value}}))}handleKeyDown(t){"Enter"!==t.key&&"Space"!==t.key||this.fireEvent()}connectedCallback(){this.setAttribute("role","option"),this.setAttribute("tabindex","0"),this._value=this.getAttribute("value"),this.addEventListener("click",this.fireEvent),this.addEventListener("keydown",this.handleKeyDown)}disconnectedCallback(){this.removeEventListener("click",this.fireEvent),this.removeEventListener("keydown",this.handleKeyDown)}});const smCopy=document.createElement("template");smCopy.innerHTML='

',customElements.define("sm-copy",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).append(smCopy.content.cloneNode(!0)),this.copyContent=this.shadowRoot.querySelector(".copy-content"),this.copyButton=this.shadowRoot.querySelector(".copy-button"),this.copy=this.copy.bind(this)}static get observedAttributes(){return["value"]}set value(t){this.setAttribute("value",t)}get value(){return this.getAttribute("value")}fireEvent(){this.dispatchEvent(new CustomEvent("copy",{composed:!0,bubbles:!0,cancelable:!0}))}copy(){navigator.clipboard.writeText(this.getAttribute("value")).then((t=>this.fireEvent())).catch((t=>console.error(t)))}connectedCallback(){this.copyButton.addEventListener("click",this.copy)}attributeChangedCallback(t,n,o){if("value"===t){const t=this.copyContent.querySelector("slot");if(!t)return;const n=t.assignedNodes();n&&n.length||(t.textContent=o)}}disconnectedCallback(){this.copyButton.removeEventListener("click",this.copy)}});const smForm=document.createElement("template");smForm.innerHTML='
',customElements.define("sm-form",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).append(smForm.content.cloneNode(!0)),this.form=this.shadowRoot.querySelector("form"),this.invalidFieldsCount,this.skipSubmit=!1,this.isFormValid=void 0,this.supportedElements="input, sm-input, sm-textarea, sm-checkbox, tags-input, file-input, sm-switch, sm-radio",this.formElements=[],this._requiredElements=[]}static get observedAttributes(){return["skip-submit"]}get validity(){return this.isFormValid}debounce=(callback,wait)=>{let timeoutId=null;return(...args)=>{window.clearTimeout(timeoutId),timeoutId=window.setTimeout((()=>{callback.apply(null,args)}),wait)}};_checkValidity=()=>{this.submitButton&&0!==this._requiredElements.length&&(this.invalidFieldsCount=0,this._requiredElements.forEach((([elem,isWC])=>{(!elem.disabled&&isWC&&!elem.isValid||!isWC&&!elem.checkValidity())&&this.invalidFieldsCount++})),this.isFormValid!==(0===this.invalidFieldsCount)&&(this.isFormValid=0===this.invalidFieldsCount,this.dispatchEvent(new CustomEvent(this.isFormValid?"valid":"invalid",{bubbles:!0,composed:!0})),this.skipSubmit||(this.submitButton.disabled=!this.isFormValid)))};handleKeydown=e=>{if("Enter"===e.key&&e.target.tagName.includes("INPUT"))if(0===this.invalidFieldsCount)this.submitButton&&this.submitButton.click(),this.dispatchEvent(new CustomEvent("submit",{bubbles:!0,composed:!0}));else for(const[elem,isWC]of this._requiredElements)if(isWC?!elem.isValid:!elem.checkValidity()){(elem?.shadowRoot?.lastElementChild||elem).animate([{transform:"translateX(-1rem)"},{transform:"translateX(1rem)"},{transform:"translateX(-0.5rem)"},{transform:"translateX(0.5rem)"},{transform:"translateX(0)"}],{duration:300,easing:"ease"}),isWC?(elem.focusIn(),"SM-INPUT"===elem.tagName&&""===elem.value.trim()&&elem.showError()):elem.focus();break}};reset=()=>{this.formElements.forEach((([elem,isWC])=>{if(isWC)elem.reset();else switch(elem.type){case"checkbox":case"radio":elem.checked=!1;break;default:elem.value=""}})),this._checkValidity()};elementsChanged=()=>{this.formElements=[...this.querySelectorAll(this.supportedElements)].map((elem=>[elem,elem.tagName.includes("-")])),this._requiredElements=this.formElements.filter((([elem])=>elem.hasAttribute("required"))),this.submitButton=this.querySelector('[variant="primary"], [type="submit"]'),this.resetButton=this.querySelector('[type="reset"]'),this.resetButton&&this.resetButton.addEventListener("click",this.reset),this._checkValidity()};connectedCallback(){const updateFormDecedents=this.debounce(this.elementsChanged,100);this.addEventListener("input",this.debounce(this._checkValidity,100)),this.addEventListener("keydown",this.debounce(this.handleKeydown,100)),this.shadowRoot.querySelector("slot").addEventListener("slotchange",updateFormDecedents),this.mutationObserver=new MutationObserver((mutations=>{mutations.forEach((mutation=>{("childList"===mutation.type&&[...mutation.addedNodes].some((node=>1===node.nodeType&&node.querySelector(this.supportedElements)))||[...mutation.removedNodes].some((node=>1===node.nodeType&&node.querySelector(this.supportedElements))))&&updateFormDecedents()}))})),this.mutationObserver.observe(this,{childList:!0,subtree:!0})}attributeChangedCallback(name,oldValue,newValue){"skip-submit"===name&&(this.skipSubmit=null!==newValue)}disconnectedCallback(){this.removeEventListener("input",this.debounce(this._checkValidity,100)),this.removeEventListener("keydown",this.debounce(this.handleKeydown,100)),this.mutationObserver.disconnect()}});const smInput=document.createElement("template");smInput.innerHTML='

',customElements.define("sm-input",class extends HTMLElement{#validationState={validatedFor:void 0,isValid:!1,errorMessage:"Please fill out this field."};constructor(){super(),this.attachShadow({mode:"open"}).append(smInput.content.cloneNode(!0)),this.inputParent=this.shadowRoot.querySelector(".input"),this.input=this.shadowRoot.querySelector("input"),this.clearBtn=this.shadowRoot.querySelector(".clear"),this.label=this.shadowRoot.querySelector(".label"),this.feedbackText=this.shadowRoot.querySelector(".feedback-text"),this.outerContainer=this.shadowRoot.querySelector(".outer-container"),this.optionList=this.shadowRoot.querySelector(".datalist"),this._helperText="",this.isRequired=!1,this.datalist=[],this.validationFunction=void 0,this.reflectedAttributes=["value","required","disabled","type","inputmode","readonly","min","max","pattern","minlength","maxlength","step","list","autocomplete"]}static get observedAttributes(){return["value","placeholder","required","disabled","type","inputmode","readonly","min","max","pattern","minlength","maxlength","step","helper-text","error-text","list"]}get value(){return this.input.value}set value(val){val!==this.input.value&&(this.input.value=val,this._value=val,this.checkInput())}get placeholder(){return this.getAttribute("placeholder")}set placeholder(val){this.setAttribute("placeholder",val)}get type(){return this.getAttribute("type")}set type(val){this.setAttribute("type",val)}get validity(){return this.input.validity}get disabled(){return this.hasAttribute("disabled")}set disabled(value){value?(this.inputParent.classList.add("disabled"),this.setAttribute("disabled","")):(this.inputParent.classList.remove("disabled"),this.removeAttribute("disabled"))}get readOnly(){return this.hasAttribute("readonly")}set readOnly(value){value?this.setAttribute("readonly",""):this.removeAttribute("readonly")}set customValidation(val){val&&(this.validationFunction=val)}set errorText(val){this.#validationState.errorText=val}showError=(errorText=this.#validationState.errorText)=>{this.feedbackText.className="feedback-text error",this.feedbackText.innerHTML=` ${errorText}`};set helperText(val){this._helperText=val}get isValid(){if(this.#validationState.validatedFor===this.input.value)return this.#validationState.isValid;const _isValid=this.input.checkValidity();let _validity={isValid:!0,errorText:""};return this.validationFunction&&(_validity=this.validationFunction(this.input.value)),_isValid&&_validity.isValid?(this.feedbackText.className="feedback-text success",this.feedbackText.textContent=""):""!==this.value.trim()&&(_validity.errorText||this.#validationState.errorText)&&this.showError(_validity.errorText||this.#validationState.errorText),this.#validationState.validatedFor=this.input.value,this.#validationState.isValid=_isValid&&_validity.isValid,this.#validationState.errorText=_validity.errorText||this.#validationState.errorText,this.#validationState.isValid}reset=()=>{this.value=""};clear=()=>{this.value="",this.input.focus(),this.fireEvent()};focusIn=()=>{this.input.focus()};focusOut=()=>{this.input.blur()};fireEvent=()=>{let event=new Event("input",{bubbles:!0,cancelable:!0,composed:!0});this.dispatchEvent(event)};searchDatalist=searchKey=>{const filteredData=this.datalist.filter((item=>item.toLowerCase().includes(searchKey.toLowerCase())));if(filteredData.sort(((a,b)=>a.toLowerCase().indexOf(searchKey.toLowerCase())-b.toLowerCase().indexOf(searchKey.toLowerCase()))),filteredData.length){if(this.optionList.children.length>filteredData.length){const optionsToRemove=this.optionList.children.length-filteredData.length;for(let i=0;i{if(this.optionList.children[index])this.optionList.children[index].textContent=item;else{const option=document.createElement("li");option.textContent=item,option.classList.add("datalist-item"),option.setAttribute("tabindex","0"),this.optionList.appendChild(option)}})),this.optionList.classList.remove("hidden")}else this.optionList.classList.add("hidden")};checkInput=e=>{this.hasAttribute("readonly")||(""!==this.input.value?this.clearBtn.classList.remove("hidden"):this.clearBtn.classList.add("hidden")),this.hasAttribute("placeholder")&&""!==this.getAttribute("placeholder").trim()&&(""!==this.input.value?(this.shouldAnimateLabel&&this.inputParent.classList.add("animate-placeholder"),this.label.classList.toggle("hidden",!this.shouldAnimateLabel),this.datalist.length&&(this.searchTimeout&&clearTimeout(this.searchTimeout),this.searchTimeout=setTimeout((()=>{this.searchDatalist(this.input.value.trim())}),100))):(this.shouldAnimateLabel&&this.inputParent.classList.remove("animate-placeholder"),this.label.classList.remove("hidden"),this.feedbackText.textContent="",this.datalist.length&&(this.optionList.innerHTML="",this.optionList.classList.add("hidden"))))};allowOnlyNum=e=>{e.ctrlKey||1===e.key.length&&(("."!==e.key||!e.target.value.includes(".")&&0!==e.target.value.length)&&["0","1","2","3","4","5","6","7","8","9","."].includes(e.key)||e.preventDefault())};handleOptionClick=e=>{this.input.value=e.target.textContent,this.optionList.classList.add("hidden"),this.input.focus()};handleInputNavigation=e=>{"ArrowDown"===e.key?(e.preventDefault(),this.optionList.children.length&&this.optionList.children[0].focus()):"ArrowUp"===e.key&&(e.preventDefault(),this.optionList.children.length&&this.optionList.children[this.optionList.children.length-1].focus())};handleDatalistNavigation=e=>{"ArrowUp"===e.key?(e.preventDefault(),this.shadowRoot.activeElement.previousElementSibling?this.shadowRoot.activeElement.previousElementSibling.focus():this.input.focus()):"ArrowDown"===e.key?(e.preventDefault(),this.shadowRoot.activeElement.nextElementSibling?this.shadowRoot.activeElement.nextElementSibling.focus():this.input.focus()):"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),this.input.value=e.target.textContent,this.optionList.classList.add("hidden"),this.input.focus())};handleFocus=e=>{this.datalist.length&&this.searchDatalist(this.input.value.trim())};handleBlur=e=>{this.datalist.length&&this.optionList.classList.add("hidden")};connectedCallback(){const uuid=crypto.randomUUID();if(this.input.id=uuid,this.label.htmlFor=uuid,this.shouldAnimateLabel=this.hasAttribute("animate"),this.shouldAnimateLabel&&""!==this.placeholder&&this.value&&(this.inputParent.classList.add("animate-placeholder"),this.label.classList.remove("hidden")),this.setAttribute("role","textbox"),"undefined"!=typeof smCompConfig&&smCompConfig["sm-input"]){const config=smCompConfig["sm-input"].find((config=>this.matches(config.selector)));this.customValidation=config?.customValidation}this.input.addEventListener("input",this.checkInput),this.clearBtn.addEventListener("click",this.clear),this.datalist.length&&(this.optionList.addEventListener("click",this.handleOptionClick),this.input.addEventListener("keydown",this.handleInputNavigation),this.optionList.addEventListener("keydown",this.handleDatalistNavigation)),this.input.addEventListener("focusin",this.handleFocus),this.addEventListener("focusout",this.handleBlur)}attributeChangedCallback(name,oldValue,newValue){if(oldValue!==newValue)switch(this.reflectedAttributes.includes(name)&&(this.hasAttribute(name)?this.input.setAttribute(name,this.getAttribute(name)?this.getAttribute(name):""):this.input.removeAttribute(name)),name){case"placeholder":this.label.textContent=newValue,this.setAttribute("aria-label",newValue);break;case"value":this.checkInput();break;case"type":this.hasAttribute("type")&&"number"===this.getAttribute("type")?(this.input.setAttribute("inputmode","decimal"),this.input.addEventListener("keydown",this.allowOnlyNum)):this.input.removeEventListener("keydown",this.allowOnlyNum);break;case"helper-text":this._helperText=newValue;break;case"error-text":this.#validationState.errorText=newValue;break;case"required":this.isRequired=this.hasAttribute("required"),this.isRequired?this.setAttribute("aria-required","true"):this.setAttribute("aria-required","false");break;case"readonly":this.hasAttribute("readonly")?this.inputParent.classList.add("readonly"):this.inputParent.classList.remove("readonly");break;case"disabled":this.hasAttribute("disabled")?this.inputParent.classList.add("disabled"):this.inputParent.classList.remove("disabled");break;case"list":this.hasAttribute("list")&&""!==this.getAttribute("list").trim()&&(this.datalist=this.getAttribute("list").split(","))}}disconnectedCallback(){this.input.removeEventListener("input",this.checkInput),this.clearBtn.removeEventListener("click",this.clear),this.input.removeEventListener("keydown",this.allowOnlyNum),this.optionList.removeEventListener("click",this.handleOptionClick),this.input.removeEventListener("keydown",this.handleInputNavigation),this.optionList.removeEventListener("keydown",this.handleDatalistNavigation),this.input.removeEventListener("focusin",this.handleFocus),this.removeEventListener("focusout",this.handleBlur)}});const smMenu=document.createElement("template");smMenu.innerHTML='
',customElements.define("sm-menu",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).append(smMenu.content.cloneNode(!0)),this.isOpen=!1,this.availableOptions,this.containerDimensions,this.animOptions={duration:200,easing:"ease"},this.optionList=this.shadowRoot.querySelector(".options"),this.menu=this.shadowRoot.querySelector(".menu"),this.icon=this.shadowRoot.querySelector(".icon"),this.expand=this.expand.bind(this),this.collapse=this.collapse.bind(this),this.toggle=this.toggle.bind(this),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleClick=this.handleClick.bind(this),this.handleClickOutside=this.handleClickOutside.bind(this)}static get observedAttributes(){return["value"]}get value(){return this.getAttribute("value")}set value(n){this.setAttribute("value",n)}expand(){this.isOpen||(this.optionList.classList.remove("hide"),this.optionList.animate([{transform:"translateY(-1rem)",opacity:"0"},{transform:"none",opacity:"1"}],this.animOptions).onfinish=()=>{this.isOpen=!0,this.icon.classList.add("focused"),document.addEventListener("mousedown",this.handleClickOutside);const n=this.optionList.firstElementChild.assignedElements().find((n=>"MENU-OPTION"===n.tagName));n&&n.focus()})}collapse(){this.isOpen&&(this.optionList.animate([{transform:"none",opacity:"1"},{transform:"translateY(-1rem)",opacity:"0"}],this.animOptions).onfinish=()=>{this.isOpen=!1,this.icon.classList.remove("focused"),this.optionList.classList.add("hide"),document.removeEventListener("mousedown",this.handleClickOutside)})}toggle(){this.isOpen?this.collapse():this.expand()}handleClick(n){n.target===this?this.toggle():this.collapse()}handleKeyDown(n){n.target===this?"ArrowDown"===n.key?(n.preventDefault(),this.availableOptions[0].focus()):" "===n.key&&(n.preventDefault(),this.toggle()):"ArrowUp"===n.key?(n.preventDefault(),document.activeElement.previousElementSibling?document.activeElement.previousElementSibling.focus():this.availableOptions[this.availableOptions.length-1].focus()):"ArrowDown"===n.key?(n.preventDefault(),document.activeElement.nextElementSibling?document.activeElement.nextElementSibling.focus():this.availableOptions[0].focus()):"Enter"!==n.key&&" "!==n.key||(n.preventDefault(),n.target.click(),this.collapse(),this.menu.focus())}handleClickOutside(n){this.contains(n.target)||2===n.button||this.collapse()}connectedCallback(){this.setAttribute("role","listbox"),this.setAttribute("aria-label","dropdown menu");this.shadowRoot.querySelector(".options slot").addEventListener("slotchange",(n=>{this.availableOptions=n.target.assignedElements(),this.containerDimensions=this.optionList.getBoundingClientRect()})),this.addEventListener("click",this.handleClick),this.addEventListener("keydown",this.handleKeyDown)}disconnectedCallback(){this.removeEventListener("click",this.handleClick),this.removeEventListener("keydown",this.handleKeyDown),document.removeEventListener("mousedown",this.handleClickOutside)}});const menuOption=document.createElement("template");menuOption.innerHTML='
',customElements.define("menu-option",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).append(menuOption.content.cloneNode(!0))}connectedCallback(){this.setAttribute("role","option"),this.setAttribute("tabindex","0"),this.addEventListener("keyup",(n=>{"Enter"!==n.key&&" "!==n.key||(n.preventDefault(),this.click())}))}});const smNotifications=document.createElement("template");smNotifications.innerHTML="
",customElements.define("sm-notifications",class extends HTMLElement{constructor(){super(),this.shadow=this.attachShadow({mode:"open"}).append(smNotifications.content.cloneNode(!0)),this.notificationPanel=this.shadowRoot.querySelector(".notification-panel"),this.animationOptions={duration:300,fill:"forwards",easing:"cubic-bezier(0.175, 0.885, 0.32, 1.275)"},this.push=this.push.bind(this),this.createNotification=this.createNotification.bind(this),this.removeNotification=this.removeNotification.bind(this),this.clearAll=this.clearAll.bind(this),this.remove=this.remove.bind(this),this.handleTouchMove=this.handleTouchMove.bind(this),this.startX=0,this.currentX=0,this.endX=0,this.swipeDistance=0,this.swipeDirection="",this.swipeThreshold=0,this.startTime=0,this.swipeTime=0,this.swipeTimeThreshold=200,this.currentTarget=null,this.notificationTimeout=5e3,this.mediaQuery=window.matchMedia("(min-width: 640px)"),this.handleOrientationChange=this.handleOrientationChange.bind(this),this.isBigViewport=!1}set timeout(value){isNaN(value)||(this.notificationTimeout=value)}randString(length){let result="";for(let i=0;i${icon}`:""} ${message} ${action?``:""} `,action&¬ification.querySelector(".action").addEventListener("click",action.callback),notification.querySelector(".close").addEventListener("click",(()=>{this.removeNotification(notification)})),pinned||setTimeout((()=>{this.removeNotification(notification,this.isBigViewport?"left":"top")}),timeout),notification}push(message,options={}){const notification=this.createNotification(message,options);return this.isBigViewport?this.notificationPanel.append(notification):this.notificationPanel.prepend(notification),notification.scrollIntoView({behavior:"smooth"}),this.notificationPanel.animate([{transform:`translateY(${this.isBigViewport?"":"-"}${notification.clientHeight}px)`},{transform:"none"}],this.animationOptions),notification.animate([{transform:"translateY(-1rem)",opacity:"0"},{transform:"none",opacity:"1"}],this.animationOptions).onfinish=e=>{e.target.commitStyles(),e.target.cancel()},notification.id}removeNotification(notification,direction="left"){if(!notification)return;const sign="left"===direction||"top"===direction?"-":"+";this.isBigViewport||"top"!==direction?notification.animate([{transform:this.currentX?`translateX(${this.currentX}px)`:"none",opacity:"1"},{transform:`translateX(calc(${sign}${Math.abs(this.currentX)}px ${sign} 1rem))`,opacity:"0"}],this.animationOptions).onfinish=()=>{notification.remove()}:notification.animate([{transform:this.currentX?`translateY(${this.currentX}px)`:"none",opacity:"1"},{transform:`translateY(calc(${sign}${Math.abs(this.currentX)}px ${sign} 1rem))`,opacity:"0"}],this.animationOptions).onfinish=()=>{notification.remove()}}remove(id){const notification=this.notificationPanel.querySelector(`#${id}`);notification&&this.removeNotification(notification)}clearAll(){Array.from(this.notificationPanel.children).forEach((child=>{this.removeNotification(child)}))}handleTouchMove(e){this.currentX=e.touches[0].clientX-this.startX,this.currentTarget.style.transform=`translateX(${this.currentX}px)`}handleOrientationChange(e){this.isBigViewport=e.matches,e.matches}connectedCallback(){this.handleOrientationChange(this.mediaQuery),this.mediaQuery.addEventListener("change",this.handleOrientationChange),this.notificationPanel.addEventListener("touchstart",(e=>{e.target.closest(".close")?this.removeNotification(e.target.closest(".notification")):e.target.closest(".notification")&&(this.swipeThreshold=e.target.closest(".notification").getBoundingClientRect().width/2,this.currentTarget=e.target.closest(".notification"),this.startTime=Date.now(),this.startX=e.touches[0].clientX,this.startY=e.touches[0].clientY,this.notificationPanel.addEventListener("touchmove",this.handleTouchMove,{passive:!0}))}),{passive:!0}),this.notificationPanel.addEventListener("touchend",(e=>{this.endX=e.changedTouches[0].clientX,this.endY=e.changedTouches[0].clientY,this.swipeDistance=Math.abs(this.endX-this.startX),this.swipeTime=Date.now()-this.startTime,this.endX>this.startX?this.swipeDirection="right":this.swipeDirection="left",this.swipeTime50&&this.removeNotification(this.currentTarget,this.swipeDirection):this.swipeDistance>this.swipeThreshold?this.removeNotification(this.currentTarget,this.swipeDirection):this.currentTarget.animate([{transform:`translateX(${this.currentX}px)`},{transform:"none"}],this.animationOptions).onfinish=e=>{e.target.commitStyles(),e.target.cancel()},this.notificationPanel.removeEventListener("touchmove",this.handleTouchMove),this.currentX=0}))}disconnectedCallback(){mediaQueryList.removeEventListener("change",handleOrientationChange)}});class Stack{constructor(){this.items=[]}push(t){this.items.push(t)}pop(){return 0==this.items.length?"Underflow":this.items.pop()}peek(){return this.items[this.items.length-1]}}const popupStack=new Stack,smPopup=document.createElement("template");smPopup.innerHTML=' ',customElements.define("sm-popup",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).append(smPopup.content.cloneNode(!0)),this.allowClosing=!1,this.isOpen=!1,this.offset=0,this.touchStartY=0,this.touchEndY=0,this.touchStartTime=0,this.touchEndTime=0,this.touchEndAnimation=void 0,this.focusable,this.autoFocus,this.mutationObserver,this.popupContainer=this.shadowRoot.querySelector(".popup-container"),this.backdrop=this.shadowRoot.querySelector(".backdrop"),this.dialogBox=this.shadowRoot.querySelector(".popup"),this.popupBodySlot=this.shadowRoot.querySelector(".popup-body slot"),this.popupHeader=this.shadowRoot.querySelector(".popup-top"),this.resumeScrolling=this.resumeScrolling.bind(this),this.setStateOpen=this.setStateOpen.bind(this),this.show=this.show.bind(this),this.hide=this.hide.bind(this),this.handleTouchStart=this.handleTouchStart.bind(this),this.handleTouchMove=this.handleTouchMove.bind(this),this.handleTouchEnd=this.handleTouchEnd.bind(this),this.detectFocus=this.detectFocus.bind(this),this.handleSoftDismiss=this.handleSoftDismiss.bind(this),this.debounce=this.debounce.bind(this)}static get observedAttributes(){return["open"]}get open(){return this.isOpen}animateTo(t,e,i){let s=t.animate(e,{...i,fill:"both"});return s.finished.then((()=>{s.commitStyles(),s.cancel()})),s}resumeScrolling(){let t=document.body.style.top;window.scrollTo(0,-1*parseInt(t||"0")),document.body.style.overflow="",document.body.style.top="initial"}setStateOpen(){if(!this.isOpen||this.offset){let t=window.innerWidth>640?"scale(1.1)":`translateY(${this.offset?`${this.offset}px`:"100%"})`;this.animateTo(this.dialogBox,[{opacity:this.offset?1:0,transform:t},{opacity:1,transform:"none"}],{duration:300,easing:"ease"})}}show(t={}){let{pinned:e=!1,payload:i}=t;if(this.isOpen)return;let s={duration:300,easing:"ease"};return this.payload=i,popupStack.push({popup:this,permission:e}),popupStack.items.length>1&&this.animateTo(popupStack.items[popupStack.items.length-2].popup.shadowRoot.querySelector(".popup"),[{transform:"none"},{transform:window.innerWidth>640?"scale(0.95)":"translateY(-1.5rem)"}],s),this.popupContainer.classList.remove("hide"),this.offset||(this.backdrop.animate([{opacity:0},{opacity:1}],s).onfinish=()=>{this.resolveOpen(this.payload)},this.dispatchEvent(new CustomEvent("popupopened",{bubbles:!0,composed:!0,detail:{payload:this.payload}})),document.body.style.overflow="hidden",document.body.style.top=`-${window.scrollY}px`),this.setStateOpen(),this.pinned=e,this.isOpen=!0,setTimeout((()=>{let t=this.autoFocus||this.focusable?.[0]||this.dialogBox;t&&(t.tagName.includes("-")?t.focusIn():t.focus())}),0),this.hasAttribute("open")||(this.setAttribute("open",""),this.addEventListener("keydown",this.detectFocus),this.resizeObserver.observe(this),this.mutationObserver.observe(this,{attributes:!0,childList:!0,subtree:!0}),this.popupHeader.addEventListener("touchstart",this.handleTouchStart,{passive:!0}),this.backdrop.addEventListener("mousedown",this.handleSoftDismiss)),{opened:new Promise((t=>{this.resolveOpen=t})),closed:new Promise((t=>{this.resolveClose=t}))}}hide(t={}){let{payload:e}=t,i={duration:150,easing:"ease"};this.backdrop.animate([{opacity:1},{opacity:0}],i),this.animateTo(this.dialogBox,[{opacity:1,transform:window.innerWidth>640?"none":`translateY(${this.offset?`${this.offset}px`:"0"})`},{opacity:0,transform:window.innerWidth>640?"scale(1.1)":"translateY(100%)"}],i).finished.finally((()=>{this.popupContainer.classList.add("hide"),this.dialogBox.style="",this.removeAttribute("open"),this.forms.length&&this.forms.forEach((t=>t.reset())),this.dispatchEvent(new CustomEvent("popupclosed",{bubbles:!0,composed:!0,detail:{payload:e||this.payload}})),this.resolveClose(e||this.payload),this.isOpen=!1})),popupStack.pop(),popupStack.items.length?this.animateTo(popupStack.items[popupStack.items.length-1].popup.shadowRoot.querySelector(".popup"),[{transform:window.innerWidth>640?"scale(0.95)":"translateY(-1.5rem)"},{transform:"none"}],i):this.resumeScrolling(),this.resizeObserver.disconnect(),this.mutationObserver.disconnect(),this.removeEventListener("keydown",this.detectFocus),this.popupHeader.removeEventListener("touchstart",this.handleTouchStart,{passive:!0}),this.backdrop.removeEventListener("mousedown",this.handleSoftDismiss)}handleTouchStart(t){this.offset=0,this.popupHeader.addEventListener("touchmove",this.handleTouchMove,{passive:!0}),this.popupHeader.addEventListener("touchend",this.handleTouchEnd,{passive:!0}),this.touchStartY=t.changedTouches[0].clientY,this.touchStartTime=t.timeStamp}handleTouchMove(t){this.touchStartY{this.dialogBox.style.transform=`translateY(${this.offset}px)`})))}handleTouchEnd(t){if(this.touchEndTime=t.timeStamp,cancelAnimationFrame(this.touchEndAnimation),this.touchEndY=t.changedTouches[0].clientY,this.threshold=.3*this.dialogBox.getBoundingClientRect().height,this.touchEndTime-this.touchStartTime>200)if(this.touchEndY-this.touchStartY>this.threshold){if(this.pinned)return void this.setStateOpen();this.hide()}else this.setStateOpen();else if(this.touchEndY>this.touchStartY){if(this.pinned)return void this.setStateOpen();this.hide()}this.popupHeader.removeEventListener("touchmove",this.handleTouchMove,{passive:!0}),this.popupHeader.removeEventListener("touchend",this.handleTouchEnd,{passive:!0})}detectFocus(t){if("Tab"===t.key&&this.focusable.length){if(!this.firstFocusable)for(let e=0;e=0;i--)if(!this.focusable[i].disabled){this.lastFocusable=this.focusable[i];break}t.shiftKey&&document.activeElement===this.firstFocusable?(t.preventDefault(),this.lastFocusable.tagName.includes("SM-")?this.lastFocusable.focusIn():this.lastFocusable.focus()):t.shiftKey||document.activeElement!==this.lastFocusable||(t.preventDefault(),this.firstFocusable.tagName.includes("SM-")?this.firstFocusable.focusIn():this.firstFocusable.focus())}}updateFocusableList(){this.focusable=this.querySelectorAll('sm-button:not([disabled]), button:not([disabled]), [href], sm-input, input:not([readonly]), sm-select, select, sm-checkbox, sm-textarea, textarea, [tabindex]:not([tabindex="-1"])'),this.autoFocus=this.querySelector("[autofocus]"),this.firstFocusable=null,this.lastFocusable=null}handleSoftDismiss(){this.pinned?this.dialogBox.animate([{transform:"translateX(-1rem)"},{transform:"translateX(1rem)"},{transform:"translateX(-0.5rem)"},{transform:"translateX(0.5rem)"},{transform:"translateX(0)"}],{duration:300,easing:"ease"}):this.hide()}debounce(t,e){let i=null;return(...s)=>{window.clearTimeout(i),i=window.setTimeout((()=>{t.apply(null,s)}),e)}}connectedCallback(){this.popupBodySlot.addEventListener("slotchange",this.debounce((()=>{this.forms=this.querySelectorAll("sm-form"),this.updateFocusableList()}),0)),this.resizeObserver=new ResizeObserver((t=>{t.forEach((t=>{if(t.contentBoxSize){let e=Array.isArray(t.contentBoxSize)?t.contentBoxSize[0]:t.contentBoxSize;this.threshold=.3*e.blockSize.height}else this.threshold=.3*t.contentRect.height}))})),this.mutationObserver=new MutationObserver((t=>{this.updateFocusableList()}))}disconnectedCallback(){this.resizeObserver.disconnect(),this.mutationObserver.disconnect(),this.removeEventListener("keydown",this.detectFocus),this.popupHeader.removeEventListener("touchstart",this.handleTouchStart,{passive:!0}),this.backdrop.removeEventListener("mousedown",this.handleSoftDismiss)}attributeChangedCallback(t){"open"===t&&this.hasAttribute("open")&&this.show()}});const smSwitch=document.createElement("template");smSwitch.innerHTML='\t',customElements.define("sm-switch",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).append(smSwitch.content.cloneNode(!0)),this.switch=this.shadowRoot.querySelector(".switch"),this.input=this.shadowRoot.querySelector("input"),this.isChecked=!1,this.isDisabled=!1,this.dispatch=this.dispatch.bind(this)}static get observedAttributes(){return["disabled","checked"]}get disabled(){return this.isDisabled}set disabled(e){e?this.setAttribute("disabled",""):this.removeAttribute("disabled")}get checked(){return this.isChecked}set checked(e){e?this.setAttribute("checked",""):this.removeAttribute("checked")}get value(){return this.isChecked}reset(){}dispatch(){this.dispatchEvent(new CustomEvent("change",{bubbles:!0,composed:!0,detail:{value:this.isChecked}}))}connectedCallback(){this.addEventListener("keydown",(e=>{" "!==e.key||this.isDisabled||(e.preventDefault(),this.input.click())})),this.input.addEventListener("click",(e=>{this.input.checked?this.checked=!0:this.checked=!1,this.dispatch()}))}attributeChangedCallback(e,t,n){t!==n&&("disabled"===e?this.hasAttribute("disabled")?this.disabled=!0:this.disabled=!1:"checked"===e&&(this.hasAttribute("checked")?(this.isChecked=!0,this.input.checked=!0):(this.isChecked=!1,this.input.checked=!1)))}});const smSelect=document.createElement("template");smSelect.innerHTML='
',customElements.define("sm-select",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).append(smSelect.content.cloneNode(!0)),this.focusIn=this.focusIn.bind(this),this.reset=this.reset.bind(this),this.open=this.open.bind(this),this.collapse=this.collapse.bind(this),this.toggle=this.toggle.bind(this),this.handleOptionsNavigation=this.handleOptionsNavigation.bind(this),this.handleOptionSelection=this.handleOptionSelection.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.handleClickOutside=this.handleClickOutside.bind(this),this.selectOption=this.selectOption.bind(this),this.debounce=this.debounce.bind(this),this.elementsChanged=this.elementsChanged.bind(this),this.availableOptions=[],this.previousOption,this.isOpen=!1,this.label="",this.defaultSelected="",this.isUnderViewport=!1,this.animationOptions={duration:300,fill:"forwards",easing:"ease"},this.optionList=this.shadowRoot.querySelector(".options"),this.selection=this.shadowRoot.querySelector(".selection"),this.selectedOptionText=this.shadowRoot.querySelector(".selected-option-text")}static get observedAttributes(){return["disabled","label","readonly"]}get value(){return this.getAttribute("value")}set value(t){const e=this.availableOptions.find((e=>e.getAttribute("value")===t));e?(this.setAttribute("value",t),this.selectOption(e)):console.warn(`There is no option with ${t} as value`)}debounce(t,e){let n=null;return(...i)=>{window.clearTimeout(n),n=window.setTimeout((()=>{t.apply(null,i)}),e)}}reset(t=!0){if(this.availableOptions[0]&&this.previousOption!==this.availableOptions[0]){const e=this.availableOptions.find((t=>t.hasAttribute("selected")))||this.availableOptions[0];this.value=e.getAttribute("value"),t&&this.fireEvent()}}selectOption(t){this.previousOption!==t&&(this.querySelectorAll("[selected").forEach((t=>t.removeAttribute("selected"))),this.selectedOptionText.textContent=`${this.label}${t.textContent}`,t.setAttribute("selected",""),this.previousOption=t)}focusIn(){this.selection.focus()}open(){this.availableOptions.forEach((t=>t.setAttribute("tabindex",0))),this.optionList.classList.remove("hidden"),this.isUnderViewport=this.getBoundingClientRect().bottom+this.optionList.getBoundingClientRect().height>window.innerHeight,this.isUnderViewport?this.setAttribute("isUnder",""):this.removeAttribute("isUnder"),this.optionList.animate([{transform:`translateY(${this.isUnderViewport?"":"-"}0.5rem)`,opacity:0},{transform:"translateY(0)",opacity:1}],this.animationOptions),this.setAttribute("open",""),this.style.zIndex=1e3,(this.availableOptions.find((t=>t.hasAttribute("selected")))||this.availableOptions[0]).focus(),document.addEventListener("mousedown",this.handleClickOutside),this.isOpen=!0}collapse(){this.removeAttribute("open"),this.optionList.animate([{transform:"translateY(0)",opacity:1},{transform:`translateY(${this.isUnderViewport?"":"-"}0.5rem)`,opacity:0}],this.animationOptions).onfinish=()=>{this.availableOptions.forEach((t=>t.removeAttribute("tabindex"))),document.removeEventListener("mousedown",this.handleClickOutside),this.optionList.classList.add("hidden"),this.isOpen=!1,this.style.zIndex="auto"}}toggle(){this.isOpen||this.hasAttribute("disabled")?this.collapse():this.open()}fireEvent(){this.dispatchEvent(new CustomEvent("change",{bubbles:!0,composed:!0,detail:{value:this.value}}))}handleOptionsNavigation(t){"ArrowUp"===t.key?(t.preventDefault(),document.activeElement.previousElementSibling?document.activeElement.previousElementSibling.focus():this.availableOptions[this.availableOptions.length-1].focus()):"ArrowDown"===t.key&&(t.preventDefault(),document.activeElement.nextElementSibling?document.activeElement.nextElementSibling.focus():this.availableOptions[0].focus())}handleOptionSelection(t){this.previousOption!==document.activeElement&&(this.value=document.activeElement.getAttribute("value"),this.fireEvent())}handleClick(t){t.target===this?this.toggle():(this.handleOptionSelection(),this.collapse())}handleKeydown(t){t.target===this?this.isOpen&&"ArrowDown"===t.key?(t.preventDefault(),(this.availableOptions.find((t=>t.hasAttribute("selected")))||this.availableOptions[0]).focus(),this.handleOptionSelection(t)):" "===t.key&&(t.preventDefault(),this.toggle()):(this.handleOptionsNavigation(t),this.handleOptionSelection(t),["Enter"," ","Escape","Tab"].includes(t.key)&&(t.preventDefault(),this.collapse(),this.focusIn()))}handleClickOutside(t){this.isOpen&&!this.contains(t.target)&&this.collapse()}elementsChanged(){this.availableOptions=[...this.querySelectorAll("sm-option")],this.reset(!1),this.defaultSelected=this.value}connectedCallback(){this.setAttribute("role","listbox"),this.hasAttribute("disabled")||this.hasAttribute("readonly")||(this.selection.setAttribute("tabindex","0"),this.addEventListener("click",this.handleClick),this.addEventListener("keydown",this.handleKeydown));const t=this.debounce(this.elementsChanged,100);this.shadowRoot.querySelector("slot").addEventListener("slotchange",t),this.mutationObserver=new MutationObserver((e=>{let n=!1;if(e.forEach((e=>{switch(e.type){case"childList":t();break;case"attributes":n=!0}})),n){const t=this.availableOptions.find((t=>t.hasAttribute("selected")))||this.availableOptions[0];this.selectedOptionText.textContent=`${this.label}${t.textContent}`,this.setAttribute("value",t.getAttribute("value"))}})),this.mutationObserver.observe(this,{subtree:!0,childList:!0,attributeFilter:["selected"]}),new IntersectionObserver(((t,e)=>{t.forEach((t=>{if(t.isIntersecting){this.selection.getBoundingClientRect().left *{ padding: 0; margin: 0; -webkit-box-sizing: border-box; box-sizing: border-box;} :host{ display: -webkit-box; display: -ms-flexbox; display: flex; overflow: hidden; border-radius: var(--border-radius, 0.3rem);}.option{ position: relative; display: flex; -webkit-box-align: center; -ms-flex-align: center; align-items: center; width: 100%; gap: 0.5rem; padding: var(--padding, 0.6rem 1rem); cursor: pointer; outline: none; user-select: none;}.option::before{ position: absolute; content: \'\'; display: block; width: 0.2rem; height: 1em; left: 0; border-radius: 0 1em 1em 0; background: rgba(var(--text-color,(17,17,17)), 0.5); transition: all 0.2s ease-in-out; opacity: 0;}:host(:focus){ outline: none; background: rgba(var(--text-color,(17,17,17)), 0.1);}:host(:focus) .option::before{ opacity: 1}:host([selected]) .option::before{ opacity: 1; background: var(--accent-color, teal);}@media (hover: hover){ .option:hover{ background: rgba(var(--text-color,(17,17,17)), 0.1); } :host(:not([selected]):hover) .option::before{ opacity: 1 }}
',customElements.define("sm-option",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).append(smOption.content.cloneNode(!0))}connectedCallback(){this.setAttribute("role","option")}});const spinner=document.createElement("template");spinner.innerHTML='';class SpinnerLoader extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).append(spinner.content.cloneNode(!0))}}window.customElements.define("sm-spinner",SpinnerLoader);const smTextarea=document.createElement("template");smTextarea.innerHTML=' ',customElements.define("sm-textarea",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).append(smTextarea.content.cloneNode(!0)),this.textarea=this.shadowRoot.querySelector("textarea"),this.textareaBox=this.shadowRoot.querySelector(".textarea"),this.placeholder=this.shadowRoot.querySelector(".placeholder"),this.reflectedAttributes=["disabled","required","readonly","rows","minlength","maxlength"],this.reset=this.reset.bind(this),this.focusIn=this.focusIn.bind(this),this.fireEvent=this.fireEvent.bind(this),this.checkInput=this.checkInput.bind(this)}static get observedAttributes(){return["disabled","value","placeholder","required","readonly","rows","minlength","maxlength"]}get value(){return this.textarea.value}set value(e){this.setAttribute("value",e),this.fireEvent()}get disabled(){return this.hasAttribute("disabled")}set disabled(e){e?this.setAttribute("disabled",""):this.removeAttribute("disabled")}get isValid(){return this.textarea.checkValidity()}reset(){this.setAttribute("value","")}focusIn(){this.textarea.focus()}fireEvent(){let e=new Event("input",{bubbles:!0,cancelable:!0,composed:!0});this.dispatchEvent(e)}checkInput(){this.hasAttribute("placeholder")&&""!==this.getAttribute("placeholder")&&(""!==this.textarea.value?this.placeholder.classList.add("hide"):this.placeholder.classList.remove("hide"))}connectedCallback(){this.textarea.addEventListener("input",(e=>{this.textareaBox.dataset.value=this.textarea.value,this.checkInput()}))}attributeChangedCallback(e,t,n){this.reflectedAttributes.includes(e)?this.hasAttribute(e)?this.textarea.setAttribute(e,this.getAttribute(e)?this.getAttribute(e):""):this.textContent.removeAttribute(e):"placeholder"===e?this.placeholder.textContent=this.getAttribute("placeholder"):"value"===e&&(this.textarea.value=n,this.textareaBox.dataset.value=n,this.checkInput())}});const textField=document.createElement("template");textField.innerHTML='
',customElements.define("text-field",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).append(textField.content.cloneNode(!0)),this.textField=this.shadowRoot.querySelector(".text-field"),this.textContainer=this.textField.children[0],this.editButton=this.textField.querySelector(".edit-button"),this.isTextEditable=!1,this.isDisabled=!1}static get observedAttributes(){return["disabled"]}get value(){return this.text}set value(val){this.text=val,this.textContainer.textContent=val,this.setAttribute("value",val)}set disabled(val){this.isDisabled=val,this.isDisabled?this.setAttribute("disabled",""):this.removeAttribute("disabled")}setEditable=()=>{this.isTextEditable||(this.textContainer.contentEditable=!0,this.setAttribute("editable",""),this.textContainer.focus(),document.execCommand("selectAll",!1,null),this.editButton.textContent="Done",this.isTextEditable=!0)};setNonEditable=()=>{this.isTextEditable&&(this.textContainer.contentEditable=!1,this.removeAttribute("editable"),this.text!==this.textContainer.textContent.trim()&&(this.setAttribute("value",this.textContainer.textContent),this.text=this.textContainer.textContent.trim(),this.dispatchEvent(new CustomEvent("change",{bubbles:!0,cancelable:!0,composed:!0}))),this.editButton.textContent="Edit",this.isTextEditable=!1)};toggleEditable=()=>{this.isTextEditable?this.setNonEditable():this.setEditable()};revert=()=>{this.textContainer.isContentEditable&&(this.value=this.text,this.setNonEditable())};connectedCallback(){this.text,this.hasAttribute("value")&&(this.text=this.getAttribute("value"),this.textContainer.textContent=this.text),this.hasAttribute("disabled")?this.isDisabled=!0:this.isDisabled=!1,this.isDisabled||(this.textContainer.addEventListener("dblclick",this.setEditable),this.editButton.addEventListener("click",this.toggleEditable))}attributeChangedCallback(name){"disabled"===name&&(this.hasAttribute("disabled")?(this.editButton.classList.add("hide"),this.textContainer.removeEventListener("dblclick",this.setEditable),this.editButton.removeEventListener("click",this.toggleEditable),this.revert()):(this.editButton.classList.remove("hide"),this.textContainer.addEventListener("dblclick",this.setEditable),this.editButton.addEventListener("click",this.toggleEditable)))}disconnectedCallback(){this.textContainer.removeEventListener("dblclick",this.setEditable),this.editButton.removeEventListener("click",this.toggleEditable)}});const themeToggle=document.createElement("template");themeToggle.innerHTML=' ';class ThemeToggle extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).append(themeToggle.content.cloneNode(!0)),this.isChecked=!1,this.hasTheme="light",this.toggleState=this.toggleState.bind(this),this.fireEvent=this.fireEvent.bind(this),this.handleThemeChange=this.handleThemeChange.bind(this)}static get observedAttributes(){return["checked"]}daylight(){this.hasTheme="light",document.body.dataset.theme="light",this.setAttribute("aria-checked","false")}nightlight(){this.hasTheme="dark",document.body.dataset.theme="dark",this.setAttribute("aria-checked","true")}toggleState(){if(!document.startViewTransition)return this.toggleAttribute("checked"),void this.fireEvent();document.startViewTransition((()=>{this.toggleAttribute("checked"),this.fireEvent()}))}handleKeyDown(e){" "===e.key&&this.toggleState()}handleThemeChange(e){e.detail.theme!==this.hasTheme&&("dark"===e.detail.theme?this.setAttribute("checked",""):this.removeAttribute("checked"))}fireEvent(){this.dispatchEvent(new CustomEvent("themechange",{bubbles:!0,composed:!0,detail:{theme:this.hasTheme}}))}connectedCallback(){this.setAttribute("role","switch"),this.setAttribute("aria-label","theme toggle"),"dark"===localStorage.getItem(`${window.location.hostname}-theme`)?(this.nightlight(),this.setAttribute("checked","")):"light"===localStorage.getItem(`${window.location.hostname}-theme`)?(this.daylight(),this.removeAttribute("checked")):window.matchMedia("(prefers-color-scheme: dark)").matches?(this.nightlight(),this.setAttribute("checked","")):(this.daylight(),this.removeAttribute("checked")),this.addEventListener("click",this.toggleState),this.addEventListener("keydown",this.handleKeyDown),document.addEventListener("themechange",this.handleThemeChange)}disconnectedCallback(){this.removeEventListener("click",this.toggleState),this.removeEventListener("keydown",this.handleKeyDown),document.removeEventListener("themechange",this.handleThemeChange)}attributeChangedCallback(e,t,n){"checked"===e&&(this.hasAttribute("checked")?(this.nightlight(),localStorage.setItem(`${window.location.hostname}-theme`,"dark")):(this.daylight(),localStorage.setItem(`${window.location.hostname}-theme`,"light")))}}window.customElements.define("theme-toggle",ThemeToggle);const colorGrid=document.createElement("template");colorGrid.innerHTML='\n\n
\n
',customElements.define("color-grid",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).append(colorGrid.content.cloneNode(!0)),this.colorArray=[],this.container=this.shadowRoot.querySelector(".color-tile-container"),this.handleChange=this.handleChange.bind(this),this.setCheckMark=this.setCheckMark.bind(this)}set colors(arr){this.colorArray=arr,this.renderTiles()}set selectedColor(color){if(this.colorArray.includes(color)&&this.container.querySelector(`[data-color="${color}"]`)){const selectedTile=this.container.querySelector(`[data-color="${color}"]`);selectedTile&&(selectedTile.querySelector("input").checked=!0,this.setCheckMark(selectedTile))}}randString(length){let result="",characters="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";for(let i=0;i{const label=document.createElement("label");label.classList.add("color-tile"),label.setAttribute("data-color",color),color.includes("--")?label.setAttribute("style",`background-color: var(${color})`):label.setAttribute("style",`background-color: ${color}`),label.innerHTML=`\n \n `,frag.append(label)})),this.container.append(frag)}setCheckMark(target){target.parentNode.querySelectorAll(".checkmark").forEach((checkmark=>checkmark.remove()));const checkMark=document.createElement("div");checkMark.classList.add("checkmark"),checkMark.innerHTML='\n \n ',target.append(checkMark)}handleChange(e){const clickedTile=e.target.closest(".color-tile");this.setCheckMark(clickedTile);const clickedTileColor=clickedTile.dataset.color,tileSelected=new CustomEvent("colorselected",{bubbles:!0,composed:!0,detail:{value:clickedTileColor}});this.dispatchEvent(tileSelected)}connectedCallback(){this.container.addEventListener("change",this.handleChange)}disconnectedCallback(){this.container.removeEventListener("change",this.handleChange)}}),window.customElements.define("keys-generator",class extends HTMLElement{constructor(){super(),this.innerHTML='\n \n
\n
\n \n
\n \n

Keep your keys safe!

\n
\n

Don\'t share with anyone. Once lost private key can\'t be recovered.

\n
\n
\n
\n
\n
FLO address
\n \n
\n
\n
Private key
\n \n
\n
\n \n

You can use these FLO credentials with other RanchiMall apps too.

\n
\n '}get keys(){return{floID:this.querySelector("#generated_flo_address").value,privKey:this.querySelector("#generated_private_key").value}}generateKeys(){const{floID:floID,privKey:privKey}=floCrypto.generateNewID();this.querySelector("#generated_flo_address").value=floID,this.querySelector("#generated_private_key").value=privKey}clearKeys(){this.querySelector("#generated_flo_address").value="",this.querySelector("#generated_private_key").value=""}});const adBlockerWarning=document.createElement("template");adBlockerWarning.innerHTML='\n \n
\n ',window.customElements.define("adblocker-warning",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}),this.shadowRoot.appendChild(adBlockerWarning.content.cloneNode(!0))}connectedCallback(){const isBrave=void 0!==navigator.brave;this.shadowRoot.querySelector("#adblocker_warning").innerHTML=`\n \n

Ad-Blocker Detected!

\n

\n Please disable your ad-blocker for optimal experience. Our app doesn't show ads or track activity. \n

\n ${isBrave?"If you have enabled Brave shield then disable it also.":""}\n `}});const IDBsupport=document.createElement("template");IDBsupport.innerHTML='\n \n \n ',window.customElements.define("idb-support",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}),this.shadowRoot.appendChild(IDBsupport.content.cloneNode(!0))}connectedCallback(){const thisComponent=this;if("indexedDB"in window){const request=window.indexedDB.open("testDB",1);request.onerror=function(event){console.log("IndexedDB is not allowed or encountered an error."),thisComponent.shadowRoot.querySelector("#idb_support").style.display="flex"},request.onsuccess=function(event){thisComponent.remove()}}else console.log("IndexedDB is not supported.")}}); \ No newline at end of file +const smChips=document.createElement("template");smChips.innerHTML='
',customElements.define("sm-chips",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).append(smChips.content.cloneNode(!0)),this.chipsWrapper=this.shadowRoot.querySelector(".sm-chips"),this.coverLeft=this.shadowRoot.querySelector(".cover--left"),this.coverRight=this.shadowRoot.querySelector(".cover--right"),this.navButtonLeft=this.shadowRoot.querySelector(".nav-button--left"),this.navButtonRight=this.shadowRoot.querySelector(".nav-button--right"),this.slottedOptions=void 0,this._value=void 0,this.scrollDistance=0,this.assignedElements=[],this.scrollLeft=this.scrollLeft.bind(this),this.scrollRight=this.scrollRight.bind(this),this.fireEvent=this.fireEvent.bind(this),this.setSelectedOption=this.setSelectedOption.bind(this)}get value(){return this._value}set value(t){this.setSelectedOption(t)}scrollLeft(){this.chipsWrapper.scrollBy({left:-this.scrollDistance,behavior:"smooth"})}scrollRight(){this.chipsWrapper.scrollBy({left:this.scrollDistance,behavior:"smooth"})}setSelectedOption(t){this._value!==t&&(this._value=t,this.assignedElements.forEach((e=>{e.value==t?(e.setAttribute("selected",""),e.scrollIntoView({behavior:"smooth",block:"nearest",inline:"center"})):e.removeAttribute("selected")})))}fireEvent(){this.dispatchEvent(new CustomEvent("change",{bubbles:!0,composed:!0,detail:{value:this._value}}))}connectedCallback(){this.setAttribute("role","listbox");const t=this.shadowRoot.querySelector("slot");t.addEventListener("slotchange",(e=>{n.disconnect(),i.disconnect(),this.observeSelf.disconnect(),clearTimeout(this.slotChangeTimeout),this.slotChangeTimeout=setTimeout((()=>{this.assignedElements=t.assignedElements(),this.assignedElements.forEach((t=>{t.hasAttribute("selected")&&(this._value=t.value)})),this.observeSelf.observe(this)}),0)}));const e=new ResizeObserver((t=>{t.forEach((t=>{if(t.contentBoxSize){const e=Array.isArray(t.contentBoxSize)?t.contentBoxSize[0]:t.contentBoxSize;this.scrollDistance=.6*e.inlineSize}else this.scrollDistance=.6*t.contentRect.width}))}));e.observe(this),this.observeSelf=new IntersectionObserver(((t,e)=>{t.forEach((t=>{t.isIntersecting&&!this.hasAttribute("multiline")&&this.assignedElements.length>0&&(n.observe(this.assignedElements[0]),i.observe(this.assignedElements[this.assignedElements.length-1]),e.unobserve(this))}))}),{threshold:1}),this.chipsWrapper.addEventListener("option-clicked",(t=>{this._value!==t.target.value&&(this.setSelectedOption(t.target.value),this.fireEvent())}));const n=new IntersectionObserver((t=>{t.forEach((t=>{t.isIntersecting?(this.navButtonLeft.classList.add("hide"),this.coverLeft.classList.add("hide")):(this.navButtonLeft.classList.remove("hide"),this.coverLeft.classList.remove("hide"))}))}),{threshold:1,root:this}),i=new IntersectionObserver((t=>{t.forEach((t=>{t.isIntersecting?(this.navButtonRight.classList.add("hide"),this.coverRight.classList.add("hide")):(this.navButtonRight.classList.remove("hide"),this.coverRight.classList.remove("hide"))}))}),{threshold:1,root:this});this.navButtonLeft.addEventListener("click",this.scrollLeft),this.navButtonRight.addEventListener("click",this.scrollRight)}disconnectedCallback(){this.navButtonLeft.removeEventListener("click",this.scrollLeft),this.navButtonRight.removeEventListener("click",this.scrollRight)}});const smChip=document.createElement("template");smChip.innerHTML=' ',customElements.define("sm-chip",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).append(smChip.content.cloneNode(!0)),this._value=void 0,this.radioButton=this.shadowRoot.querySelector("input"),this.fireEvent=this.fireEvent.bind(this),this.handleKeyDown=this.handleKeyDown.bind(this)}get value(){return this._value}fireEvent(){this.dispatchEvent(new CustomEvent("option-clicked",{bubbles:!0,composed:!0,detail:{value:this._value}}))}handleKeyDown(t){"Enter"!==t.key&&"Space"!==t.key||this.fireEvent()}connectedCallback(){this.setAttribute("role","option"),this.setAttribute("tabindex","0"),this._value=this.getAttribute("value"),this.addEventListener("click",this.fireEvent),this.addEventListener("keydown",this.handleKeyDown)}disconnectedCallback(){this.removeEventListener("click",this.fireEvent),this.removeEventListener("keydown",this.handleKeyDown)}});const smCopy=document.createElement("template");smCopy.innerHTML='

',customElements.define("sm-copy",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).append(smCopy.content.cloneNode(!0)),this.copyContent=this.shadowRoot.querySelector(".copy-content"),this.copyButton=this.shadowRoot.querySelector(".copy-button"),this.copy=this.copy.bind(this)}static get observedAttributes(){return["value"]}set value(t){this.setAttribute("value",t)}get value(){return this.getAttribute("value")}fireEvent(){this.dispatchEvent(new CustomEvent("copy",{composed:!0,bubbles:!0,cancelable:!0}))}copy(){navigator.clipboard.writeText(this.getAttribute("value")).then((t=>this.fireEvent())).catch((t=>console.error(t)))}connectedCallback(){this.copyButton.addEventListener("click",this.copy)}attributeChangedCallback(t,n,o){if("value"===t){const t=this.copyContent.querySelector("slot");if(!t)return;const n=t.assignedNodes();n&&n.length||(t.textContent=o)}}disconnectedCallback(){this.copyButton.removeEventListener("click",this.copy)}});const smForm=document.createElement("template");smForm.innerHTML='
',customElements.define("sm-form",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).append(smForm.content.cloneNode(!0)),this.form=this.shadowRoot.querySelector("form"),this.invalidFieldsCount,this.skipSubmit=!1,this.isFormValid=void 0,this.supportedElements="input, sm-input, sm-textarea, sm-checkbox, tags-input, file-input, sm-switch, sm-radio",this.formElements=[],this._requiredElements=[]}static get observedAttributes(){return["skip-submit"]}get validity(){return this.isFormValid}debounce=(callback,wait)=>{let timeoutId=null;return(...args)=>{window.clearTimeout(timeoutId),timeoutId=window.setTimeout((()=>{callback.apply(null,args)}),wait)}};_checkValidity=()=>{this.submitButton&&0!==this._requiredElements.length&&(this.invalidFieldsCount=0,this._requiredElements.forEach((([elem,isWC])=>{(!elem.disabled&&isWC&&!elem.isValid||!isWC&&!elem.checkValidity())&&this.invalidFieldsCount++})),this.isFormValid!==(0===this.invalidFieldsCount)&&(this.isFormValid=0===this.invalidFieldsCount,this.dispatchEvent(new CustomEvent(this.isFormValid?"valid":"invalid",{bubbles:!0,composed:!0})),this.skipSubmit||(this.submitButton.disabled=!this.isFormValid)))};handleKeydown=e=>{if("Enter"===e.key&&e.target.tagName.includes("INPUT"))if(0===this.invalidFieldsCount)this.submitButton&&this.submitButton.click(),this.dispatchEvent(new CustomEvent("submit",{bubbles:!0,composed:!0}));else for(const[elem,isWC]of this._requiredElements)if(isWC?!elem.isValid:!elem.checkValidity()){(elem?.shadowRoot?.lastElementChild||elem).animate([{transform:"translateX(-1rem)"},{transform:"translateX(1rem)"},{transform:"translateX(-0.5rem)"},{transform:"translateX(0.5rem)"},{transform:"translateX(0)"}],{duration:300,easing:"ease"}),isWC?(elem.focusIn(),"SM-INPUT"===elem.tagName&&""===elem.value.trim()&&elem.showError()):elem.focus();break}};reset=()=>{this.formElements.forEach((([elem,isWC])=>{if(isWC)elem.reset();else switch(elem.type){case"checkbox":case"radio":elem.checked=!1;break;default:elem.value=""}})),this._checkValidity()};elementsChanged=()=>{this.formElements=[...this.querySelectorAll(this.supportedElements)].map((elem=>[elem,elem.tagName.includes("-")])),this._requiredElements=this.formElements.filter((([elem])=>elem.hasAttribute("required"))),this.submitButton=this.querySelector('[variant="primary"], [type="submit"]'),this.resetButton=this.querySelector('[type="reset"]'),this.resetButton&&this.resetButton.addEventListener("click",this.reset),this._checkValidity()};checkIfSupported=elem=>1===elem.nodeType&&(elem.tagName.includes("-")||"input"===elem.tagName||elem.querySelector(this.supportedElements));connectedCallback(){const updateFormDecedents=this.debounce(this.elementsChanged,100);this.addEventListener("input",this.debounce(this._checkValidity,100)),this.addEventListener("keydown",this.debounce(this.handleKeydown,100)),this.shadowRoot.querySelector("slot").addEventListener("slotchange",updateFormDecedents),this.mutationObserver=new MutationObserver((mutations=>{mutations.forEach((mutation=>{("childList"===mutation.type&&[...mutation.addedNodes].some((node=>this.checkIfSupported(node)))||[...mutation.removedNodes].some((node=>this.checkIfSupported(node))))&&updateFormDecedents()}))})),this.mutationObserver.observe(this,{childList:!0,subtree:!0})}attributeChangedCallback(name,oldValue,newValue){"skip-submit"===name&&(this.skipSubmit=this.hasAttribute("skip-submit"))}disconnectedCallback(){this.removeEventListener("input",this.debounce(this._checkValidity,100)),this.removeEventListener("keydown",this.debounce(this.handleKeydown,100)),this.mutationObserver.disconnect()}});const smInput=document.createElement("template");smInput.innerHTML='
',customElements.define("sm-input",class extends HTMLElement{#validationState={validatedFor:void 0,isValid:!1,errorMessage:"Please fill out this field."};constructor(){super(),this.attachShadow({mode:"open"}).append(smInput.content.cloneNode(!0)),this.inputParent=this.shadowRoot.querySelector(".input"),this.input=this.shadowRoot.querySelector("input"),this.clearBtn=this.shadowRoot.querySelector(".clear"),this.label=this.shadowRoot.querySelector(".label"),this.feedbackText=this.shadowRoot.querySelector(".feedback-text"),this.outerContainer=this.shadowRoot.querySelector(".outer-container"),this.optionList=this.shadowRoot.querySelector(".datalist"),this._helperText="",this.isRequired=!1,this.datalist=[],this.validationFunction=void 0,this.reflectedAttributes=["value","required","disabled","type","inputmode","readonly","min","max","pattern","minlength","maxlength","step","list","autocomplete"]}static get observedAttributes(){return["value","placeholder","required","disabled","type","inputmode","readonly","min","max","pattern","minlength","maxlength","step","helper-text","error-text","list"]}get value(){return this.input.value}set value(val){val!==this.input.value&&(this.input.value=val,this._value=val,this.checkInput())}get placeholder(){return this.getAttribute("placeholder")}set placeholder(val){this.setAttribute("placeholder",val)}get type(){return this.getAttribute("type")}set type(val){this.setAttribute("type",val)}get validity(){return this.input.validity}get disabled(){return this.hasAttribute("disabled")}set disabled(value){value?(this.inputParent.classList.add("disabled"),this.setAttribute("disabled","")):(this.inputParent.classList.remove("disabled"),this.removeAttribute("disabled"))}get readOnly(){return this.hasAttribute("readonly")}set readOnly(value){value?this.setAttribute("readonly",""):this.removeAttribute("readonly")}set customValidation(val){val&&(this.validationFunction=val)}set errorText(val){this.#validationState.errorText=val}showError=(errorText=this.#validationState.errorText)=>{this.feedbackText.className="feedback-text error",this.feedbackText.innerHTML=` ${errorText}`};set helperText(val){this._helperText=val}get isValid(){if(this.#validationState.validatedFor===this.input.value)return this.#validationState.isValid;const _isValid=this.input.checkValidity();let _validity={isValid:!0,errorText:""};return this.validationFunction&&(_validity=this.validationFunction(this.input.value)),_isValid&&_validity.isValid?(this.feedbackText.className="feedback-text success",this.feedbackText.textContent=""):""!==this.value.trim()&&(_validity.errorText||this.#validationState.errorText)&&this.showError(_validity.errorText||this.#validationState.errorText),this.#validationState.validatedFor=this.input.value,this.#validationState.isValid=_isValid&&_validity.isValid,this.#validationState.errorText=_validity.errorText||this.#validationState.errorText,this.#validationState.isValid}reset=()=>{this.value=""};clear=()=>{this.value="",this.input.focus(),this.fireEvent()};focusIn=()=>{this.input.focus()};focusOut=()=>{this.input.blur()};fireEvent=()=>{let event=new Event("input",{bubbles:!0,cancelable:!0,composed:!0});this.dispatchEvent(event)};searchDatalist=searchKey=>{const filteredData=this.datalist.filter((item=>item.toLowerCase().includes(searchKey.toLowerCase())));if(filteredData.sort(((a,b)=>a.toLowerCase().indexOf(searchKey.toLowerCase())-b.toLowerCase().indexOf(searchKey.toLowerCase()))),filteredData.length){if(this.optionList.children.length>filteredData.length){const optionsToRemove=this.optionList.children.length-filteredData.length;for(let i=0;i{if(this.optionList.children[index])this.optionList.children[index].textContent=item;else{const option=document.createElement("li");option.textContent=item,option.classList.add("datalist-item"),option.setAttribute("tabindex","0"),this.optionList.appendChild(option)}})),this.optionList.classList.remove("hidden")}else this.optionList.classList.add("hidden")};checkInput=e=>{this.hasAttribute("readonly")||(""!==this.input.value?this.clearBtn.classList.remove("hidden"):this.clearBtn.classList.add("hidden")),this.hasAttribute("placeholder")&&""!==this.getAttribute("placeholder").trim()&&(""!==this.input.value?(this.shouldAnimateLabel&&this.inputParent.classList.add("animate-placeholder"),this.label.classList.toggle("hidden",!this.shouldAnimateLabel),this.datalist.length&&(this.searchTimeout&&clearTimeout(this.searchTimeout),this.searchTimeout=setTimeout((()=>{this.searchDatalist(this.input.value.trim())}),100))):(this.shouldAnimateLabel&&this.inputParent.classList.remove("animate-placeholder"),this.label.classList.remove("hidden"),this.feedbackText.textContent="",this.datalist.length&&(this.optionList.innerHTML="",this.optionList.classList.add("hidden"))))};allowOnlyNum=e=>{e.ctrlKey||1===e.key.length&&(("."!==e.key||!e.target.value.includes(".")&&0!==e.target.value.length)&&["0","1","2","3","4","5","6","7","8","9","."].includes(e.key)||e.preventDefault())};handleOptionClick=e=>{this.input.value=e.target.textContent,this.optionList.classList.add("hidden"),this.input.focus()};handleInputNavigation=e=>{"ArrowDown"===e.key?(e.preventDefault(),this.optionList.children.length&&this.optionList.children[0].focus()):"ArrowUp"===e.key&&(e.preventDefault(),this.optionList.children.length&&this.optionList.children[this.optionList.children.length-1].focus())};handleDatalistNavigation=e=>{"ArrowUp"===e.key?(e.preventDefault(),this.shadowRoot.activeElement.previousElementSibling?this.shadowRoot.activeElement.previousElementSibling.focus():this.input.focus()):"ArrowDown"===e.key?(e.preventDefault(),this.shadowRoot.activeElement.nextElementSibling?this.shadowRoot.activeElement.nextElementSibling.focus():this.input.focus()):"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),this.input.value=e.target.textContent,this.optionList.classList.add("hidden"),this.input.focus())};handleFocus=e=>{this.datalist.length&&this.searchDatalist(this.input.value.trim())};handleBlur=e=>{this.datalist.length&&this.optionList.classList.add("hidden")};connectedCallback(){const uuid=crypto.randomUUID();if(this.input.id=uuid,this.label.htmlFor=uuid,this.shouldAnimateLabel=this.hasAttribute("animate"),this.shouldAnimateLabel&&""!==this.placeholder&&this.value&&(this.inputParent.classList.add("animate-placeholder"),this.label.classList.remove("hidden")),this.setAttribute("role","textbox"),"undefined"!=typeof smCompConfig&&smCompConfig["sm-input"]){const config=smCompConfig["sm-input"].find((config=>this.matches(config.selector)));this.customValidation=config?.customValidation}this.input.addEventListener("input",this.checkInput),this.clearBtn.addEventListener("click",this.clear),this.datalist.length&&(this.optionList.addEventListener("click",this.handleOptionClick),this.input.addEventListener("keydown",this.handleInputNavigation),this.optionList.addEventListener("keydown",this.handleDatalistNavigation)),this.input.addEventListener("focusin",this.handleFocus),this.addEventListener("focusout",this.handleBlur)}attributeChangedCallback(name,oldValue,newValue){if(oldValue!==newValue)switch(this.reflectedAttributes.includes(name)&&(this.hasAttribute(name)?this.input.setAttribute(name,this.getAttribute(name)?this.getAttribute(name):""):this.input.removeAttribute(name)),name){case"placeholder":this.label.textContent=newValue,this.setAttribute("aria-label",newValue);break;case"value":this.checkInput();break;case"type":this.hasAttribute("type")&&"number"===this.getAttribute("type")?(this.input.setAttribute("inputmode","decimal"),this.input.addEventListener("keydown",this.allowOnlyNum)):this.input.removeEventListener("keydown",this.allowOnlyNum);break;case"helper-text":this._helperText=newValue;break;case"error-text":this.#validationState.errorText=newValue;break;case"required":this.isRequired=this.hasAttribute("required"),this.isRequired?this.setAttribute("aria-required","true"):this.setAttribute("aria-required","false");break;case"readonly":this.hasAttribute("readonly")?this.inputParent.classList.add("readonly"):this.inputParent.classList.remove("readonly");break;case"disabled":this.hasAttribute("disabled")?this.inputParent.classList.add("disabled"):this.inputParent.classList.remove("disabled");break;case"list":this.hasAttribute("list")&&""!==this.getAttribute("list").trim()&&(this.datalist=this.getAttribute("list").split(","))}}disconnectedCallback(){this.input.removeEventListener("input",this.checkInput),this.clearBtn.removeEventListener("click",this.clear),this.input.removeEventListener("keydown",this.allowOnlyNum),this.optionList.removeEventListener("click",this.handleOptionClick),this.input.removeEventListener("keydown",this.handleInputNavigation),this.optionList.removeEventListener("keydown",this.handleDatalistNavigation),this.input.removeEventListener("focusin",this.handleFocus),this.removeEventListener("focusout",this.handleBlur)}});const smMenu=document.createElement("template");smMenu.innerHTML='
',customElements.define("sm-menu",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).append(smMenu.content.cloneNode(!0)),this.isOpen=!1,this.availableOptions,this.containerDimensions,this.animOptions={duration:200,easing:"ease"},this.optionList=this.shadowRoot.querySelector(".options"),this.menu=this.shadowRoot.querySelector(".menu"),this.icon=this.shadowRoot.querySelector(".icon"),this.expand=this.expand.bind(this),this.collapse=this.collapse.bind(this),this.toggle=this.toggle.bind(this),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleClick=this.handleClick.bind(this),this.handleClickOutside=this.handleClickOutside.bind(this)}static get observedAttributes(){return["value"]}get value(){return this.getAttribute("value")}set value(n){this.setAttribute("value",n)}expand(){this.isOpen||(this.optionList.classList.remove("hide"),this.optionList.animate([{transform:"translateY(-1rem)",opacity:"0"},{transform:"none",opacity:"1"}],this.animOptions).onfinish=()=>{this.isOpen=!0,this.icon.classList.add("focused"),document.addEventListener("mousedown",this.handleClickOutside);const n=this.optionList.firstElementChild.assignedElements().find((n=>"MENU-OPTION"===n.tagName));n&&n.focus()})}collapse(){this.isOpen&&(this.optionList.animate([{transform:"none",opacity:"1"},{transform:"translateY(-1rem)",opacity:"0"}],this.animOptions).onfinish=()=>{this.isOpen=!1,this.icon.classList.remove("focused"),this.optionList.classList.add("hide"),document.removeEventListener("mousedown",this.handleClickOutside)})}toggle(){this.isOpen?this.collapse():this.expand()}handleClick(n){n.target===this?this.toggle():this.collapse()}handleKeyDown(n){n.target===this?"ArrowDown"===n.key?(n.preventDefault(),this.availableOptions[0].focus()):" "===n.key&&(n.preventDefault(),this.toggle()):"ArrowUp"===n.key?(n.preventDefault(),document.activeElement.previousElementSibling?document.activeElement.previousElementSibling.focus():this.availableOptions[this.availableOptions.length-1].focus()):"ArrowDown"===n.key?(n.preventDefault(),document.activeElement.nextElementSibling?document.activeElement.nextElementSibling.focus():this.availableOptions[0].focus()):"Enter"!==n.key&&" "!==n.key||(n.preventDefault(),n.target.click(),this.collapse(),this.menu.focus())}handleClickOutside(n){this.contains(n.target)||2===n.button||this.collapse()}connectedCallback(){this.setAttribute("role","listbox"),this.setAttribute("aria-label","dropdown menu");this.shadowRoot.querySelector(".options slot").addEventListener("slotchange",(n=>{this.availableOptions=n.target.assignedElements(),this.containerDimensions=this.optionList.getBoundingClientRect()})),this.addEventListener("click",this.handleClick),this.addEventListener("keydown",this.handleKeyDown)}disconnectedCallback(){this.removeEventListener("click",this.handleClick),this.removeEventListener("keydown",this.handleKeyDown),document.removeEventListener("mousedown",this.handleClickOutside)}});const menuOption=document.createElement("template");menuOption.innerHTML='
',customElements.define("menu-option",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).append(menuOption.content.cloneNode(!0))}connectedCallback(){this.setAttribute("role","option"),this.setAttribute("tabindex","0"),this.addEventListener("keyup",(n=>{"Enter"!==n.key&&" "!==n.key||(n.preventDefault(),this.click())}))}});const smNotifications=document.createElement("template");smNotifications.innerHTML="
",customElements.define("sm-notifications",class extends HTMLElement{constructor(){super(),this.shadow=this.attachShadow({mode:"open"}).append(smNotifications.content.cloneNode(!0)),this.notificationPanel=this.shadowRoot.querySelector(".notification-panel"),this.animationOptions={duration:300,fill:"forwards",easing:"cubic-bezier(0.175, 0.885, 0.32, 1.275)"},this.push=this.push.bind(this),this.createNotification=this.createNotification.bind(this),this.removeNotification=this.removeNotification.bind(this),this.clearAll=this.clearAll.bind(this),this.remove=this.remove.bind(this),this.handleTouchMove=this.handleTouchMove.bind(this),this.startX=0,this.currentX=0,this.endX=0,this.swipeDistance=0,this.swipeDirection="",this.swipeThreshold=0,this.startTime=0,this.swipeTime=0,this.swipeTimeThreshold=200,this.currentTarget=null,this.notificationTimeout=5e3,this.mediaQuery=window.matchMedia("(min-width: 640px)"),this.handleOrientationChange=this.handleOrientationChange.bind(this),this.isBigViewport=!1}set timeout(value){isNaN(value)||(this.notificationTimeout=value)}randString(length){let result="";for(let i=0;i${icon}`:""} ${message} ${action?``:""} `,action&¬ification.querySelector(".action").addEventListener("click",action.callback),notification.querySelector(".close").addEventListener("click",(()=>{this.removeNotification(notification)})),pinned||setTimeout((()=>{this.removeNotification(notification,this.isBigViewport?"left":"top")}),timeout),notification}push(message,options={}){const notification=this.createNotification(message,options);return this.isBigViewport?this.notificationPanel.append(notification):this.notificationPanel.prepend(notification),notification.scrollIntoView({behavior:"smooth"}),this.notificationPanel.animate([{transform:`translateY(${this.isBigViewport?"":"-"}${notification.clientHeight}px)`},{transform:"none"}],this.animationOptions),notification.animate([{transform:"translateY(-1rem)",opacity:"0"},{transform:"none",opacity:"1"}],this.animationOptions).onfinish=e=>{e.target.commitStyles(),e.target.cancel()},notification.id}removeNotification(notification,direction="left"){if(!notification)return;const sign="left"===direction||"top"===direction?"-":"+";this.isBigViewport||"top"!==direction?notification.animate([{transform:this.currentX?`translateX(${this.currentX}px)`:"none",opacity:"1"},{transform:`translateX(calc(${sign}${Math.abs(this.currentX)}px ${sign} 1rem))`,opacity:"0"}],this.animationOptions).onfinish=()=>{notification.remove()}:notification.animate([{transform:this.currentX?`translateY(${this.currentX}px)`:"none",opacity:"1"},{transform:`translateY(calc(${sign}${Math.abs(this.currentX)}px ${sign} 1rem))`,opacity:"0"}],this.animationOptions).onfinish=()=>{notification.remove()}}remove(id){const notification=this.notificationPanel.querySelector(`#${id}`);notification&&this.removeNotification(notification)}clearAll(){Array.from(this.notificationPanel.children).forEach((child=>{this.removeNotification(child)}))}handleTouchMove(e){this.currentX=e.touches[0].clientX-this.startX,this.currentTarget.style.transform=`translateX(${this.currentX}px)`}handleOrientationChange(e){this.isBigViewport=e.matches,e.matches}connectedCallback(){this.handleOrientationChange(this.mediaQuery),this.mediaQuery.addEventListener("change",this.handleOrientationChange),this.notificationPanel.addEventListener("touchstart",(e=>{e.target.closest(".close")?this.removeNotification(e.target.closest(".notification")):e.target.closest(".notification")&&(this.swipeThreshold=e.target.closest(".notification").getBoundingClientRect().width/2,this.currentTarget=e.target.closest(".notification"),this.startTime=Date.now(),this.startX=e.touches[0].clientX,this.startY=e.touches[0].clientY,this.notificationPanel.addEventListener("touchmove",this.handleTouchMove,{passive:!0}))}),{passive:!0}),this.notificationPanel.addEventListener("touchend",(e=>{this.endX=e.changedTouches[0].clientX,this.endY=e.changedTouches[0].clientY,this.swipeDistance=Math.abs(this.endX-this.startX),this.swipeTime=Date.now()-this.startTime,this.endX>this.startX?this.swipeDirection="right":this.swipeDirection="left",this.swipeTime50&&this.removeNotification(this.currentTarget,this.swipeDirection):this.swipeDistance>this.swipeThreshold?this.removeNotification(this.currentTarget,this.swipeDirection):this.currentTarget.animate([{transform:`translateX(${this.currentX}px)`},{transform:"none"}],this.animationOptions).onfinish=e=>{e.target.commitStyles(),e.target.cancel()},this.notificationPanel.removeEventListener("touchmove",this.handleTouchMove),this.currentX=0}))}disconnectedCallback(){mediaQueryList.removeEventListener("change",handleOrientationChange)}});class Stack{constructor(){this.items=[]}push(t){this.items.push(t)}pop(){return 0==this.items.length?"Underflow":this.items.pop()}peek(){return this.items[this.items.length-1]}}const popupStack=new Stack,smPopup=document.createElement("template");smPopup.innerHTML=' ',customElements.define("sm-popup",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).append(smPopup.content.cloneNode(!0)),this.allowClosing=!1,this.isOpen=!1,this.offset=0,this.touchStartY=0,this.touchEndY=0,this.touchStartTime=0,this.touchEndTime=0,this.touchEndAnimation=void 0,this.focusable,this.autoFocus,this.mutationObserver,this.popupContainer=this.shadowRoot.querySelector(".popup-container"),this.backdrop=this.shadowRoot.querySelector(".backdrop"),this.dialogBox=this.shadowRoot.querySelector(".popup"),this.popupBodySlot=this.shadowRoot.querySelector(".popup-body slot"),this.popupHeader=this.shadowRoot.querySelector(".popup-top"),this.resumeScrolling=this.resumeScrolling.bind(this),this.setStateOpen=this.setStateOpen.bind(this),this.show=this.show.bind(this),this.hide=this.hide.bind(this),this.handleTouchStart=this.handleTouchStart.bind(this),this.handleTouchMove=this.handleTouchMove.bind(this),this.handleTouchEnd=this.handleTouchEnd.bind(this),this.detectFocus=this.detectFocus.bind(this),this.handleSoftDismiss=this.handleSoftDismiss.bind(this),this.debounce=this.debounce.bind(this)}static get observedAttributes(){return["open"]}get open(){return this.isOpen}animateTo(t,e,i){let s=t.animate(e,{...i,fill:"both"});return s.finished.then((()=>{s.commitStyles(),s.cancel()})),s}resumeScrolling(){let t=document.body.style.top;window.scrollTo(0,-1*parseInt(t||"0")),document.body.style.overflow="",document.body.style.top="initial"}setStateOpen(){if(!this.isOpen||this.offset){let t=window.innerWidth>640?"scale(1.1)":`translateY(${this.offset?`${this.offset}px`:"100%"})`;this.animateTo(this.dialogBox,[{opacity:this.offset?1:0,transform:t},{opacity:1,transform:"none"}],{duration:300,easing:"ease"})}}show(t={}){let{pinned:e=!1,payload:i}=t;if(this.isOpen)return;let s={duration:300,easing:"ease"};return this.payload=i,popupStack.push({popup:this,permission:e}),popupStack.items.length>1&&this.animateTo(popupStack.items[popupStack.items.length-2].popup.shadowRoot.querySelector(".popup"),[{transform:"none"},{transform:window.innerWidth>640?"scale(0.95)":"translateY(-1.5rem)"}],s),this.popupContainer.classList.remove("hide"),this.offset||(this.backdrop.animate([{opacity:0},{opacity:1}],s).onfinish=()=>{this.resolveOpen(this.payload)},this.dispatchEvent(new CustomEvent("popupopened",{bubbles:!0,composed:!0,detail:{payload:this.payload}})),document.body.style.overflow="hidden",document.body.style.top=`-${window.scrollY}px`),this.setStateOpen(),this.pinned=e,this.isOpen=!0,setTimeout((()=>{let t=this.autoFocus||this.focusable?.[0]||this.dialogBox;t&&(t.tagName.includes("-")?t.focusIn():t.focus())}),0),this.hasAttribute("open")||(this.setAttribute("open",""),this.addEventListener("keydown",this.detectFocus),this.resizeObserver.observe(this),this.mutationObserver.observe(this,{attributes:!0,childList:!0,subtree:!0}),this.popupHeader.addEventListener("touchstart",this.handleTouchStart,{passive:!0}),this.backdrop.addEventListener("mousedown",this.handleSoftDismiss)),{opened:new Promise((t=>{this.resolveOpen=t})),closed:new Promise((t=>{this.resolveClose=t}))}}hide(t={}){let{payload:e}=t,i={duration:150,easing:"ease"};this.backdrop.animate([{opacity:1},{opacity:0}],i),this.animateTo(this.dialogBox,[{opacity:1,transform:window.innerWidth>640?"none":`translateY(${this.offset?`${this.offset}px`:"0"})`},{opacity:0,transform:window.innerWidth>640?"scale(1.1)":"translateY(100%)"}],i).finished.finally((()=>{this.popupContainer.classList.add("hide"),this.dialogBox.style="",this.removeAttribute("open"),this.forms.length&&this.forms.forEach((t=>t.reset())),this.dispatchEvent(new CustomEvent("popupclosed",{bubbles:!0,composed:!0,detail:{payload:e||this.payload}})),this.resolveClose(e||this.payload),this.isOpen=!1})),popupStack.pop(),popupStack.items.length?this.animateTo(popupStack.items[popupStack.items.length-1].popup.shadowRoot.querySelector(".popup"),[{transform:window.innerWidth>640?"scale(0.95)":"translateY(-1.5rem)"},{transform:"none"}],i):this.resumeScrolling(),this.resizeObserver.disconnect(),this.mutationObserver.disconnect(),this.removeEventListener("keydown",this.detectFocus),this.popupHeader.removeEventListener("touchstart",this.handleTouchStart,{passive:!0}),this.backdrop.removeEventListener("mousedown",this.handleSoftDismiss)}handleTouchStart(t){this.offset=0,this.popupHeader.addEventListener("touchmove",this.handleTouchMove,{passive:!0}),this.popupHeader.addEventListener("touchend",this.handleTouchEnd,{passive:!0}),this.touchStartY=t.changedTouches[0].clientY,this.touchStartTime=t.timeStamp}handleTouchMove(t){this.touchStartY{this.dialogBox.style.transform=`translateY(${this.offset}px)`})))}handleTouchEnd(t){if(this.touchEndTime=t.timeStamp,cancelAnimationFrame(this.touchEndAnimation),this.touchEndY=t.changedTouches[0].clientY,this.threshold=.3*this.dialogBox.getBoundingClientRect().height,this.touchEndTime-this.touchStartTime>200)if(this.touchEndY-this.touchStartY>this.threshold){if(this.pinned)return void this.setStateOpen();this.hide()}else this.setStateOpen();else if(this.touchEndY>this.touchStartY){if(this.pinned)return void this.setStateOpen();this.hide()}this.popupHeader.removeEventListener("touchmove",this.handleTouchMove,{passive:!0}),this.popupHeader.removeEventListener("touchend",this.handleTouchEnd,{passive:!0})}detectFocus(t){if("Tab"===t.key&&this.focusable.length){if(!this.firstFocusable)for(let e=0;e=0;i--)if(!this.focusable[i].disabled){this.lastFocusable=this.focusable[i];break}t.shiftKey&&document.activeElement===this.firstFocusable?(t.preventDefault(),this.lastFocusable.tagName.includes("SM-")?this.lastFocusable.focusIn():this.lastFocusable.focus()):t.shiftKey||document.activeElement!==this.lastFocusable||(t.preventDefault(),this.firstFocusable.tagName.includes("SM-")?this.firstFocusable.focusIn():this.firstFocusable.focus())}}updateFocusableList(){this.focusable=this.querySelectorAll('sm-button:not([disabled]), button:not([disabled]), [href], sm-input, input:not([readonly]), sm-select, select, sm-checkbox, sm-textarea, textarea, [tabindex]:not([tabindex="-1"])'),this.autoFocus=this.querySelector("[autofocus]"),this.firstFocusable=null,this.lastFocusable=null}handleSoftDismiss(){this.pinned?this.dialogBox.animate([{transform:"translateX(-1rem)"},{transform:"translateX(1rem)"},{transform:"translateX(-0.5rem)"},{transform:"translateX(0.5rem)"},{transform:"translateX(0)"}],{duration:300,easing:"ease"}):this.hide()}debounce(t,e){let i=null;return(...s)=>{window.clearTimeout(i),i=window.setTimeout((()=>{t.apply(null,s)}),e)}}connectedCallback(){this.popupBodySlot.addEventListener("slotchange",this.debounce((()=>{this.forms=this.querySelectorAll("sm-form"),this.updateFocusableList()}),0)),this.resizeObserver=new ResizeObserver((t=>{t.forEach((t=>{if(t.contentBoxSize){let e=Array.isArray(t.contentBoxSize)?t.contentBoxSize[0]:t.contentBoxSize;this.threshold=.3*e.blockSize.height}else this.threshold=.3*t.contentRect.height}))})),this.mutationObserver=new MutationObserver((t=>{this.updateFocusableList()}))}disconnectedCallback(){this.resizeObserver.disconnect(),this.mutationObserver.disconnect(),this.removeEventListener("keydown",this.detectFocus),this.popupHeader.removeEventListener("touchstart",this.handleTouchStart,{passive:!0}),this.backdrop.removeEventListener("mousedown",this.handleSoftDismiss)}attributeChangedCallback(t){"open"===t&&this.hasAttribute("open")&&this.show()}});const smSwitch=document.createElement("template");smSwitch.innerHTML='\t',customElements.define("sm-switch",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).append(smSwitch.content.cloneNode(!0)),this.switch=this.shadowRoot.querySelector(".switch"),this.input=this.shadowRoot.querySelector("input"),this.isChecked=!1,this.isDisabled=!1,this.dispatch=this.dispatch.bind(this)}static get observedAttributes(){return["disabled","checked"]}get disabled(){return this.isDisabled}set disabled(e){e?this.setAttribute("disabled",""):this.removeAttribute("disabled")}get checked(){return this.isChecked}set checked(e){e?this.setAttribute("checked",""):this.removeAttribute("checked")}get value(){return this.isChecked}reset(){}dispatch(){this.dispatchEvent(new CustomEvent("change",{bubbles:!0,composed:!0,detail:{value:this.isChecked}}))}connectedCallback(){this.addEventListener("keydown",(e=>{" "!==e.key||this.isDisabled||(e.preventDefault(),this.input.click())})),this.input.addEventListener("click",(e=>{this.input.checked?this.checked=!0:this.checked=!1,this.dispatch()}))}attributeChangedCallback(e,t,n){t!==n&&("disabled"===e?this.hasAttribute("disabled")?this.disabled=!0:this.disabled=!1:"checked"===e&&(this.hasAttribute("checked")?(this.isChecked=!0,this.input.checked=!0):(this.isChecked=!1,this.input.checked=!1)))}});const smSelect=document.createElement("template");smSelect.innerHTML='
',customElements.define("sm-select",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).append(smSelect.content.cloneNode(!0)),this.focusIn=this.focusIn.bind(this),this.reset=this.reset.bind(this),this.open=this.open.bind(this),this.collapse=this.collapse.bind(this),this.toggle=this.toggle.bind(this),this.handleOptionsNavigation=this.handleOptionsNavigation.bind(this),this.handleOptionSelection=this.handleOptionSelection.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.handleClickOutside=this.handleClickOutside.bind(this),this.selectOption=this.selectOption.bind(this),this.debounce=this.debounce.bind(this),this.elementsChanged=this.elementsChanged.bind(this),this.availableOptions=[],this.previousOption,this.isOpen=!1,this.label="",this.defaultSelected="",this.isUnderViewport=!1,this.animationOptions={duration:300,fill:"forwards",easing:"ease"},this.optionList=this.shadowRoot.querySelector(".options"),this.selection=this.shadowRoot.querySelector(".selection"),this.selectedOptionText=this.shadowRoot.querySelector(".selected-option-text")}static get observedAttributes(){return["disabled","label","readonly"]}get value(){return this.getAttribute("value")}set value(t){const e=this.availableOptions.find((e=>e.getAttribute("value")===t));e?(this.setAttribute("value",t),this.selectOption(e)):console.warn(`There is no option with ${t} as value`)}debounce(t,e){let n=null;return(...i)=>{window.clearTimeout(n),n=window.setTimeout((()=>{t.apply(null,i)}),e)}}reset(t=!0){if(this.availableOptions[0]&&this.previousOption!==this.availableOptions[0]){const e=this.availableOptions.find((t=>t.hasAttribute("selected")))||this.availableOptions[0];this.value=e.getAttribute("value"),t&&this.fireEvent()}}selectOption(t){this.previousOption!==t&&(this.querySelectorAll("[selected").forEach((t=>t.removeAttribute("selected"))),this.selectedOptionText.textContent=`${this.label}${t.textContent}`,t.setAttribute("selected",""),this.previousOption=t)}focusIn(){this.selection.focus()}open(){this.availableOptions.forEach((t=>t.setAttribute("tabindex",0))),this.optionList.classList.remove("hidden"),this.isUnderViewport=this.getBoundingClientRect().bottom+this.optionList.getBoundingClientRect().height>window.innerHeight,this.isUnderViewport?this.setAttribute("isUnder",""):this.removeAttribute("isUnder"),this.optionList.animate([{transform:`translateY(${this.isUnderViewport?"":"-"}0.5rem)`,opacity:0},{transform:"translateY(0)",opacity:1}],this.animationOptions),this.setAttribute("open",""),this.style.zIndex=1e3,(this.availableOptions.find((t=>t.hasAttribute("selected")))||this.availableOptions[0]).focus(),document.addEventListener("mousedown",this.handleClickOutside),this.isOpen=!0}collapse(){this.removeAttribute("open"),this.optionList.animate([{transform:"translateY(0)",opacity:1},{transform:`translateY(${this.isUnderViewport?"":"-"}0.5rem)`,opacity:0}],this.animationOptions).onfinish=()=>{this.availableOptions.forEach((t=>t.removeAttribute("tabindex"))),document.removeEventListener("mousedown",this.handleClickOutside),this.optionList.classList.add("hidden"),this.isOpen=!1,this.style.zIndex="auto"}}toggle(){this.isOpen||this.hasAttribute("disabled")?this.collapse():this.open()}fireEvent(){this.dispatchEvent(new CustomEvent("change",{bubbles:!0,composed:!0,detail:{value:this.value}}))}handleOptionsNavigation(t){"ArrowUp"===t.key?(t.preventDefault(),document.activeElement.previousElementSibling?document.activeElement.previousElementSibling.focus():this.availableOptions[this.availableOptions.length-1].focus()):"ArrowDown"===t.key&&(t.preventDefault(),document.activeElement.nextElementSibling?document.activeElement.nextElementSibling.focus():this.availableOptions[0].focus())}handleOptionSelection(t){this.previousOption!==document.activeElement&&(this.value=document.activeElement.getAttribute("value"),this.fireEvent())}handleClick(t){t.target===this?this.toggle():(this.handleOptionSelection(),this.collapse())}handleKeydown(t){t.target===this?this.isOpen&&"ArrowDown"===t.key?(t.preventDefault(),(this.availableOptions.find((t=>t.hasAttribute("selected")))||this.availableOptions[0]).focus(),this.handleOptionSelection(t)):" "===t.key&&(t.preventDefault(),this.toggle()):(this.handleOptionsNavigation(t),this.handleOptionSelection(t),["Enter"," ","Escape","Tab"].includes(t.key)&&(t.preventDefault(),this.collapse(),this.focusIn()))}handleClickOutside(t){this.isOpen&&!this.contains(t.target)&&this.collapse()}elementsChanged(){this.availableOptions=[...this.querySelectorAll("sm-option")],this.reset(!1),this.defaultSelected=this.value}connectedCallback(){this.setAttribute("role","listbox"),this.hasAttribute("disabled")||this.hasAttribute("readonly")||(this.selection.setAttribute("tabindex","0"),this.addEventListener("click",this.handleClick),this.addEventListener("keydown",this.handleKeydown));const t=this.debounce(this.elementsChanged,100);this.shadowRoot.querySelector("slot").addEventListener("slotchange",t),this.mutationObserver=new MutationObserver((e=>{let n=!1;if(e.forEach((e=>{switch(e.type){case"childList":t();break;case"attributes":n=!0}})),n){const t=this.availableOptions.find((t=>t.hasAttribute("selected")))||this.availableOptions[0];this.selectedOptionText.textContent=`${this.label}${t.textContent}`,this.setAttribute("value",t.getAttribute("value"))}})),this.mutationObserver.observe(this,{subtree:!0,childList:!0,attributeFilter:["selected"]}),new IntersectionObserver(((t,e)=>{t.forEach((t=>{if(t.isIntersecting){this.selection.getBoundingClientRect().left *{ padding: 0; margin: 0; -webkit-box-sizing: border-box; box-sizing: border-box;} :host{ display: -webkit-box; display: -ms-flexbox; display: flex; overflow: hidden; border-radius: var(--border-radius, 0.3rem);}.option{ position: relative; display: flex; -webkit-box-align: center; -ms-flex-align: center; align-items: center; width: 100%; gap: 0.5rem; padding: var(--padding, 0.6rem 1rem); cursor: pointer; outline: none; user-select: none;}.option::before{ position: absolute; content: \'\'; display: block; width: 0.2rem; height: 1em; left: 0; border-radius: 0 1em 1em 0; background: rgba(var(--text-color,(17,17,17)), 0.5); transition: all 0.2s ease-in-out; opacity: 0;}:host(:focus){ outline: none; background: rgba(var(--text-color,(17,17,17)), 0.1);}:host(:focus) .option::before{ opacity: 1}:host([selected]) .option::before{ opacity: 1; background: var(--accent-color, teal);}@media (hover: hover){ .option:hover{ background: rgba(var(--text-color,(17,17,17)), 0.1); } :host(:not([selected]):hover) .option::before{ opacity: 1 }}
',customElements.define("sm-option",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).append(smOption.content.cloneNode(!0))}connectedCallback(){this.setAttribute("role","option")}});const spinner=document.createElement("template");spinner.innerHTML='';class SpinnerLoader extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).append(spinner.content.cloneNode(!0))}}window.customElements.define("sm-spinner",SpinnerLoader);const smTextarea=document.createElement("template");smTextarea.innerHTML=' ',customElements.define("sm-textarea",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).append(smTextarea.content.cloneNode(!0)),this.textarea=this.shadowRoot.querySelector("textarea"),this.textareaBox=this.shadowRoot.querySelector(".textarea"),this.placeholder=this.shadowRoot.querySelector(".placeholder"),this.reflectedAttributes=["disabled","required","readonly","rows","minlength","maxlength"],this.reset=this.reset.bind(this),this.focusIn=this.focusIn.bind(this),this.fireEvent=this.fireEvent.bind(this),this.checkInput=this.checkInput.bind(this)}static get observedAttributes(){return["disabled","value","placeholder","required","readonly","rows","minlength","maxlength"]}get value(){return this.textarea.value}set value(e){this.setAttribute("value",e),this.fireEvent()}get disabled(){return this.hasAttribute("disabled")}set disabled(e){e?this.setAttribute("disabled",""):this.removeAttribute("disabled")}get isValid(){return this.textarea.checkValidity()}reset(){this.setAttribute("value","")}focusIn(){this.textarea.focus()}fireEvent(){let e=new Event("input",{bubbles:!0,cancelable:!0,composed:!0});this.dispatchEvent(e)}checkInput(){this.hasAttribute("placeholder")&&""!==this.getAttribute("placeholder")&&(""!==this.textarea.value?this.placeholder.classList.add("hide"):this.placeholder.classList.remove("hide"))}connectedCallback(){this.textarea.addEventListener("input",(e=>{this.textareaBox.dataset.value=this.textarea.value,this.checkInput()}))}attributeChangedCallback(e,t,n){this.reflectedAttributes.includes(e)?this.hasAttribute(e)?this.textarea.setAttribute(e,this.getAttribute(e)?this.getAttribute(e):""):this.textContent.removeAttribute(e):"placeholder"===e?this.placeholder.textContent=this.getAttribute("placeholder"):"value"===e&&(this.textarea.value=n,this.textareaBox.dataset.value=n,this.checkInput())}});const textField=document.createElement("template");textField.innerHTML='
',customElements.define("text-field",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).append(textField.content.cloneNode(!0)),this.textField=this.shadowRoot.querySelector(".text-field"),this.textContainer=this.textField.children[0],this.editButton=this.textField.querySelector(".edit-button"),this.isTextEditable=!1,this.isDisabled=!1}static get observedAttributes(){return["disabled"]}get value(){return this.text}set value(val){this.text=val,this.textContainer.textContent=val,this.setAttribute("value",val)}set disabled(val){this.isDisabled=val,this.isDisabled?this.setAttribute("disabled",""):this.removeAttribute("disabled")}setEditable=()=>{this.isTextEditable||(this.textContainer.contentEditable=!0,this.setAttribute("editable",""),this.textContainer.focus(),document.execCommand("selectAll",!1,null),this.editButton.textContent="Done",this.isTextEditable=!0)};setNonEditable=()=>{this.isTextEditable&&(this.textContainer.contentEditable=!1,this.removeAttribute("editable"),this.text!==this.textContainer.textContent.trim()&&(this.setAttribute("value",this.textContainer.textContent),this.text=this.textContainer.textContent.trim(),this.dispatchEvent(new CustomEvent("change",{bubbles:!0,cancelable:!0,composed:!0}))),this.editButton.textContent="Edit",this.isTextEditable=!1)};toggleEditable=()=>{this.isTextEditable?this.setNonEditable():this.setEditable()};revert=()=>{this.textContainer.isContentEditable&&(this.value=this.text,this.setNonEditable())};connectedCallback(){this.text,this.hasAttribute("value")&&(this.text=this.getAttribute("value"),this.textContainer.textContent=this.text),this.hasAttribute("disabled")?this.isDisabled=!0:this.isDisabled=!1,this.isDisabled||(this.textContainer.addEventListener("dblclick",this.setEditable),this.editButton.addEventListener("click",this.toggleEditable))}attributeChangedCallback(name){"disabled"===name&&(this.hasAttribute("disabled")?(this.editButton.classList.add("hide"),this.textContainer.removeEventListener("dblclick",this.setEditable),this.editButton.removeEventListener("click",this.toggleEditable),this.revert()):(this.editButton.classList.remove("hide"),this.textContainer.addEventListener("dblclick",this.setEditable),this.editButton.addEventListener("click",this.toggleEditable)))}disconnectedCallback(){this.textContainer.removeEventListener("dblclick",this.setEditable),this.editButton.removeEventListener("click",this.toggleEditable)}});const themeToggle=document.createElement("template");themeToggle.innerHTML=' ';class ThemeToggle extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).append(themeToggle.content.cloneNode(!0)),this.isChecked=!1,this.hasTheme="light",this.toggleState=this.toggleState.bind(this),this.fireEvent=this.fireEvent.bind(this),this.handleThemeChange=this.handleThemeChange.bind(this)}static get observedAttributes(){return["checked"]}daylight(){this.hasTheme="light",document.body.dataset.theme="light",this.setAttribute("aria-checked","false")}nightlight(){this.hasTheme="dark",document.body.dataset.theme="dark",this.setAttribute("aria-checked","true")}toggleState(){if(!document.startViewTransition)return this.toggleAttribute("checked"),void this.fireEvent();document.startViewTransition((()=>{this.toggleAttribute("checked"),this.fireEvent()}))}handleKeyDown(e){" "===e.key&&this.toggleState()}handleThemeChange(e){e.detail.theme!==this.hasTheme&&("dark"===e.detail.theme?this.setAttribute("checked",""):this.removeAttribute("checked"))}fireEvent(){this.dispatchEvent(new CustomEvent("themechange",{bubbles:!0,composed:!0,detail:{theme:this.hasTheme}}))}connectedCallback(){this.setAttribute("role","switch"),this.setAttribute("aria-label","theme toggle"),"dark"===localStorage.getItem(`${window.location.hostname}-theme`)?(this.nightlight(),this.setAttribute("checked","")):"light"===localStorage.getItem(`${window.location.hostname}-theme`)?(this.daylight(),this.removeAttribute("checked")):window.matchMedia("(prefers-color-scheme: dark)").matches?(this.nightlight(),this.setAttribute("checked","")):(this.daylight(),this.removeAttribute("checked")),this.addEventListener("click",this.toggleState),this.addEventListener("keydown",this.handleKeyDown),document.addEventListener("themechange",this.handleThemeChange)}disconnectedCallback(){this.removeEventListener("click",this.toggleState),this.removeEventListener("keydown",this.handleKeyDown),document.removeEventListener("themechange",this.handleThemeChange)}attributeChangedCallback(e,t,n){"checked"===e&&(this.hasAttribute("checked")?(this.nightlight(),localStorage.setItem(`${window.location.hostname}-theme`,"dark")):(this.daylight(),localStorage.setItem(`${window.location.hostname}-theme`,"light")))}}window.customElements.define("theme-toggle",ThemeToggle);const colorGrid=document.createElement("template");colorGrid.innerHTML='\n\n
\n
',customElements.define("color-grid",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}).append(colorGrid.content.cloneNode(!0)),this.colorArray=[],this.container=this.shadowRoot.querySelector(".color-tile-container"),this.handleChange=this.handleChange.bind(this),this.setCheckMark=this.setCheckMark.bind(this)}set colors(arr){this.colorArray=arr,this.renderTiles()}set selectedColor(color){if(this.colorArray.includes(color)&&this.container.querySelector(`[data-color="${color}"]`)){const selectedTile=this.container.querySelector(`[data-color="${color}"]`);selectedTile&&(selectedTile.querySelector("input").checked=!0,this.setCheckMark(selectedTile))}}randString(length){let result="",characters="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";for(let i=0;i{const label=document.createElement("label");label.classList.add("color-tile"),label.setAttribute("data-color",color),color.includes("--")?label.setAttribute("style",`background-color: var(${color})`):label.setAttribute("style",`background-color: ${color}`),label.innerHTML=`\n \n `,frag.append(label)})),this.container.append(frag)}setCheckMark(target){target.parentNode.querySelectorAll(".checkmark").forEach((checkmark=>checkmark.remove()));const checkMark=document.createElement("div");checkMark.classList.add("checkmark"),checkMark.innerHTML='\n \n ',target.append(checkMark)}handleChange(e){const clickedTile=e.target.closest(".color-tile");this.setCheckMark(clickedTile);const clickedTileColor=clickedTile.dataset.color,tileSelected=new CustomEvent("colorselected",{bubbles:!0,composed:!0,detail:{value:clickedTileColor}});this.dispatchEvent(tileSelected)}connectedCallback(){this.container.addEventListener("change",this.handleChange)}disconnectedCallback(){this.container.removeEventListener("change",this.handleChange)}}),window.customElements.define("keys-generator",class extends HTMLElement{constructor(){super(),this.innerHTML='\n \n
\n
\n \n
\n \n

Keep your keys safe!

\n
\n

Don\'t share with anyone. Once lost private key can\'t be recovered.

\n
\n
\n
\n
\n
FLO address
\n \n
\n
\n
Private key
\n \n
\n
\n \n

You can use these FLO credentials with other RanchiMall apps too.

\n
\n '}get keys(){return{floID:this.querySelector("#generated_flo_address").value,privKey:this.querySelector("#generated_private_key").value}}generateKeys(){const{floID:floID,privKey:privKey}=floCrypto.generateNewID();this.querySelector("#generated_flo_address").value=floID,this.querySelector("#generated_private_key").value=privKey}clearKeys(){this.querySelector("#generated_flo_address").value="",this.querySelector("#generated_private_key").value=""}});const adBlockerWarning=document.createElement("template");adBlockerWarning.innerHTML='\n \n
\n ',window.customElements.define("adblocker-warning",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}),this.shadowRoot.appendChild(adBlockerWarning.content.cloneNode(!0))}connectedCallback(){const isBrave=void 0!==navigator.brave;this.shadowRoot.querySelector("#adblocker_warning").innerHTML=`\n \n

Ad-Blocker Detected!

\n

\n Please disable your ad-blocker for optimal experience. Our app doesn't show ads or track activity. \n

\n ${isBrave?"If you have enabled Brave shield then disable it also.":""}\n `}});const IDBsupport=document.createElement("template");IDBsupport.innerHTML='\n \n \n ',window.customElements.define("idb-support",class extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}),this.shadowRoot.appendChild(IDBsupport.content.cloneNode(!0))}connectedCallback(){const thisComponent=this;if("indexedDB"in window){const request=window.indexedDB.open("testDB",1);request.onerror=function(event){console.log("IndexedDB is not allowed or encountered an error."),thisComponent.shadowRoot.querySelector("#idb_support").style.display="flex"},request.onsuccess=function(event){thisComponent.remove()}}else console.log("IndexedDB is not supported.")}}); \ No newline at end of file