/*
 * This file is part of the TYPO3 CMS project.
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */
class t extends HTMLElement{constructor(){super(),this.valuePicker=null,this.linkedField=null,this.initialValueSet=!1,this.onChange=()=>{this.setValue(),this.valuePicker.blur()},this.linkedFieldOnChange=()=>{this.valuePicker!==null&&this.selectValue(this.linkedField.value)};const e=document.createElement("slot");e.addEventListener("slotchange",()=>this.initializeValuePicker(e)),this.attachShadow({mode:"open"}).append(e)}connectedCallback(){this.linkedField=document.querySelector(this.getAttribute("linked-field")),this.linkedField?.addEventListener("change",this.linkedFieldOnChange),this.initializeValuePicker(this.shadowRoot.querySelector("slot"))}disconnectedCallback(){this.linkedField?.removeEventListener("change",this.linkedFieldOnChange),this.linkedField=null}initializeValuePicker(e){const i=e.assignedElements()[0]??null;if(i!==null&&i.tagName.toLowerCase()!=="select")throw new Error(`ValuePicker could not be initialized. Expected <select> child name, but found: ${i}`);i!==this.valuePicker&&(this.valuePicker?.removeEventListener("change",this.onChange),this.valuePicker=i,this.valuePicker?.addEventListener("change",this.onChange),this.initialValueSet=!1),this.setInitialPickerValue()}setInitialPickerValue(){if(this.linkedField===null||this.valuePicker===null||this.initialValueSet)return;const e=document.getElementsByName(this.linkedField.dataset.formengineInputName)[0]??null;e!==null&&(this.selectValue(e.value),this.initialValueSet=!0)}selectValue(e){this.valuePicker.selectedIndex=Array.from(this.valuePicker.options).findIndex(i=>i.value===e)}setValue(){const e=this.valuePicker.options[this.valuePicker.selectedIndex].value;this.linkedField.value=e,this.linkedField.dispatchEvent(new Event("change",{bubbles:!0,cancelable:!0}))}}window.customElements.define("typo3-formengine-valuepicker",t);export{t as ValuePicker};
