/*
 * 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!
 */
var t;(function(l){l.append="append",l.replace="replace",l.prepend="prepend"})(t||(t={}));class n 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.getInsertMode()===t.replace?this.selectValue(this.linkedField.value):this.valuePicker.selectedIndex=0)};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)&&this.getInsertMode()===t.replace){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)}getInsertMode(){return this.getAttribute("mode")??t.replace}setValue(){const e=this.valuePicker.options[this.valuePicker.selectedIndex].value;switch(this.getInsertMode()){case t.append:this.linkedField.value+=e;break;case t.prepend:this.linkedField.value=e+this.linkedField.value;break;default:this.linkedField.value=e;break}this.linkedField.dispatchEvent(new Event("change",{bubbles:!0,cancelable:!0}))}}window.customElements.define("typo3-formengine-valuepicker",n);export{n as ValuePicker};
