import{__decorate as t}from"tslib";import{html as i}from"lit";import{state as e,query as s,property as h,customElement as o}from"lit/decorators.js";import{s as l}from"./nile-chip.css.esm.js";import{classMap as n}from"lit/directives/class-map.js";import{H as r}from"../internal/slot.esm.js";import{N as a}from"../internal/nile-element.esm.js";import{unsafeHTML as p}from"lit/directives/unsafe-html.js";import{V as c}from"../utilities/visibility-manager.esm.js";import"../internal/accessibility/a11y.state.enum.esm.js";import"../internal/accessibility/a11y.property.enum.esm.js";import"../internal/accessibility/role.enum.esm.js";let d=class extends a{constructor(){super(...arguments),this.hasSlotController=new r(this,"help-text","label"),this.tags=[],this.inputValue="",this.isDropdownOpen=!1,this.tooltips=[],this.chipFocusIndex=null,this.warning=!1,this.noAutoComplete=!1,this.error=!1,this.success=!1,this.noDuplicates=!1,this.label="",this.tagVariant="",this.acceptUserInput=!1,this.addOnBlur=!1,this.clearable=!1,this.placeholder="type here...",this.readonly=!1,this.disabled=!1,this.portal=!1,this.enableVirtualScroll=!1,this.autoCompleteOptions=[],this.filteredAutoCompleteOptions=[],this.value=[],this.noWrap=!1,this.loading=!1,this.errorIndexes=[],this.helpText="",this.errorMessage="",this.filterFunction=(t,i)=>t.toLowerCase().includes(i.toLowerCase()),this.renderItemFunction=t=>t,this.enableVisibilityEffect=!1,this.enableTabClose=!1,this.showTooltip=!1,this.enableTagDelete=!1,this.required=!1,this.openDropdownOnFocus=!0,this.noDropdownClose=!1,this.isSelectingFromDropdown=!1,this.handleDocumentClick=t=>{const i=t.composedPath();this.isSelectingFromDropdown?this.resetDropdownState():i.includes(this)||(this.addOnBlur&&this.acceptUserInput&&this.inputValue&&this.addChipFromInputValue(),this.isDropdownOpen=!1)}}static get styles(){return[l]}resetDropdownState(){this.isSelectingFromDropdown=!1}updated(t){if(super.updated(t),t.has("autoCompleteOptions")){let t=this.autoCompleteOptions;if("string"==typeof t)try{t=JSON.parse(t)}catch(i){t=[]}this.filteredAutoCompleteOptions=Array.isArray(t)?[...t]:[],this.noDuplicates&&(this.filteredAutoCompleteOptions=this.filteredAutoCompleteOptions.filter((t=>!this.value.includes(t))))}t.has("value")&&(this.tags=[...this.value],this.onTagsChanged()),t.has("tags")&&this.onTagsChanged()}async firstUpdated(t){await this.updateComplete;const i=this.noAutoComplete?this.renderRoot.querySelector("nile-input")?.input:this.autoComplete?.inputElement?.input||this.autoComplete?.inputElement;this.visibilityManager=new c({host:this,target:i,enableVisibilityEffect:this.enableVisibilityEffect,enableTabClose:this.enableTabClose,isOpen:()=>this.isDropdownOpen,onAnchorOutOfView:()=>{this.isDropdownOpen=!1,this.autoComplete&&(this.autoComplete.isDropdownOpen=!1),this.emit("nile-visibility-change",{visible:!1,reason:"anchor-out-of-view"})},onDocumentHidden:()=>{this.isDropdownOpen=!1,this.autoComplete&&(this.autoComplete.isDropdownOpen=!1),this.emit("nile-visibility-change",{visible:!1,reason:"document-hidden"})},emit:(t,i)=>this.emit(`nile-${t}`,i)})}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.handleDocumentClick),this.noDuplicates&&(this.filteredAutoCompleteOptions=this.filteredAutoCompleteOptions.filter((t=>!this.value.includes(t)))),this.emit("nile-init")}disconnectedCallback(){super.disconnectedCallback(),this.visibilityManager?.cleanup(),document.removeEventListener("click",this.handleDocumentClick),this.emit("nile-destroy")}markDropdownSelectStart(t){this.isSelectingFromDropdown=!0}render(){const t=this.hasSlotController.test("label");this.hasSlotController.test("help-text");const e=!!this.label||!!t,s=!!this.helpText,h=!!this.errorMessage;return i`
      <div
        part="form-control"
        class=${n({"form-control":!0,"form-control--medium":!0,"form-control--has-label":e,"form-control--has-help-text":s,"nile-chip--disabled":this.disabled})}
      >
        <label
          part="form-control-label"
          class="form-control__label"
          for="input"
          aria-hidden=${e?"false":"true"}
        >
          <slot name="label">${this.label}</slot>
        </label>

        <div
          part='base' 
          class=${n({"nile-chip":!0,"nile-chip--warning":this.warning,"nile-chip--error":this.error,"nile-chip--success":this.success,"nile-chip--no-wrap":this.noWrap,"nile-chip--open":this.isDropdownOpen})}
        >
          ${this.tags.map(((t,e)=>{const s=this.tooltips[e],h=this.enableTagDelete&&this.chipFocusIndex===e;let o="";(t||"number"==typeof t)&&(o=t.toString());const l=i`
              <nile-tag
                class=${n({"nile-chip__tags":!0,"nile-chip__tags--focused":h})}
                aria-selected=${h?"true":"false"}
                .variant=${this.errorIndexes.includes(e)?"error":"normal"}
                @nile-remove=${()=>this.handleRemove(t)}
                removable
                ?pill=${"normal"!==this.tagVariant}
                ?disabled=${this.disabled}
              >
                ${p(o)}
              </nile-tag>
            `;return this.showTooltip&&s?i`
                <nile-lite-tooltip allowHTML .content=${s}>
                  ${l}
                </nile-lite-tooltip>
              `:l}))}

          <div class="nile-chip__auto-complete">
            ${this.noAutoComplete?i`
                  <nile-input
                    .value=${this.inputValue}
                    .placeholder=${this.placeholder}
                    .disabled=${this.disabled}
                    ?no-border=${!0}
                    ?no-outline=${!0}
                    ?no-padding=${!0}
                    @nile-input=${this.handleInputChange}
                    @keydown=${this.handleInputKeydown}
                    @focus=${this.handleFocus}
                    @blur=${this.handleBlur}
                    exportparts="input"
                    ?required=${this.required}
                  ></nile-input>
                `:i`
                  <nile-auto-complete
                    .enableVirtualScroll=${this.enableVirtualScroll}
                    .allMenuItems=${this.filteredAutoCompleteOptions}
                    .filterFunction=${this.filterFunction}
                    .renderItemFunction=${this.renderItemFunction}
                    .showTooltips=${this.showTooltip}
                    .loading="${this.loading}"
                    .value=${this.inputValue}
                    ?isDropdownOpen=${this.isDropdownOpen}
                    .noBorder=${!0}
                    .noOutline=${!0}
                    .noPadding=${!0}
                    .disabled=${this.disabled}
                    .readonly=${this.readonly}
                    .portal=${this.portal}
                    ?openOnFocus=${this.openDropdownOnFocus}
                    exportparts="options__wrapper, input, base"
                    .placeholder=${this.placeholder}
                    @nile-input=${this.handleInputChange}
                    @keydown=${this.handleInputKeydown}
                    @nile-focus=${this.handleFocus}
                    @nile-blur=${this.handleBlur}
                    @nile-complete=${this.handleSelect}
                    @mousedown=${this.markDropdownSelectStart}
                    .noDropdownClose=${this.noDropdownClose}
                    ?required=${this.required}
                  ></nile-auto-complete>
                `}
          </div>
        </div>
        ${s?i` <nile-form-help-text>${this.helpText}</nile-form-help-text> `:""}
        ${h?i`
              <nile-form-error-message
                >${this.errorMessage}</nile-form-error-message
              >
            `:""}
      </div>
    `}handleSelect(t){this.isSelectingFromDropdown=!1,this.resetDropdownState();const i=t.detail.value,e=this.autoCompleteOptions.find((t=>t.name===i||t.id===i));let s=null;if(this.showTooltip)if(e?.tooltip?.content){const{content:t,for:i}=e.tooltip;if(!i||"tag"===i)if(t instanceof Promise){this.tooltips=[...this.tooltips,"Loading..."];const i=this.tooltips.length-1;t.then((t=>{this.tooltips[i]=t,this.requestUpdate()}))}else s=t}else s=e?.name||i;this.noDuplicates&&this.tags.includes(i)||(this.tags=[...this.tags,i],e?.tooltip?.content instanceof Promise||(this.tooltips=[...this.tooltips,s]),this.emit("nile-chip-change",{value:this.tags}),this.resetInput())}handleRemove(t){this.tags=this.tags.filter((i=>i!==t)),this.noDuplicates&&this.autoCompleteOptions.includes(t)&&(this.filteredAutoCompleteOptions=[...this.filteredAutoCompleteOptions,t]),this.emit("nile-chip-change",{value:this.tags})}handleInputChange(t){this.inputValue=t.detail.value}addChipFromInputValue(){return this.noDuplicates&&this.tags.includes(this.inputValue)?(this.emit("nile-duplicates-blocked"),!1):(this.tags=[...this.tags,this.inputValue],this.showTooltip?this.tooltips=[...this.tooltips,this.inputValue]:this.tooltips=[...this.tooltips,null],this.inputValue="",this.visibilityManager?.cleanup(),this.emit("nile-chip-change",{value:this.tags}),!0)}handleInputKeydown(t){if(this.enableTagDelete&&("Backspace"===t.key||"Delete"===t.key)&&!this.inputValue&&!this.readonly&&!this.disabled){if(0===this.tags.length)return void(this.chipFocusIndex=null);if(t.preventDefault(),null===this.chipFocusIndex)return this.chipFocusIndex=this.tags.length-1,void this.requestUpdate();const i=this.chipFocusIndex;return this.tags[i],this.tags=this.tags.filter(((t,e)=>e!==i)),this.tooltips=this.tooltips.filter(((t,e)=>e!==i)),this.emit("nile-chip-change",{value:this.tags}),void(this.tags.length>0?this.chipFocusIndex=Math.max(0,i-1):this.chipFocusIndex=null)}if(this.readonly){if(!["ArrowUp","ArrowDown","Enter","Tab"].includes(t.key))return void t.preventDefault()}this.acceptUserInput&&("Tab"===t.key&&t.preventDefault(),"Enter"!==t.key&&"Tab"!==t.key||!this.inputValue||this.noDuplicates&&this.tags.includes(this.inputValue)||(t.preventDefault(),this.tags=[...this.tags,this.inputValue],this.showTooltip?this.tooltips=[...this.tooltips,this.inputValue]:this.tooltips=[...this.tooltips,null],this.resetInput(),this.emit("nile-chip-change",{value:this.tags})),"Enter"!==t.key&&"Tab"!==t.key||!this.inputValue||!this.noDuplicates&&!this.tags.includes(this.inputValue)||this.emit("nile-duplicates-blocked"))}handleFocus(){this.noAutoComplete||(this.visibilityManager?.setup(),this.isDropdownOpen=!0)}handleBlur(){this.isSelectingFromDropdown||this.addOnBlur&&this.acceptUserInput&&this.inputValue&&this.addChipFromInputValue()}onTagsChanged(){this.noDuplicates&&(this.filteredAutoCompleteOptions=this.filteredAutoCompleteOptions.filter((t=>!this.tags.includes(t))))}resetInput(){this.inputValue="",this.isDropdownOpen=!1,this.visibilityManager?.cleanup(),!this.noAutoComplete&&this.autoComplete&&(this.autoComplete.value="",this.autoComplete.handleFocus())}};t([e()],d.prototype,"tags",void 0),t([e()],d.prototype,"inputValue",void 0),t([e()],d.prototype,"isDropdownOpen",void 0),t([e()],d.prototype,"tooltips",void 0),t([e()],d.prototype,"chipFocusIndex",void 0),t([s("nile-auto-complete")],d.prototype,"autoComplete",void 0),t([h({type:Boolean})],d.prototype,"warning",void 0),t([h({type:Boolean})],d.prototype,"noAutoComplete",void 0),t([h({type:Boolean})],d.prototype,"error",void 0),t([h({type:Boolean})],d.prototype,"success",void 0),t([h({type:Boolean})],d.prototype,"noDuplicates",void 0),t([h()],d.prototype,"label",void 0),t([h({type:String})],d.prototype,"tagVariant",void 0),t([h({type:Boolean})],d.prototype,"acceptUserInput",void 0),t([h({type:Boolean})],d.prototype,"addOnBlur",void 0),t([h({type:Boolean})],d.prototype,"clearable",void 0),t([h()],d.prototype,"placeholder",void 0),t([h({type:Boolean,reflect:!0})],d.prototype,"readonly",void 0),t([h({type:Boolean,reflect:!0})],d.prototype,"disabled",void 0),t([h({type:Boolean,reflect:!0})],d.prototype,"portal",void 0),t([h({type:Boolean})],d.prototype,"enableVirtualScroll",void 0),t([h({type:Array})],d.prototype,"autoCompleteOptions",void 0),t([h({type:Array})],d.prototype,"filteredAutoCompleteOptions",void 0),t([h({type:Array})],d.prototype,"value",void 0),t([h({type:Boolean})],d.prototype,"noWrap",void 0),t([h({type:Boolean})],d.prototype,"loading",void 0),t([h({type:Array})],d.prototype,"errorIndexes",void 0),t([h({attribute:"help-text",reflect:!0})],d.prototype,"helpText",void 0),t([h({attribute:"error-message",reflect:!0})],d.prototype,"errorMessage",void 0),t([h({attribute:!1})],d.prototype,"filterFunction",void 0),t([h({attribute:!1})],d.prototype,"renderItemFunction",void 0),t([h({type:Boolean,reflect:!0})],d.prototype,"enableVisibilityEffect",void 0),t([h({type:Boolean,reflect:!0})],d.prototype,"enableTabClose",void 0),t([h({type:Boolean})],d.prototype,"showTooltip",void 0),t([h({type:Boolean})],d.prototype,"enableTagDelete",void 0),t([h({type:Boolean,reflect:!0})],d.prototype,"required",void 0),t([h({reflect:!0,converter:{fromAttribute:t=>"false"!==t,toAttribute:t=>t?"":"false"}})],d.prototype,"openDropdownOnFocus",void 0),t([h({type:Boolean,reflect:!0,attribute:!0})],d.prototype,"noDropdownClose",void 0),d=t([o("nile-chip")],d);export{d as N};
