-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathautocomplete.min.js
1 lines (1 loc) · 1.54 KB
/
autocomplete.min.js
1
function $(z,Q={}){const I={..._,...Q};let j,G=0,D=[],H,N;z.autocomplete="off",["input","keydown","blur","focus"].forEach((f)=>z.addEventListener(f,V));function V(f){if(f.type==="keydown"&&W(f))return;if(f.type==="blur"){J();return}if(f.target.value===""){J(),H=null;return}if(f.target.value===H)return;H=f.target.value,clearTimeout(N),N=setTimeout(X,I.debounce)}function W(f){if(!j)return!0;switch(f.keyCode){case 38:return O(-1,f);case 40:return O(1,f);case 13:P(G),J();return;case 27:J();return}}async function X(){if(!H)return;if(D=await I.onQuery(H),!D.length){J();return}if(!j)Y();Z()}function Y(){j=document.createElement("div"),Object.assign(j.style,{width:window.getComputedStyle(z).width,position:"absolute",left:`${z.offsetLeft}px`,top:`${z.offsetTop+z.offsetHeight}px`}),j.classList.add("autocomp"),z.parentNode.insertBefore(j,z.nextSibling)}function Z(){j.innerHTML="",D.forEach((f,M)=>{const C=document.createElement("div");if(C.classList.add("autocomp-item"),I.onRender?C.appendChild(I.onRender(f)):C.innerText=f,M===G)C.classList.add("autocomp-sel");C.addEventListener("mousedown",()=>P(M)),j.appendChild(C)})}function O(f,M){M.preventDefault();const C=j.querySelector(`:nth-child(${G+1})`);C&&C.classList.remove("autocomp-sel"),G=(G+f+D.length)%D.length,j.querySelector(`:nth-child(${G+1})`).classList.add("autocomp-sel")}function P(f){if(!I.onSelect)return;H=I.onSelect(D[f]),z.value=H||D[f]}function J(){if(D=[],G=0,j)j.remove(),j=null}}var _={onQuery:null,onNavigate:null,onSelect:null,onRender:null,debounce:100},w=$;export{w as default,$ as autocomp};