@magicx-eng/ai-autocomplete-react 0.1.15 → 0.1.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -10
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -529,5 +529,5 @@ import{forwardRef as vt,useCallback as It,useEffect as tt,useImperativeHandle as
|
|
|
529
529
|
opacity: 0;
|
|
530
530
|
}
|
|
531
531
|
}
|
|
532
|
-
`,document.head.appendChild(e)}var be={list:"PillList-module_list_qvLqO",pill:"PillList-module_pill_osSyz",fadeIn:"PillList-module_fadeIn_Aezob",active:"PillList-module_active_Oll--"};import{jsx as Ve}from"react/jsx-runtime";function mt(e){return e===0?.4:e===1?.3:.15}function je({pills:e,activePillIndex:i,onSelectPill:t}){return Ve("span",{className:be.list,children:e.map((o,r)=>Ve("button",{type:"button",className:`${be.pill} ${r===i?be.active:""}`,style:{opacity:mt(r)},onClick:()=>t(r),children:o.text},`${o.type}-${o.text}`))})}import{useCallback as ee,useMemo as xe,useRef as M,useState as ge}from"react";function ie(e,i,t){let o=e.slice(i);if(t||i===0||e[i-1]===" ")return o;let r=o.indexOf(" ");return r===-1?"":o.slice(r+1)}function he(e,i){if(!e)return[];let t=i.trimStart();if(!t)return e;let o=t.toLowerCase();return e.filter(r=>!r.is_tappable||r.text.toLowerCase().includes(o))}function me(e,i){if(!e)return null;let t=i.trim();if(!t)return null;let o=t.toLowerCase();return e.find(r=>r.is_tappable&&r.text.toLowerCase()===o)??null}function Be(e,i){let t=[],o=0;for(let a of i){let l=e.indexOf(a.text,o);l!==-1&&(l>o&&t.push({type:"text",value:e.slice(o,l)}),t.push({type:"completed",value:a.text,param:a}),o=l+a.text.length)}let r=e.slice(o);return r&&t.push({type:"text",value:r}),t}function Ke(e,i){let t=[],o=[],r=0;for(let a of i){let l=e.indexOf(a.text,r);l===-1?o.push(a):(t.push(a),r=l+a.text.length)}return{valid:t,invalid:o}}import{useCallback as ht,useEffect as We,useRef as se,useState as ke}from"react";var gt="0.1.15",qe=!1;function ft(){return crypto.randomUUID()}function bt(e,i){return{placeholder:e.placeholder,type:e.type,...i&&{text:e.text},kind:e.kind}}async function Qe(e,i,t){let o=t?.apiConfig,r=o?.apiKey??"";!r&&!qe&&(qe=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header."));let a=o?.authScheme??"Bearer",l=!t?.maskCompletedText,d=i.find(g=>g.type==="contact"&&g.metadata?.contact_account_count)?.metadata?.contact_account_count,p=typeof d=="number"?d:void 0,c={data:{raw_query:e,completed_params:i.map(g=>bt(g,l)),...p!=null&&{contact_account_count:p}},meta:{request_id:ft(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:gt}},u={"Content-Type":"application/json",...o?.appIdentifier&&{"X-App-Identifier":o.appIdentifier},...o?.headers};r&&(u.Authorization=a==="Basic"?`Basic ${btoa(r)}`:`Bearer ${r}`);let m=await fetch(o?.endpoint??"/ac/suggest",{method:"POST",headers:u,body:JSON.stringify(c),signal:t?.signal});if(!m.ok)throw new Error(`API error: ${m.status} ${m.statusText}`);return m.json()}function ae(e,i){let t=e,o={},r=[];for(let a of i){let l=(o[a.type]??0)+1;o[a.type]=l;let p=`{{${a.type.toUpperCase().replace(/\s+/g,"_")}_${l}}}`,c=t.indexOf(a.text);c!==-1&&(t=t.slice(0,c)+p+t.slice(c+a.text.length)),r.push({...a,placeholder:p})}return{rawQuery:t,completedParams:r}}function Ge(e,i){return i?e.map(t=>{let o=i[t.type];if(!o)return t;let r=o("");if(r.length===0)return t;let a=new Set(r.map(d=>d.text)),l=(t.options??[]).filter(d=>!a.has(d.text));return{...t,options:[...r,...l]}}):e}var xt=100,yt=300,_t=2;function Je({textRef:e,suggestionsRef:i,filterBaseRef:t,filterInProgressRef:o,maskCompletedTextRef:r,apiConfigRef:a,optionOverridesRef:l,onErrorRef:d,setCompletedParams:p,setSuggestions:c,setActiveDropdownIndex:u}){let[m,g]=ke(!1),[y,T]=ke(null),[I,f]=ke(!1),_=se(0),S=se(null),h=se(""),A=ht(async(N,v)=>{S.current?.abort();let w=new AbortController;S.current=w;let n=++_.current,s=e.current.length;i.current.some(E=>E.type!=="placeholder")||g(!0),T(null);try{let E=await Qe(N,v,{maskCompletedText:r.current,signal:w.signal,apiConfig:a.current});if(n!==_.current)return;let R=Ge(E.data.suggestions??[],l.current);f(E.data.is_ready??!1),h.current=N;let Z=E.data.input??[],G=Z[Z.length-1],F=e.current;if(G?.state==="in_progress"){o.current=!0;let V=F.toLowerCase().lastIndexOf(G.text.toLowerCase());V!==-1?t.current=V:t.current=s}else o.current=!1,t.current=s;let D=R.filter(V=>V.type!=="placeholder")[0];if(D){let V=ie(F,t.current,o.current),W=me(D.options,V);W&&(p(x=>[...x,{id:crypto.randomUUID(),placeholder:"",type:D.type,text:W.text,kind:W.kind,suggestionType:D.type,suggestionPlaceholder:D.text,options:D.options??[],metadata:W.metadata}]),R=R.filter(x=>x!==D))}c(R),g(!1),u(-1)}catch(E){if(n===_.current){let R=E instanceof Error?E:new Error(String(E));T(R),g(!1),d.current?.(R)}}},[e,i,t,o,r,a,l,d,p,c,u]);return We(()=>(A("",[]),()=>{S.current?.abort()}),[A]),{doFetch:A,isLoading:m,error:y,isReady:I,lastRawQueryRef:h}}function Xe({text:e,completedParams:i,doFetch:t,filterBaseRef:o,filterInProgressRef:r,skipNextFetchRef:a,suggestionsRef:l,lastRawQueryRef:d}){let p=se(null),c=se(null),u=se(!0);We(()=>{if(p.current&&clearTimeout(p.current),c.current&&clearTimeout(c.current),a.current){a.current=!1;return}let m=g=>{if(!e&&i.length===0)return u.current?(t("",[]),!0):(u.current=!0,!1);let y=ie(e,o.current,r.current),f=l.current.filter(s=>s.type!=="placeholder")[0],S=(f?he(f.options,y):[]).filter(s=>s.is_tappable),h=f?me(f.options,y)!==null:!1,A=y.trim().length>0;if(S.length>0&&!h&&A)return!1;let{rawQuery:N,completedParams:v}=ae(e,i),w=N.length<d.current.length,n=Math.abs(N.length-d.current.length);return w||n>=g?(t(N,v),!0):!1};return p.current=setTimeout(()=>{m(_t)&&c.current&&clearTimeout(c.current)},xt),c.current=setTimeout(()=>m(1),yt),()=>{p.current&&clearTimeout(p.current),c.current&&clearTimeout(c.current)}},[e,i,t,o,r,a,l,d])}import{useCallback as Ze}from"react";function Ye({activeDropdownIndex:e,setActiveDropdownIndex:i,filteredOptions:t,selectOption:o,onSubmitRef:r,text:a,completedParams:l,isDropdownOpen:d,hasPlaceholder:p,placeholderText:c,suggestions:u,actionableSuggestions:m,setActivePill:g,listboxId:y,pillTappedRef:T,filterBaseRef:I,columns:f,setText:_,setCompletedParams:S,setSuggestions:h}){let A=Ze(()=>{let v=t.map((n,s)=>n.is_tappable?s:-1).filter(n=>n!==-1),w=Array.from({length:f},()=>[]);for(let n of v)w[n%f].push(n);return w.flat()},[t,f]);return{handleKeyDown:Ze(v=>{let w=A();switch(v.key){case"ArrowDown":{let n=v.target;if(!(n.selectionStart!=null&&n.selectionStart===n.value.length)&&e<0)break;if(v.preventDefault(),!d&&m.length>0){T.current=!0;let R=w[0];i(R??0);break}if(w.length===0)return;let k=w.indexOf(e),E=k<w.length-1?k+1:0;i(w[E]);break}case"ArrowUp":{if(w.length===0||e<0)break;if(v.preventDefault(),e<f){i(-1);break}let s=w.indexOf(e),k=s>0?s-1:w.length-1;i(w[k]);break}case"ArrowRight":{if(e<0){let s=v.target;s.selectionStart!=null&&s.selectionStart===s.value.length&&m.length>1&&(v.preventDefault(),g(1));break}if(e%f<f-1){let s=e+1;s<t.length&&t[s]?.is_tappable&&(v.preventDefault(),i(s))}break}case"ArrowLeft":{if(e<0)break;if(e%f>0){let n=e-1;n>=0&&t[n]?.is_tappable&&(v.preventDefault(),i(n))}break}case"Enter":{if(v.preventDefault(),e>=0&&t[e]?.is_tappable){let n=document.getElementById(`${y}-option-${e}`);n?n.click():o(t[e])}else if(r.current){let{rawQuery:n,completedParams:s}=ae(a,l),k={query:a.trim(),raw_query:n,completed_params:s};r.current(k)}break}case"Tab":{if(e>=0&&t[e]?.is_tappable){v.preventDefault();let n=document.getElementById(`${y}-option-${e}`);n?n.click():o(t[e])}else if(d){let n=t.findIndex(s=>s.is_tappable);if(n>=0){v.preventDefault();let s=document.getElementById(`${y}-option-${n}`);s?s.click():o(t[n])}}else if(!a&&p){v.preventDefault();let n=u.find(s=>s.type==="placeholder");n?(_(c),I.current=c.length,S(s=>[...s,{id:crypto.randomUUID(),placeholder:"",type:n.type,text:c,kind:null,suggestionType:n.type,suggestionPlaceholder:n.text,options:n.options??[]}]),h(s=>s.filter(k=>k!==n))):(_(c),I.current=c.length)}break}case"Escape":i(-1);break}},[m,e,f,l,t,I,A,p,y,T,d,r,c,o,i,g,S,h,_,u,a]),getTappableIndices:A}}import{useCallback as Ce}from"react";function et({completedParams:e,suggestions:i,setCompletedParams:t,setSuggestions:o,setActiveDropdownIndex:r,filterBaseRef:a,pillTappedRef:l}){let d=Ce(u=>{let m=i.filter(I=>I.type!=="placeholder");if(u<0||u>=m.length)return;let g=m[u],y=m.filter((I,f)=>f!==u),T=i.filter(I=>I.type==="placeholder");o([...T,g,...y]),l.current=!0,r(-1)},[i,o,r,l]),p=Ce(()=>{if(e.length===0)return;let u=e[e.length-1],m={type:u.suggestionType,text:u.suggestionPlaceholder,required:!0,options:u.options};t(g=>g.slice(0,-1)),o(g=>[m,...g]),r(-1)},[e,t,o,r]),c=Ce(u=>{let m={type:u.suggestionType,text:u.suggestionPlaceholder,required:!0,options:u.options};return{apply:g=>{g(y=>{let T=0;for(let I of e){let f=y.indexOf(I.text,T);if(f!==-1){if(I.id===u.id){let _=y.slice(0,f),S=y.slice(f+u.text.length),h=(_+S).replace(/ {2,}/g," ");return a.current=Math.min(a.current,h.length),h}T=f+I.text.length}}return y}),t(y=>y.filter(T=>T.id!==u.id)),o(y=>[m,...y]),r(-1),l.current=!0}}},[e,t,o,r,a,l]);return{setActivePill:d,removeLastParam:p,reEditParam:c}}var St=0;function At(){let e=M(null);return e.current===null&&(e.current=`:ac-${++St}:`),e.current}function Re({onSubmit:e,onError:i,optionOverrides:t,maskCompletedText:o,placeholder:r,apiConfig:a,columns:l=2,value:d,completedParams:p,onChange:c,onParamsChange:u}){let m=d!==void 0,g=p!==void 0,[y,T]=ge(""),[I,f]=ge([]),[_,S]=ge([]),[h,A]=ge(-1),[N,v]=ge(null),w=ee(()=>v(null),[]),n=m?d:y,s=g?p:I,k=M(e);k.current=e;let E=M(c);E.current=c;let R=M(u);R.current=u;let Z=M(d);Z.current=d;let G=M(p);G.current=p;let F=ee(b=>{if(typeof b=="function")if(m){let C=b(Z.current??"");E.current?.(C)}else T(C=>{let O=b(C);return E.current?.(O),O});else m||T(b),E.current?.(b)},[m]),$=ee(b=>{if(typeof b=="function")if(g){let C=b(G.current??[]);R.current?.(C)}else f(C=>{let O=b(C);return R.current?.(O),O});else g||f(b),R.current?.(b)},[g]),D=M(i);D.current=i;let V=M(t);V.current=t;let W=M(o);W.current=o;let x=M(a);x.current=a;let U=M(n);U.current=n;let oe=M(_);oe.current=_;let z=M(0),j=M(!1),H=M(!1),le=M(!1),J=At(),{doFetch:ue,isLoading:Te,error:ot,isReady:rt,lastRawQueryRef:ye}=Je({textRef:U,suggestionsRef:oe,filterBaseRef:z,filterInProgressRef:j,maskCompletedTextRef:W,apiConfigRef:x,optionOverridesRef:V,onErrorRef:D,setCompletedParams:$,setSuggestions:S,setActiveDropdownIndex:A});Xe({text:n,completedParams:s,doFetch:ue,filterBaseRef:z,filterInProgressRef:j,skipNextFetchRef:le,suggestionsRef:oe,lastRawQueryRef:ye});let nt=xe(()=>Be(n,s),[n,s]);z.current=Math.min(z.current,n.length);let _e=ie(n,z.current,j.current),re=xe(()=>_.filter(C=>C.type==="placeholder").map(C=>C.text).join(" ")||r||"",[_,r]),ce=xe(()=>_.filter(b=>b.type!=="placeholder"),[_]),P=ce[0],Ee=P?t?.[P.type]:void 0,ze=P?Ee?Ee(_e.trim()):P.options??[]:[],Se=xe(()=>he(ze,_e),[ze,_e]),Le=re.length>0,Ae=!Te&&Se.length>0&&(!!n||H.current||!Le),Me=ee(b=>{if(!P)return;let C=z.current,O=U.current.slice(0,C),ne=O.length===0&&U.current.length===0;if(ne&&re&&(O=re+" "),O.length>0&&!O.endsWith(" ")){let Y=O.split(/\s+/).pop()??"";Y&&b.text.toLowerCase().startsWith(Y.toLowerCase())&&(O=O.slice(0,O.length-Y.length))}let ve=O.length>0&&O[O.length-1]!==" ",X=O+(ve?" ":"")+b.text+" ",B=ne&&X.length>0?X[0].toUpperCase()+X.slice(1):X,K=B.toLowerCase().lastIndexOf(b.text.toLowerCase()),de=K>=0?B.slice(K,K+b.text.length):b.text,fe={id:crypto.randomUUID(),placeholder:"",type:P.type,text:de,kind:b.kind,suggestionType:P.type,suggestionPlaceholder:P.text,options:P.options??[],metadata:b.metadata};F(B),z.current=B.length,$(Y=>[...Y,fe]),v(fe.id),H.current=!1,A(-1),ce.length-1>0&&(le.current=!0),setTimeout(()=>{S(Y=>Y.filter(ct=>ct!==P))},400)},[P,ce,re,F,$]),it=ee(b=>{let C=b.target.value,ne=C.length>0&&!b.nativeEvent?.isComposing&&C[0]!==C[0].toUpperCase()?C[0].toUpperCase()+C.slice(1):C;F(ne),H.current=!1,A(-1);let{valid:ve,invalid:X}=Ke(ne,s);if(X.length>0){$(()=>ve);for(let B of X)S(K=>[{type:B.suggestionType,text:B.suggestionPlaceholder,required:!0,options:B.options},...K])}if(P&&X.length===0){let B=ie(ne,z.current,j.current),K=me(P.options,B);K&&($(de=>[...de,{id:crypto.randomUUID(),placeholder:"",type:P.type,text:K.text,kind:K.kind,suggestionType:P.type,suggestionPlaceholder:P.text,options:P.options??[],metadata:K.metadata}]),S(de=>de.filter(fe=>fe!==P)))}},[s,P,F,$]),pe=et({completedParams:s,suggestions:_,setCompletedParams:$,setSuggestions:S,setActiveDropdownIndex:A,filterBaseRef:z,pillTappedRef:H}),at=ee(b=>{pe.reEditParam(b).apply(F)},[pe,F]),{handleKeyDown:st}=Ye({activeDropdownIndex:h,setActiveDropdownIndex:A,filteredOptions:Se,selectOption:Me,onSubmitRef:k,text:n,completedParams:s,isDropdownOpen:Ae,hasPlaceholder:Le,placeholderText:re,suggestions:_,actionableSuggestions:ce,setActivePill:pe.setActivePill,listboxId:J,pillTappedRef:H,filterBaseRef:z,columns:l,setText:F,setCompletedParams:$,setSuggestions:S}),lt=ee(()=>{F(""),$(()=>[]),S([]),A(-1),z.current=0,j.current=!1,ye.current="",ue("",[])},[ue,F,$,ye]),ut=h>=0?`${J}-option-${h}`:void 0;return{completedParams:s,suggestionPills:ce,setActivePill:pe.setActivePill,removeLastParam:pe.removeLastParam,reEditParam:at,segments:nt,newParamId:N,clearNewParamId:w,suggestions:_,activeIndex:h,isReady:rt,isLoading:Te,error:ot,inputProps:{value:n,placeholder:re||void 0,onChange:it,onKeyDown:st,role:"combobox","aria-expanded":Ae,"aria-activedescendant":ut,"aria-autocomplete":"list","aria-controls":J},reset:lt,dropdownProps:{suggestions:P?[{...P,options:Se}]:[],activeIndex:h,onSelect:Me,onHighlight:A,isOpen:Ae,id:J}}}import{jsx as Q,jsxs as te}from"react/jsx-runtime";var kt=vt(function({onSubmit:i,onError:t,optionOverrides:o,maskCompletedText:r,placeholder:a,className:l,apiConfig:d,columns:p,typewriterEffect:c=!0,value:u,completedParams:m,onChange:g,onParamsChange:y},T){let I=Oe(null),f=Oe(()=>{}),[_,S]=Pt(0),h=Oe(void 0);tt(()=>(I.current?.focus(),()=>{h.current&&cancelAnimationFrame(h.current)}),[]);let{completedParams:A,suggestionPills:N,setActivePill:v,segments:w,newParamId:n,clearNewParamId:s,inputProps:k,dropdownProps:E,reset:R}=Re({onSubmit:x=>f.current(x),onError:t,optionOverrides:o,maskCompletedText:r,placeholder:a,apiConfig:d,columns:p,value:u,completedParams:m,onChange:g,onParamsChange:y});tt(()=>{if(h.current&&cancelAnimationFrame(h.current),!n){S(0);return}let x=A.find(H=>H.id===n);if(!x)return;let U=x.text.length;if(!c){S(U);let H=window.setTimeout(()=>s(),650);return()=>window.clearTimeout(H)}S(0);let oe=performance.now(),z=300,j=()=>{let H=performance.now()-oe,le=Math.min(H/z,1),J=Math.ceil(le*U);S(J),J<U?h.current=requestAnimationFrame(j):h.current=requestAnimationFrame(()=>{s()})};return h.current=requestAnimationFrame(j),()=>{h.current&&cancelAnimationFrame(h.current)}},[n,A,s,c]),wt(T,()=>({focus:()=>I.current?.focus(),reset:R}),[R]);let Z=()=>{I.current?.focus()},G=!!k.value||A.length>0,F=It(()=>{if(!G)return;let{rawQuery:x,completedParams:U}=ae(k.value,A);i({query:k.value.trim(),raw_query:x,completed_params:U}),R()},[G,k.value,A,i,R]);f.current=F;let{onChange:$,placeholder:D,...V}=k,W=!k.value;return te("div",{className:`${L.container} ${l??""}`,children:[Q(Pe,{...E}),te("div",{className:L.inputWrapper,onClick:Z,children:[te("div",{className:L.editorArea,children:[te("div",{className:L.sizerContent,"aria-hidden":"true",children:[W&&D?te("span",{className:L.placeholderText,children:[D," "]}):te("span",{className:`${L.sizerText} ${n?L.sizerTextVisible:""}`,children:[w.map((x,U)=>{if(x.type==="completed"&&x.param.id===n){if(!c){let ue=`${L.shimmerRevealed} ${L.shimmerSweep}`;return Q("span",{className:ue,children:x.value},`${U}-${x.type}`)}let z=x.value.length,j=x.value.slice(0,_),H=x.value.slice(_),J=`${100-(z>0?_/z:0)*100}% 0`;return te("span",{className:L.shimmer,children:[Q("span",{className:L.shimmerRevealed,style:{backgroundPosition:J},children:j}),Q("span",{className:L.shimmerHidden,children:H})]},`${U}-${x.type}`)}return Q("span",{children:x.value},`${U}-${x.type}`)}),w.length===0&&"\xA0"]})," ",Q(je,{pills:N,activePillIndex:0,onSelectPill:v})]}),Q("textarea",{ref:I,className:`${L.textarea} ${n?L.textareaHidden:""}`,rows:1,onChange:$,...V})]}),Q("button",{type:"button",className:L.submitButton,disabled:!G,onClick:x=>{x.stopPropagation(),F()},"aria-label":"Submit",children:Q("svg",{width:"18",height:"18",viewBox:"0 0 18 18",fill:"none",role:"img","aria-label":"Submit",children:Q("path",{d:"M9 14V4M9 4L4 9M9 4L14 9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})});export{kt as AIAutocomplete,Pe as AIAutocompleteDropdown,Re as useAIAutocomplete};
|
|
532
|
+
`,document.head.appendChild(e)}var be={list:"PillList-module_list_qvLqO",pill:"PillList-module_pill_osSyz",fadeIn:"PillList-module_fadeIn_Aezob",active:"PillList-module_active_Oll--"};import{jsx as Ve}from"react/jsx-runtime";function mt(e){return e===0?.4:e===1?.3:.15}function je({pills:e,activePillIndex:i,onSelectPill:t}){return Ve("span",{className:be.list,children:e.map((o,r)=>Ve("button",{type:"button",className:`${be.pill} ${r===i?be.active:""}`,style:{opacity:mt(r)},onClick:()=>t(r),children:o.text},`${o.type}-${o.text}`))})}import{useCallback as ee,useMemo as xe,useRef as M,useState as ge}from"react";function ie(e,i,t){let o=e.slice(i);if(t||i===0||e[i-1]===" ")return o;let r=o.indexOf(" ");return r===-1?"":o.slice(r+1)}function he(e,i){if(!e)return[];let t=i.trimStart();if(!t)return e;let o=t.toLowerCase();return e.filter(r=>!r.is_tappable||r.text.toLowerCase().includes(o))}function me(e,i){if(!e)return null;let t=i.trim();if(!t)return null;let o=t.toLowerCase();return e.find(r=>r.is_tappable&&r.text.toLowerCase()===o)??null}function Be(e,i){let t=[],o=0;for(let a of i){let l=e.indexOf(a.text,o);l!==-1&&(l>o&&t.push({type:"text",value:e.slice(o,l)}),t.push({type:"completed",value:a.text,param:a}),o=l+a.text.length)}let r=e.slice(o);return r&&t.push({type:"text",value:r}),t}function Ke(e,i){let t=[],o=[],r=0;for(let a of i){let l=e.indexOf(a.text,r);l===-1?o.push(a):(t.push(a),r=l+a.text.length)}return{valid:t,invalid:o}}import{useCallback as ht,useEffect as We,useRef as se,useState as ke}from"react";var gt="0.1.17",qe=!1;function ft(){return crypto.randomUUID()}function bt(e,i){return{placeholder:e.placeholder,type:e.type,...i&&{text:e.text},kind:e.kind}}async function Qe(e,i,t){let o=t?.apiConfig,r=o?.apiKey??"";!r&&!qe&&(qe=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header."));let a=o?.authScheme??"Bearer",l=!t?.maskCompletedText,d=i.find(g=>g.type==="contact"&&g.metadata?.contact_account_count)?.metadata?.contact_account_count,p=typeof d=="number"?d:void 0,c={data:{raw_query:e,completed_params:i.map(g=>bt(g,l)),...p!=null&&{contact_account_count:p}},meta:{request_id:ft(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:gt}},u={"Content-Type":"application/json",...o?.appIdentifier&&{"X-App-Identifier":o.appIdentifier},...o?.headers};r&&(u.Authorization=a==="Basic"?`Basic ${btoa(r)}`:`Bearer ${r}`);let m=await fetch(o?.endpoint??"/ac/suggest",{method:"POST",headers:u,body:JSON.stringify(c),signal:t?.signal});if(!m.ok)throw new Error(`API error: ${m.status} ${m.statusText}`);return m.json()}function ae(e,i){let t=e,o={},r=[];for(let a of i){let l=(o[a.type]??0)+1;o[a.type]=l;let p=`{{${a.type.toUpperCase().replace(/\s+/g,"_")}_${l}}}`,c=t.indexOf(a.text);c!==-1&&(t=t.slice(0,c)+p+t.slice(c+a.text.length)),r.push({...a,placeholder:p})}return{rawQuery:t,completedParams:r}}function Ge(e,i){return i?e.map(t=>{let o=i[t.type];if(!o)return t;let r=o("");if(r.length===0)return t;let a=new Set(r.map(d=>d.text)),l=(t.options??[]).filter(d=>!a.has(d.text));return{...t,options:[...r,...l]}}):e}var xt=100,yt=300,_t=2;function Je({textRef:e,suggestionsRef:i,filterBaseRef:t,filterInProgressRef:o,maskCompletedTextRef:r,apiConfigRef:a,optionOverridesRef:l,onErrorRef:d,setCompletedParams:p,setSuggestions:c,setActiveDropdownIndex:u}){let[m,g]=ke(!1),[y,T]=ke(null),[I,f]=ke(!1),_=se(0),S=se(null),h=se(""),A=ht(async(N,v)=>{S.current?.abort();let w=new AbortController;S.current=w;let n=++_.current,s=e.current.length;i.current.some(E=>E.type!=="placeholder")||g(!0),T(null);try{let E=await Qe(N,v,{maskCompletedText:r.current,signal:w.signal,apiConfig:a.current});if(n!==_.current)return;let R=Ge(E.data.suggestions??[],l.current);f(E.data.is_ready??!1),h.current=N;let Z=E.data.input??[],G=Z[Z.length-1],F=e.current;if(G?.state==="in_progress"){o.current=!0;let V=F.toLowerCase().lastIndexOf(G.text.toLowerCase());V!==-1?t.current=V:t.current=s}else o.current=!1,t.current=s;let D=R.filter(V=>V.type!=="placeholder")[0];if(D){let V=ie(F,t.current,o.current),W=me(D.options,V);W&&(p(x=>[...x,{id:crypto.randomUUID(),placeholder:"",type:D.type,text:W.text,kind:W.kind,suggestionType:D.type,suggestionPlaceholder:D.text,options:D.options??[],metadata:W.metadata}]),R=R.filter(x=>x!==D))}c(R),g(!1),u(-1)}catch(E){if(n===_.current){let R=E instanceof Error?E:new Error(String(E));T(R),g(!1),d.current?.(R)}}},[e,i,t,o,r,a,l,d,p,c,u]);return We(()=>(A("",[]),()=>{S.current?.abort()}),[A]),{doFetch:A,isLoading:m,error:y,isReady:I,lastRawQueryRef:h}}function Xe({text:e,completedParams:i,doFetch:t,filterBaseRef:o,filterInProgressRef:r,skipNextFetchRef:a,suggestionsRef:l,lastRawQueryRef:d}){let p=se(null),c=se(null),u=se(!0);We(()=>{if(p.current&&clearTimeout(p.current),c.current&&clearTimeout(c.current),a.current){a.current=!1;return}let m=g=>{if(!e&&i.length===0)return u.current?(t("",[]),!0):(u.current=!0,!1);let y=ie(e,o.current,r.current),f=l.current.filter(s=>s.type!=="placeholder")[0],S=(f?he(f.options,y):[]).filter(s=>s.is_tappable),h=f?me(f.options,y)!==null:!1,A=y.trim().length>0;if(S.length>0&&!h&&A)return!1;let{rawQuery:N,completedParams:v}=ae(e,i),w=N.length<d.current.length,n=Math.abs(N.length-d.current.length);return w||n>=g?(t(N,v),!0):!1};return p.current=setTimeout(()=>{m(_t)&&c.current&&clearTimeout(c.current)},xt),c.current=setTimeout(()=>m(1),yt),()=>{p.current&&clearTimeout(p.current),c.current&&clearTimeout(c.current)}},[e,i,t,o,r,a,l,d])}import{useCallback as Ze}from"react";function Ye({activeDropdownIndex:e,setActiveDropdownIndex:i,filteredOptions:t,selectOption:o,onSubmitRef:r,text:a,completedParams:l,isDropdownOpen:d,hasPlaceholder:p,placeholderText:c,suggestions:u,actionableSuggestions:m,setActivePill:g,listboxId:y,pillTappedRef:T,filterBaseRef:I,columns:f,setText:_,setCompletedParams:S,setSuggestions:h}){let A=Ze(()=>{let v=t.map((n,s)=>n.is_tappable?s:-1).filter(n=>n!==-1),w=Array.from({length:f},()=>[]);for(let n of v)w[n%f].push(n);return w.flat()},[t,f]);return{handleKeyDown:Ze(v=>{let w=A();switch(v.key){case"ArrowDown":{let n=v.target;if(!(n.selectionStart!=null&&n.selectionStart===n.value.length)&&e<0)break;if(v.preventDefault(),!d&&m.length>0){T.current=!0;let R=w[0];i(R??0);break}if(w.length===0)return;let k=w.indexOf(e),E=k<w.length-1?k+1:0;i(w[E]);break}case"ArrowUp":{if(w.length===0||e<0)break;if(v.preventDefault(),e<f){i(-1);break}let s=w.indexOf(e),k=s>0?s-1:w.length-1;i(w[k]);break}case"ArrowRight":{if(e<0){let s=v.target;s.selectionStart!=null&&s.selectionStart===s.value.length&&m.length>1&&(v.preventDefault(),g(1));break}if(e%f<f-1){let s=e+1;s<t.length&&t[s]?.is_tappable&&(v.preventDefault(),i(s))}break}case"ArrowLeft":{if(e<0)break;if(e%f>0){let n=e-1;n>=0&&t[n]?.is_tappable&&(v.preventDefault(),i(n))}break}case"Enter":{if(v.preventDefault(),e>=0&&t[e]?.is_tappable){let n=document.getElementById(`${y}-option-${e}`);n?n.click():o(t[e])}else if(r.current){let{rawQuery:n,completedParams:s}=ae(a,l),k={query:a.trim(),raw_query:n,completed_params:s};r.current(k)}break}case"Tab":{if(e>=0&&t[e]?.is_tappable){v.preventDefault();let n=document.getElementById(`${y}-option-${e}`);n?n.click():o(t[e])}else if(d){let n=t.findIndex(s=>s.is_tappable);if(n>=0){v.preventDefault();let s=document.getElementById(`${y}-option-${n}`);s?s.click():o(t[n])}}else if(!a&&p){v.preventDefault();let n=u.find(s=>s.type==="placeholder");n?(_(c),I.current=c.length,S(s=>[...s,{id:crypto.randomUUID(),placeholder:"",type:n.type,text:c,kind:null,suggestionType:n.type,suggestionPlaceholder:n.text,options:n.options??[]}]),h(s=>s.filter(k=>k!==n))):(_(c),I.current=c.length)}break}case"Escape":i(-1);break}},[m,e,f,l,t,I,A,p,y,T,d,r,c,o,i,g,S,h,_,u,a]),getTappableIndices:A}}import{useCallback as Ce}from"react";function et({completedParams:e,suggestions:i,setCompletedParams:t,setSuggestions:o,setActiveDropdownIndex:r,filterBaseRef:a,pillTappedRef:l}){let d=Ce(u=>{let m=i.filter(I=>I.type!=="placeholder");if(u<0||u>=m.length)return;let g=m[u],y=m.filter((I,f)=>f!==u),T=i.filter(I=>I.type==="placeholder");o([...T,g,...y]),l.current=!0,r(-1)},[i,o,r,l]),p=Ce(()=>{if(e.length===0)return;let u=e[e.length-1],m={type:u.suggestionType,text:u.suggestionPlaceholder,required:!0,options:u.options};t(g=>g.slice(0,-1)),o(g=>[m,...g]),r(-1)},[e,t,o,r]),c=Ce(u=>{let m={type:u.suggestionType,text:u.suggestionPlaceholder,required:!0,options:u.options};return{apply:g=>{g(y=>{let T=0;for(let I of e){let f=y.indexOf(I.text,T);if(f!==-1){if(I.id===u.id){let _=y.slice(0,f),S=y.slice(f+u.text.length),h=(_+S).replace(/ {2,}/g," ");return a.current=Math.min(a.current,h.length),h}T=f+I.text.length}}return y}),t(y=>y.filter(T=>T.id!==u.id)),o(y=>[m,...y]),r(-1),l.current=!0}}},[e,t,o,r,a,l]);return{setActivePill:d,removeLastParam:p,reEditParam:c}}var St=0;function At(){let e=M(null);return e.current===null&&(e.current=`:ac-${++St}:`),e.current}function Re({onSubmit:e,onError:i,optionOverrides:t,maskCompletedText:o,placeholder:r,apiConfig:a,columns:l=2,value:d,completedParams:p,onChange:c,onParamsChange:u}){let m=d!==void 0,g=p!==void 0,[y,T]=ge(""),[I,f]=ge([]),[_,S]=ge([]),[h,A]=ge(-1),[N,v]=ge(null),w=ee(()=>v(null),[]),n=m?d:y,s=g?p:I,k=M(e);k.current=e;let E=M(c);E.current=c;let R=M(u);R.current=u;let Z=M(d);Z.current=d;let G=M(p);G.current=p;let F=ee(b=>{if(typeof b=="function")if(m){let C=b(Z.current??"");E.current?.(C)}else T(C=>{let O=b(C);return E.current?.(O),O});else m||T(b),E.current?.(b)},[m]),$=ee(b=>{if(typeof b=="function")if(g){let C=b(G.current??[]);R.current?.(C)}else f(C=>{let O=b(C);return R.current?.(O),O});else g||f(b),R.current?.(b)},[g]),D=M(i);D.current=i;let V=M(t);V.current=t;let W=M(o);W.current=o;let x=M(a);x.current=a;let U=M(n);U.current=n;let oe=M(_);oe.current=_;let z=M(0),j=M(!1),H=M(!1),le=M(!1),J=At(),{doFetch:ue,isLoading:Te,error:ot,isReady:rt,lastRawQueryRef:ye}=Je({textRef:U,suggestionsRef:oe,filterBaseRef:z,filterInProgressRef:j,maskCompletedTextRef:W,apiConfigRef:x,optionOverridesRef:V,onErrorRef:D,setCompletedParams:$,setSuggestions:S,setActiveDropdownIndex:A});Xe({text:n,completedParams:s,doFetch:ue,filterBaseRef:z,filterInProgressRef:j,skipNextFetchRef:le,suggestionsRef:oe,lastRawQueryRef:ye});let nt=xe(()=>Be(n,s),[n,s]);z.current=Math.min(z.current,n.length);let _e=ie(n,z.current,j.current),re=xe(()=>_.filter(C=>C.type==="placeholder").map(C=>C.text).join(" ")||r||"",[_,r]),ce=xe(()=>_.filter(b=>b.type!=="placeholder"),[_]),P=ce[0],Ee=P?t?.[P.type]:void 0,ze=P?Ee?Ee(_e.trim()):P.options??[]:[],Se=xe(()=>he(ze,_e),[ze,_e]),Le=re.length>0,Ae=!Te&&Se.length>0&&(!!n||H.current||!Le),Me=ee(b=>{if(!P)return;let C=z.current,O=U.current.slice(0,C),ne=O.length===0&&U.current.length===0;if(ne&&re&&(O=re+" "),O.length>0&&!O.endsWith(" ")){let Y=O.split(/\s+/).pop()??"";Y&&b.text.toLowerCase().startsWith(Y.toLowerCase())&&(O=O.slice(0,O.length-Y.length))}let ve=O.length>0&&O[O.length-1]!==" ",X=O+(ve?" ":"")+b.text+" ",B=ne&&X.length>0?X[0].toUpperCase()+X.slice(1):X,K=B.toLowerCase().lastIndexOf(b.text.toLowerCase()),de=K>=0?B.slice(K,K+b.text.length):b.text,fe={id:crypto.randomUUID(),placeholder:"",type:P.type,text:de,kind:b.kind,suggestionType:P.type,suggestionPlaceholder:P.text,options:P.options??[],metadata:b.metadata};F(B),z.current=B.length,$(Y=>[...Y,fe]),v(fe.id),H.current=!1,A(-1),ce.length-1>0&&(le.current=!0),setTimeout(()=>{S(Y=>Y.filter(ct=>ct!==P))},400)},[P,ce,re,F,$]),it=ee(b=>{let C=b.target.value,ne=C.length>0&&!b.nativeEvent?.isComposing&&C[0]!==C[0].toUpperCase()?C[0].toUpperCase()+C.slice(1):C;F(ne),H.current=!1,A(-1);let{valid:ve,invalid:X}=Ke(ne,s);if(X.length>0){$(()=>ve);for(let B of X)S(K=>[{type:B.suggestionType,text:B.suggestionPlaceholder,required:!0,options:B.options},...K])}if(P&&X.length===0){let B=ie(ne,z.current,j.current),K=me(P.options,B);K&&($(de=>[...de,{id:crypto.randomUUID(),placeholder:"",type:P.type,text:K.text,kind:K.kind,suggestionType:P.type,suggestionPlaceholder:P.text,options:P.options??[],metadata:K.metadata}]),S(de=>de.filter(fe=>fe!==P)))}},[s,P,F,$]),pe=et({completedParams:s,suggestions:_,setCompletedParams:$,setSuggestions:S,setActiveDropdownIndex:A,filterBaseRef:z,pillTappedRef:H}),at=ee(b=>{pe.reEditParam(b).apply(F)},[pe,F]),{handleKeyDown:st}=Ye({activeDropdownIndex:h,setActiveDropdownIndex:A,filteredOptions:Se,selectOption:Me,onSubmitRef:k,text:n,completedParams:s,isDropdownOpen:Ae,hasPlaceholder:Le,placeholderText:re,suggestions:_,actionableSuggestions:ce,setActivePill:pe.setActivePill,listboxId:J,pillTappedRef:H,filterBaseRef:z,columns:l,setText:F,setCompletedParams:$,setSuggestions:S}),lt=ee(()=>{F(""),$(()=>[]),S([]),A(-1),z.current=0,j.current=!1,ye.current="",ue("",[])},[ue,F,$,ye]),ut=h>=0?`${J}-option-${h}`:void 0;return{completedParams:s,suggestionPills:ce,setActivePill:pe.setActivePill,removeLastParam:pe.removeLastParam,reEditParam:at,segments:nt,newParamId:N,clearNewParamId:w,suggestions:_,activeIndex:h,isReady:rt,isLoading:Te,error:ot,inputProps:{value:n,placeholder:re||void 0,onChange:it,onKeyDown:st,role:"combobox","aria-expanded":Ae,"aria-activedescendant":ut,"aria-autocomplete":"list","aria-controls":J},reset:lt,dropdownProps:{suggestions:P?[{...P,options:Se}]:[],activeIndex:h,onSelect:Me,onHighlight:A,isOpen:Ae,id:J}}}import{jsx as Q,jsxs as te}from"react/jsx-runtime";var kt=vt(function({onSubmit:i,onError:t,optionOverrides:o,maskCompletedText:r,placeholder:a,className:l,apiConfig:d,columns:p,typewriterEffect:c=!1,value:u,completedParams:m,onChange:g,onParamsChange:y},T){let I=Oe(null),f=Oe(()=>{}),[_,S]=Pt(0),h=Oe(void 0);tt(()=>(I.current?.focus(),()=>{h.current&&cancelAnimationFrame(h.current)}),[]);let{completedParams:A,suggestionPills:N,setActivePill:v,segments:w,newParamId:n,clearNewParamId:s,inputProps:k,dropdownProps:E,reset:R}=Re({onSubmit:x=>f.current(x),onError:t,optionOverrides:o,maskCompletedText:r,placeholder:a,apiConfig:d,columns:p,value:u,completedParams:m,onChange:g,onParamsChange:y});tt(()=>{if(h.current&&cancelAnimationFrame(h.current),!n){S(0);return}let x=A.find(H=>H.id===n);if(!x)return;let U=x.text.length;if(!c){S(U);let H=window.setTimeout(()=>s(),650);return()=>window.clearTimeout(H)}S(0);let oe=performance.now(),z=300,j=()=>{let H=performance.now()-oe,le=Math.min(H/z,1),J=Math.ceil(le*U);S(J),J<U?h.current=requestAnimationFrame(j):h.current=requestAnimationFrame(()=>{s()})};return h.current=requestAnimationFrame(j),()=>{h.current&&cancelAnimationFrame(h.current)}},[n,A,s,c]),wt(T,()=>({focus:()=>I.current?.focus(),reset:R}),[R]);let Z=()=>{I.current?.focus()},G=!!k.value||A.length>0,F=It(()=>{if(!G)return;let{rawQuery:x,completedParams:U}=ae(k.value,A);i({query:k.value.trim(),raw_query:x,completed_params:U}),R()},[G,k.value,A,i,R]);f.current=F;let{onChange:$,placeholder:D,...V}=k,W=!k.value;return te("div",{className:`${L.container} ${l??""}`,children:[Q(Pe,{...E}),te("div",{className:L.inputWrapper,onClick:Z,children:[te("div",{className:L.editorArea,children:[te("div",{className:L.sizerContent,"aria-hidden":"true",children:[W&&D?te("span",{className:L.placeholderText,children:[D," "]}):te("span",{className:`${L.sizerText} ${n?L.sizerTextVisible:""}`,children:[w.map((x,U)=>{if(x.type==="completed"&&x.param.id===n){if(!c){let ue=`${L.shimmerRevealed} ${L.shimmerSweep}`;return Q("span",{className:ue,children:x.value},`${U}-${x.type}`)}let z=x.value.length,j=x.value.slice(0,_),H=x.value.slice(_),J=`${100-(z>0?_/z:0)*100}% 0`;return te("span",{className:L.shimmer,children:[Q("span",{className:L.shimmerRevealed,style:{backgroundPosition:J},children:j}),Q("span",{className:L.shimmerHidden,children:H})]},`${U}-${x.type}`)}return Q("span",{children:x.value},`${U}-${x.type}`)}),w.length===0&&"\xA0"]})," ",Q(je,{pills:N,activePillIndex:0,onSelectPill:v})]}),Q("textarea",{ref:I,className:`${L.textarea} ${n?L.textareaHidden:""}`,rows:1,onChange:$,...V})]}),Q("button",{type:"button",className:L.submitButton,disabled:!G,onClick:x=>{x.stopPropagation(),F()},"aria-label":"Submit",children:Q("svg",{width:"18",height:"18",viewBox:"0 0 18 18",fill:"none",role:"img","aria-label":"Submit",children:Q("path",{d:"M9 14V4M9 4L4 9M9 4L14 9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})});export{kt as AIAutocomplete,Pe as AIAutocompleteDropdown,Re as useAIAutocomplete};
|
|
533
533
|
//# sourceMappingURL=index.mjs.map
|