import{LitElement as t,html as i,css as e}from"../../../lit/index.js";import{SimpleFieldsFieldBehaviors as s}from"./simple-fields-field.js";class SimpleFieldsCombo extends(s(t)){static get tag(){return"simple-fields-combo"}static get styles(){return[super.styles,e`
        :host([expanded]) {
          overflow: visible;
        }
        :host(:focus-within),
        :host(:hover),
        ul:hover,
        li:hover {
          z-index: 2;
        }
        .input-option {
          display: flex;
          align-items: center;
          justify-content: space-between;
          flex: 1 1 100%;
        }
        .box-input {
          flex: 1 1 auto;
        }
        ul[role="listbox"] {
          opacity: 0;
          position: absolute;
          list-style: none;
          max-height: var(--simple-fields-combo-max-height, 12em);
          max-width: 100%;
          left: 0;
        }
        :host([align-right]) ul[role="listbox"] {
          right: 0;
          left: unset;
        }
        :host([justify]) ul[role="listbox"] {
          right: 0;
          left: 0;
        }
        :host([expanded]:hover) ul[role="listbox"],
        :host([expanded]:focus-within) ul[role="listbox"] {
          opacity: 1;
        }

        ul[role="listbox"] li[role="option"] {
          margin: 0;
          padding: 0;
          padding-left: 0.125em;
          border-top: 1px solid transparent;
          border-bottom: 1px solid transparent;
          background-color: var(--simple-fields-background-color, white);
        }

        [role="listbox"] [role="option"] {
          display: block;
          margin: 0.25em;
          padding: 0;
          font-size: 100%;
        }

        [role="listbox"] [role="option"][aria-selected="true"] {
          background-color: var(--simple-fields-active-color, #eeeeee);
        }

        [role="listbox"].focus [role="option"][aria-selected="true"] {
          background-color: var(--simple-fields-accent-color-light, #d9eaff);
          border-color: var(--simple-fields-accent-color, #3f51b5);
        }

        [role="listbox"] li[role="option"]:hover {
          background-color: var(--simple-fields-accent-color-light, #d9eaff);
        }
        ::slotted([slot="prefix"]:not(:empty)) {
          margin-right: 0.25em;
        }
        ::slotted([slot="suffix"]:not(:empty)) {
          margin: 0 0.25em;
        }
      `]}static get properties(){return{...super.properties,activeDescendant:{type:String},alignRight:{type:Boolean,reflect:!0,attribute:"align-right"},expanded:{type:Boolean,reflect:!0},justify:{type:Boolean,reflect:!0},filter:{type:String},filteredOptions:{type:Array},inputFocus:{type:Boolean},inputHover:{type:Boolean},listFocus:{type:Boolean},listHover:{type:Boolean},hoveredOption:{type:Object}}}constructor(){super(),this.expanded=!1,this.filter="",this.filteredOptions=[],this.inputFocus=!1,this.inputHover=!1,this.isNone=!0,this.isList=!1,this.isBoth=!1,this.listFocus=!1,this.listHover=!1,this.option=!1,this.autocomplete="none"}get stateInfo(){return{activeDescendant:this.activeDescendant,filteredOptions:this.filteredOptions,filter:this.filter,option:this.option,_selectedOption:this._selectedOption,value:this.value,firstOption:this.firstOption,lastOption:this.lastOption,input:!!this.input&&this.input.value}}get fieldElementTag(){return"input"}firstUpdated(t){super.firstUpdated&&super.firstUpdated(t),this.filter=this.value?this.value:"",this.filterOptions(this.filter,this.option)}updated(t){super.updated&&super.updated(t),t.forEach(((t,i)=>{"autocomplete"===i&&this.autocompleteChanged(),"value"===i&&this.value!==t&&this.fieldValueChanged(),"itemsList"!==i&&"options"!==i||this.filterOptions(this.filter,this.option)}))}fieldValueChanged(){this.input&&this.input.value!==this.value&&(this.input.value=this.value),this._fireValueChanged()}autocompleteChanged(){if("string"==typeof this.autocomplete){let t=this.autocomplete.toLowerCase();this.isNone="none"===t,this.isList="list"===t,this.isBoth="both"===t}else this.isNone=!0}get inputTemplate(){return i`
      <input
        .aria-activedescendant="${this.activeDescendant}"
        .aria-autocomplete="${this.autocomplete}"
        .aria-descrbedby="${this.describedBy}"
        .aria-expanded="${this.expanded}"
        aria-haspopup="true"
        .aria-invalid="${this.error?"true":"false"}"
        .aria-owns="${this.id}-list"
        ?autofocus="${this.autofocus}"
        @blur="${this._onInputBlur}"
        @change="${this._handleFieldChange}"
        class="field box-input ${this.inputFocus?"focus":""}"
        @click="${this._onInputClick}"
        ?disabled="${this.disabled}"
        @focus="${this._onInputFocus}"
        @paste="${this._onInputPaste}"
        id="${this.id}"
        @keydown="${this._onInputKeydown}"
        @keyup="${this._onInputKeyup}"
        name="${this.id}"
        .placeholder="${this.placeholder||""}"
        part="option-input"
        ?readonly="${this.readonly}"
        ?required="${this.required}"
        tabindex="0"
        type="text"
        value="${this.value||""}"
      />
    `}get expandButtonTemplate(){return i`
      <simple-icon-button-lite
        icon="arrow-drop-down"
        ?hidden="${this.sortedOptions.length<1}"
        label="open"
        @click="${this._onButtonClick}"
        part="option-icon"
        tabindex="-1"
      >
      </simple-icon-button-lite>
    `}get listboxTemplate(){return i`
      <ul
        .aria-labelledBy="${this.fieldId}-label"
        class="${this.listFocus?"focus":""}"
        data-items="${this.itemsList.join()}"
        data-options="${this.filteredOptions.map((t=>t.value)).join()}"
        ?hidden="${this.isListboxHidden}"
        id="${this.id}-list"
        @mouseout="${this._onListboxMouseout}"
        @mouseover="${this._onListboxMouseover}"
        role="listbox"
        part="listbox"
      >
        ${this.listboxInnerTemplate}
      </ul>
    `}get listboxInnerTemplate(){return(this.filteredOptions||[]).map((t=>this.getListItem(t)))}get isListboxHidden(){return this.hidden||!this.expanded||this.filteredOptions.length<1}getListItem(t){return i`
      <li
        aria-selected="${this._isSelected(t)}"
        id="option${t.id}"
        role="option"
        part="listbox-li"
        @click="${i=>this._onOptionClick(i,t)}"
        @mouseout="${i=>this._onOptionMouseout(i,t)}"
        @mouseover="${i=>this._onOptionMouseover(i,t)}"
      >
        ${this.getListItemInner(t)}
      </li>
    `}getListItemInner(t){return t.value}get fieldMainTemplate(){return i`
      <div class="field-main" part="field-main" ?hidden="${this.hidden}">
        ${this.labelTemplate}
        <div id="field-main-inner" part="field-main-inner">
          ${this.prefixTemplate}
          <span class="input-option" part="option-inner">
            ${this.inputTemplate} ${this.suffixTemplate}
            ${this.expandButtonTemplate}
          </span>
          ${this.listboxTemplate}
        </div>
      </div>
    `}get hasOptions(){return this.filteredOptions.length>0}setActiveDescendant(t){t&&this.listFocus?this.activeDescendant=`option${t.id}`:this.activeDescendant=""}setValue(t){this.filter=t,this.input.setSelectionRange(this.filter.length,this.filter.length),(this.isList||this.isBoth)&&this.filterOptions(this.filter,this.option)}setOption(t,i=!1){t&&(this.option=t,this.setCurrentOptionStyle(this.option),this.setActiveDescendant(this.option),this.isBoth&&(this.value=this.option.value,this.input.value=this.option.value,i?setTimeout((()=>{this.input.setSelectionRange(t.value.length,t.value.length)}),0):setTimeout((()=>{this.input.setSelectionRange(this.filter.length,t.value.length)}),0)))}setVisualFocusTextbox(){this.listFocus=!1,this.inputFocus=!0,this.setActiveDescendant(!1)}setVisualFocusListbox(){this.inputFocus=!1,this.listFocus=!0,this.setActiveDescendant(this.option)}removeVisualFocusAll(){this.inputFocus=!1,this.listFocus=!0,this.option=!1,this.setActiveDescendant(!1)}_onButtonClick(t){this.expanded?this.close(!0):this.open(),this.input.focus(),this.setVisualFocusTextbox()}_onInputClick(t){this.expanded?this.close(!0):this.open()}_onInputBlur(t){this.hoveredOption||(this.listFocus=!1,this.setCurrentOptionStyle(null),this.removeVisualFocusAll(),setTimeout(this.close(!1),300))}_onInputPaste(t){clearTimeout(this.__debounce),this.__debounce=setTimeout((()=>{this.value=this.input.value}),0)}_onInputFocus(t){this.setVisualFocusTextbox(),this.option=!1,this.setCurrentOptionStyle(null)}_onInputKeydown(t){clearTimeout(this.__debounce),this.__debounce=setTimeout((()=>{this.value=this.input.value}),300);var i=!1,e=t.altKey;switch(t.keyCode){case this.keyCode.RETURN:(this.listFocus||this.isBoth)&&this.option&&this.setValue(this.option.value),this.close(!0),i=!0;break;case this.keyCode.DOWN:this.hasOptions&&(this.listFocus||this.isBoth&&this.option?this.setOption(this.nextItem,!0):(this.open(),e||this.setOption(this.firstItem,!0)),this.setVisualFocusListbox()),i=!0;break;case this.keyCode.UP:this.hasOptions&&(this.listFocus||this.isBoth&&this.option?this.setOption(this.previousItem,!0):(this.open(),e||this.setOption(this.lastItem,!0)),this.setVisualFocusListbox()),i=!0;break;case this.keyCode.ESC:this.close(!0),this.setVisualFocusTextbox(),this.setValue(""),this.option=!1,i=!0;break;case this.keyCode.TAB:this.close(!0),this.listFocus&&this.option&&this.setValue(this.option.value)}i&&(t.stopPropagation(),t.preventDefault())}_onInputKeyup(t){this.dispatchEvent(new CustomEvent("combo-input-keyup",{bubbles:!0,cancelable:!0,composed:!0,detail:t}));var i=!1,e=!1,s=t.key||"";function isPrintableCharacter(t){return 1===t.length&&t.match(/\S/)}if(isPrintableCharacter(s)&&(this.filter+=s),this.input&&(this.input.value||"").length<this.filter.length&&(this.filter=this.input.value||"",this.option=!1),t.keyCode!==this.keyCode.ESC){switch(t.keyCode){case this.keyCode.BACKSPACE:this.setValue(this.input.value),this.setVisualFocusTextbox(),this.setCurrentOptionStyle(!1),this.option=!1,i=!0;break;case this.keyCode.LEFT:case this.keyCode.RIGHT:case this.keyCode.HOME:case this.keyCode.END:this.isBoth?this.filter=this.input.value:(this.option=!1,this.setCurrentOptionStyle(!1)),this.setVisualFocusTextbox(),i=!0;break;default:isPrintableCharacter(s)&&(this.setVisualFocusTextbox(),this.setCurrentOptionStyle(!1),i=!0)}t.keyCode!==this.keyCode.RETURN&&(this.isList||this.isBoth?(e=this.filterOptions(this.filter,this.option))?(!this.expanded&&(this.input.value||"").length&&this.open(),0===e.textComparison.indexOf((this.input.value||"").toLowerCase())?(this.option=e,(this.isBoth||this.listFocus)&&(this.setCurrentOptionStyle(e),this.isBoth&&isPrintableCharacter(s)&&this.setOption(e))):(this.option=!1,this.setCurrentOptionStyle(!1))):(this.close(),this.option=!1,this.setActiveDescendant(!1)):this.input&&(this.input.value||"").length&&this.open()),i&&(t.stopPropagation(),t.preventDefault())}}get sortedOptions(){let t=(this.itemsList||[]).map(((t,i)=>"object"==typeof t?t:{id:i,value:t}));return Object.keys(this.options||{}).sort(((t,i)=>t>i?1:-1)).forEach((i=>t.push({id:t.length,value:this.options[i]}))),t}filterOptions(t,i){"string"!=typeof t&&(t="");var e,s,o,n;for(t=t.toLowerCase(),this.filteredOptions=[],this.firstChars=[],e=0;e<this.sortedOptions.length;e++)(s=this.sortedOptions[e]).id=e,s.textComparison=s.value.toLowerCase(),0!==t.length&&0!==s.textComparison.indexOf(t)||(this.filteredOptions.push(s),o=s.value.trim(),this.firstChars.push(o.substring(0,1).toLowerCase()));if((n=this.filteredOptions.length)>0){this.firstOption=this.filteredOptions[0],this.lastOption=this.filteredOptions[n-1];let t=this.filteredOptions.map((t=>t.textComparison));s=i&&i.textComparison&&t.includes(i.textComparison)?i:this.firstOption}else this.firstOption=!1,s=!1,this.lastOption=!1;return s}setCurrentOptionStyle(t){this._selectedOption=t,this.listbox&&t&&this.shadowRoot&&this.shadowRoot.querySelector(`#option${t.id}`)&&(this.listbox.scrollTop=this.shadowRoot.querySelector(`#option${t.id}`).offsetTop)}_isSelected(t){return t&&this._selectedOption&&t.textComparison===this._selectedOption.textComparison?"true":"false"}_onListboxMouseover(t){this.listHover=!0}_onListboxMouseout(t){this.listHover=!1,this.hoveredOption=void 0,setTimeout(this.close(!1),300)}open(){this.expanded||(this.expanded=!0)}close(t){"boolean"!=typeof t&&(t=!1),!t&&(this.inputFocus||this.hasHover||this.hasHover)||(this.setCurrentOptionStyle(!1),this.expanded=!1,this.setActiveDescendant(!1))}_onOptionClick(t,i){i&&(this.setOption(i),this.setValue(i.value)),this.close(!0)}_onOptionMouseover(t,i){this.hoveredOption=i,this.listHover=!0,this.open()}_onOptionMouseout(t,i){this.listHover=!1,this.hoveredOption=void 0,setTimeout(this.close(!1),300)}get previousItem(){var t,i=this.option?this.option.textComparison:void 0,e=this.firstOption?this.firstOption.textComparison:void 0,s=this.filteredOptions.map((t=>t.textComparison));return i!==e?(t=s.indexOf(i),this.filteredOptions[t-1]):this.lastOption}get nextItem(){var t,i=this.option?this.option.textComparison:void 0,e=this.lastOption?this.lastOption.textComparison:void 0,s=this.filteredOptions.map((t=>t.textComparison));return i!==e?(t=s.indexOf(i),this.filteredOptions[t+1]):this.firstOption}get listbox(){return this._listbox||(this._listbox=this.shadowRoot&&this.shadowRoot.querySelector(`#${this.id}-list`)?this.shadowRoot.querySelector(`#${this.id}-list`):void 0),this._listbox}get input(){return this._input||(this._input=this.field?this.field:this.shadowRoot&&this.shadowRoot.querySelector(`#${this.id}`)?this.shadowRoot.querySelector(`#${this.id}`):void 0),this._input}get keyCode(){return{BACKSPACE:8,TAB:9,RETURN:13,ESC:27,SPACE:32,PAGEUP:33,PAGEDOWN:34,END:35,HOME:36,LEFT:37,UP:38,RIGHT:39,DOWN:40}}}customElements.define(SimpleFieldsCombo.tag,SimpleFieldsCombo);export{SimpleFieldsCombo};