UNPKG

dk-plus

Version:
2 lines (1 loc) 2.88 kB
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const i=require("vue"),L=require("./index3.js"),S=require("./index4.js"),O=i.defineComponent({name:"DkAutocomplete",props:L.dkAutocompleteProps,emits:S.autocompleteEmits,setup(o,{emit:c}){const x=i.ref(),y=i.ref(),f=[],b=(e,n)=>{if(!e){f[n]=null;return}if(e instanceof HTMLElement){f[n]=e;return}const s=e.$el;f[n]=s instanceof HTMLElement?s:null},g=()=>{if(!y.value||t.activeIndex<0)return;const e=f[t.activeIndex];if(!!e)try{e.scrollIntoView({block:"nearest"})}catch{}},t=i.reactive({inputValue:o.modelValue,showDropdown:!1,loading:!1,activeIndex:-1,suggestions:[]});let u=null,w=!1;const h=e=>{if(typeof e=="string")return e;const n=o.valueKey||"value",s=e[n];return s==null?"":String(s)},a=e=>{t.suggestions=e,o.highlightFirstItem?t.activeIndex=e.length>0?0:-1:t.activeIndex=-1,i.nextTick(()=>{g()})},I=async e=>{if(o.disabled)return;const n=!!o.fetchSuggestions,s=Array.isArray(o.options)&&o.options.length>0;if(!n&&!s){a([]);return}if(!n){const r=e.trim().toLowerCase(),v=(o.options||[]).filter(E=>{const F=h(E).toLowerCase();return r?F.includes(r):!0});a(v);return}const T=r=>{t.loading=!1,a(Array.isArray(r)?r:[])};t.loading=!0;try{const r=o.fetchSuggestions(e,T);if(r&&typeof r.then=="function"){const v=await r;T(v)}}catch{t.loading=!1,a([])}},d=e=>{if(!o.fetchSuggestions){u&&window.clearTimeout(u),I(e);return}const n=o.debounce||0;u&&window.clearTimeout(u),u=window.setTimeout(()=>{I(e)},n)},m=()=>{o.disabled||(t.showDropdown=!0,document.addEventListener("click",k))},l=()=>{t.showDropdown=!1,t.activeIndex=-1,document.removeEventListener("click",k)},k=e=>{const n=x.value;if(!n)return;const s=e.target;n.contains(s)||l()},V=e=>{m(),c("focus",e),o.triggerOnFocus&&d(t.inputValue)},A=e=>{c("blur",e),window.setTimeout(()=>{l()},120)},D=e=>{if(o.disabled)return;const n=h(e);t.inputValue=n,c("update:modelValue",n),c("select",e),l()},p=e=>{if(!!t.showDropdown&&t.suggestions.length!==0){if(e.key==="ArrowDown"){e.preventDefault();const n=t.activeIndex+1;t.activeIndex=n>=t.suggestions.length?0:n,i.nextTick(()=>g());return}if(e.key==="ArrowUp"){e.preventDefault();const n=t.activeIndex-1;t.activeIndex=n<0?t.suggestions.length-1:n,i.nextTick(()=>g());return}if(e.key==="Enter"){if(t.activeIndex<0)return;e.preventDefault(),D(t.suggestions[t.activeIndex]);return}e.key==="Escape"&&l()}};return i.watch(()=>o.modelValue,e=>{w=!0,t.inputValue=e,i.nextTick(()=>{w=!1})}),i.watch(()=>t.inputValue,(e,n)=>{if(w)return;const s=String(e!=null?e:"");if(c("update:modelValue",s),c("change",s),n!==""&&s===""){c("clear"),o.triggerOnFocus?(m(),d("")):(a([]),l());return}m(),d(s)}),i.watch(()=>o.options,()=>{!t.showDropdown||d(t.inputValue)}),{rootRef:x,dropdownRef:y,...i.toRefs(t),getOptionText:h,onFocus:V,onBlur:A,onSelect:D,onKeydown:p,setItemRef:b}}});exports.default=O;