/**
 * Copyright 2020 The Pennsylvania State University
 * @license Apache-2.0, see License.md for full text.
 */
import{LitElement as e,html as t,css as i}from"../../lit/index.js";import{SimpleFilterMixin as o}from"../simple-filter/simple-filter.js";import{getRange as s}from"../utils/utils.js";import"../simple-popover/simple-popover.js";class SimpleAutocomplete extends(o(e)){static get styles(){return[i`
        :host {
          display: inline-flex;
        }
        :host([hidden]) {
          display: none;
        }
        #input {
          border: none;
          min-width: 10px;
          outline: none;
          padding: 0 2px;
        }
        simple-popover {
          max-width: var(--simple-autocomplete-popover-max-width, 50vw);
          padding: 0;
          --simple-popover-padding: 0px;
          --simple-popover-border: none;
          --simple-popover-border-color: #eeeeee;
          --simple-popover-border-radius: 0;
        }
        ul {
          margin: 0;
          padding: 0;
          border: var(--simple-autocomplete-ul-border, 1px solid #eeeeee);
        }
        li {
          list-style: none;
          padding: 0;
          margin: 0;
          display: block;
        }
        button {
          font-size: var(--simple-autocomplete-font-size, 14px);
          line-height: var(--simple-autocomplete-line-height, 1.5);
          display: block;
          border: none;
          border-bottom: var(
            --simple-autocomplete-border-bottom,
            1px solid #eeeeee
          );
          padding: 6px 12px;
          font-weight: 500;
          width: 100%;
          background-color: transparent;
          max-height: var(
            --simple-autocomplete-max-height,
            54px
          ); /* font * line-height * 2 + padding */
          text-overflow: ellipsis;
          overflow: hidden;
          text-align: left;
          color: var(--simple-autocomplete-color, #333333);
        }
        ul li:first-child button {
          border-top: none;
        }
        button:hover,
        button:active,
        button:focus {
          background-color: var(
            --simple-autocomplete-button-hover-background-color,
            #eeeeee
          );
          color: var(--simple-autocomplete-hover-color, #000000);
          outline: none;
        }
        .no-results {
          font-size: var(--simple-autocomplete-font-size, 16px);
          padding: 4px 8px;
        }
        simple-icon-lite {
          color: var(--simple-autocomplete-color, #333333);
          --simple-icon-width: var(--simple-autocomplete-icon-size, 16px);
          --simple-icon-height: var(--simple-autocomplete-icon-size, 16px);
          margin-right: 2px;
          vertical-align: middle;
        }
      `]}setValue(e){this.processInput(e),this.hideInput||(this.$input.innerText=e)}processInput(e){this.opened=!0,this.value=e,this.like=this.value}inputChanged(e){this.processInput(this.$input.innerText)}render(){return t`
      ${this.hideInput?"":t`<span
            part="input"
            id="input"
            name="input"
            @input="${this.inputChanged}"
            contenteditable
            @keydown="${this.a11yInputKeys}"
          ></span>`}
      <simple-popover
        part="popover"
        auto
        part="simple-popover"
        ?hidden="${!this.opened||0===this.filtered.length}"
        position="bottom"
        for="input"
      >
        ${this.filtered.length>0&&this.opened?t` <ul
              part="list"
              role="listbox"
              @keydown="${this.a11yListKeys}"
            >
              ${this.filtered.map(((e,i)=>t`${i<this.itemLimit?t`<li
                        role="option"
                        part="list-item"
                        value="${e.value}"
                        data-index="${i}"
                      >
                        <button
                          part="button"
                          value="${e.value}"
                          data-index="${i}"
                          @click="${this.itemSelect}"
                        >
                          ${e.icon?t`<simple-icon-lite
                                icon="${e.icon}"
                              ></simple-icon-lite>`:""}${e.label}
                        </button>
                      </li>`:""}`))}
            </ul>`:t`<div class="no-results" part="no-result">No results</div>`}
      </simple-popover>
    `}a11yListKeys(e){if(this.filtered.length>0&&this.opened)switch(e.key){case"ArrowDown":"BUTTON"===this.shadowRoot.activeElement.tagName&&this.shadowRoot.activeElement.parentNode.nextElementSibling&&this.shadowRoot.activeElement.parentNode.nextElementSibling.children&&(this.hardStopEvent(e),this.shadowRoot.activeElement.parentNode.nextElementSibling.children[0].focus());break;case"Escape":this.hardStopEvent(e),this.resetFocusOnInput();break;case"ArrowUp":"BUTTON"===this.shadowRoot.activeElement.tagName&&this.shadowRoot.activeElement.parentNode.previousElementSibling&&this.shadowRoot.activeElement.parentNode.previousElementSibling.children&&(this.hardStopEvent(e),this.shadowRoot.activeElement.parentNode.previousElementSibling.children[0].focus())}}hardStopEvent(e){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),e.detail.keyboardEvent&&(e.detail.keyboardEvent.preventDefault(),e.detail.keyboardEvent.stopPropagation(),e.detail.keyboardEvent.stopImmediatePropagation())}a11yInputKeys(e){if(this.filtered.length>0&&this.opened)switch(e.key){case"ArrowDown":this.shadowRoot.querySelector("button")&&(this.hardStopEvent(e),this.shadowRoot.querySelector("button").focus());break;case"Escape":this.hardStopEvent(e),this.opened=!1;break;case"ArrowUp":this.shadowRoot.querySelectorAll("button").length&&(this.hardStopEvent(e),this.shadowRoot.querySelectorAll("button")[this.shadowRoot.querySelectorAll("button").length-1].focus())}}constructor(){super(),this.itemLimit=6,this.hideInput=!1,this.selectionPosition=!1,this.value="",this.opened=!1,this.addEventListener("mousedown",(e=>{this._clicking=!0})),this.addEventListener("mouseup",(e=>{this._clicking=!1})),this.addEventListener("focusout",(e=>{this._clicking?this._clicking=!1:(this.hideInput||(this.value=this.$input.innerText),this.opened=!1)}))}firstUpdated(e){super.firstUpdated&&super.firstUpdated(e),!this.selectionPosition&&this.shadowRoot.querySelector("#input")&&(this.$input=this.shadowRoot.querySelector("#input"),this.shadowRoot.querySelector("simple-popover").target=this.$input,this.$input.addEventListener("focusin",(e=>{this.value&&!this._ignoreFocusOpen&&(this.opened=!0,this.hideInput||(this.value=this.$input.innerText,this.like=this.$input.innerText)),this._ignoreFocusOpen=!1})))}getSelection(){if(this.$input){if(this.$input.getSelection)return this.$input.getSelection();if(void 0===this.$input.endOffset&&s(this.$input))return s(this.$input)}return globalThis.getSelection()}getRange(){let e=this.getSelection();return e&&e.getRangeAt&&e.rangeCount?e.getRangeAt(0):e||!1}resetFocusOnInput(){if(this.opened=!1,this._ignoreFocusOpen=!0,void 0===this.$input.endOffset&&(this.$input.focus(),null!=this.$input.getAttribute("contenteditable"))){var e=globalThis.document.createRange(),t=this.getSelection();e.setEnd(this.$input.childNodes[0],this.$input.innerText.length),e.collapse(!0),t.removeAllRanges(),t.addRange(e)}}itemSelect(e){this.value=e.target.parentNode.getAttribute("value"),this.hideInput||(this.$input.innerText=this.value),this.dispatchEvent(new CustomEvent("item-selected",{detail:{value:this.value}})),this._clicking=!1,this.resetFocusOnInput()}static get properties(){return{opened:{type:Boolean,reflect:!0},hideInput:{type:Boolean,attribute:"hide-input"},selectionPosition:{type:Boolean,attribute:"selection-position"},value:{type:String},itemLimit:{type:Number,attribute:"item-limit"}}}static get tag(){return"simple-autocomplete"}updated(e){e.forEach(((e,t)=>{if("value"==t&&this.dispatchEvent(new CustomEvent(`${t}-changed`,{detail:{value:this[t]}})),"opened"==t&&this.opened&&(this.shadowRoot.querySelector("simple-popover").updatePosition(),setTimeout((()=>{this.selectionPosition&&this.getRange()&&(this.$input=this.getRange(),["TEXTAREA","INPUT"].includes(document.activeElement.tagName)&&(this.$input=globalThis.document.activeElement),this.shadowRoot.querySelector("simple-popover").target=this.$input,this.shadowRoot.querySelector("simple-popover").updatePosition())}),0)),"items"==t&&this.items.length>0&&!this._ignore){this._ignore=!0;for(var i=0;i<this.items.length;i++)this.items[i].title||(this.items[i].title=Object.keys(this.items[i]).map((e=>"icon"!==e&&this.items[i][e])).join(" ")),this.items[i].icon&&(import("../simple-icon/lib/simple-icon-lite.js"),import("../simple-icon/lib/simple-icons.js"));this._ignore=!1}}))}}customElements.define(SimpleAutocomplete.tag,SimpleAutocomplete);export{SimpleAutocomplete};