@magicx-eng/ai-autocomplete-react 0.1.4 → 0.1.5

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/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var be=Object.defineProperty;var Je=Object.getOwnPropertyDescriptor;var Ze=Object.getOwnPropertyNames;var et=Object.prototype.hasOwnProperty;var tt=(e,o)=>{for(var t in o)be(e,t,{get:o[t],enumerable:!0})},ot=(e,o,t,r)=>{if(o&&typeof o=="object"||typeof o=="function")for(let n of Ze(o))!et.call(e,n)&&n!==t&&be(e,n,{get:()=>o[n],enumerable:!(r=Je(o,n))||r.enumerable});return e};var nt=e=>ot(be({},"__esModule",{value:!0}),e);var St={};tt(St,{AIAutocomplete:()=>ze,AIAutocompleteDropdown:()=>re,useAIAutocomplete:()=>ce});module.exports=nt(St);var D=require("react");var j={};var ye={};var Re={};var W={};var ne=require("react/jsx-runtime");function _e({option:e,isHighlighted:o,onSelect:t,onHighlight:r,id:n}){let a=[W.item,o?W.highlighted:"",e.is_tappable?W.tappable:W.nonTappable].filter(Boolean).join(" ");return(0,ne.jsxs)("div",{id:n,role:"option","aria-selected":o,className:a,tabIndex:e.is_tappable?0:-1,onClick:()=>e.is_tappable&&t(e),onKeyDown:i=>{e.is_tappable&&(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),t(e))},onMouseEnter:r,children:[e.icon?`${e.icon} ${e.text}`:e.text,e.tag&&(0,ne.jsx)("span",{className:W.tag,children:e.tag})]})}var Se=require("react/jsx-runtime");function Te({options:e,activeIndex:o,onSelect:t,onHighlight:r,listboxId:n}){return(0,Se.jsx)("div",{className:Re.grid,children:e.map((a,i)=>(0,Se.jsx)(_e,{option:a,isHighlighted:i===o,onSelect:t,onHighlight:()=>r(i),id:`${n}-option-${i}`},a.text))})}var xe=require("react/jsx-runtime");function re({suggestions:e,activeIndex:o,onSelect:t,onHighlight:r,isOpen:n,id:a,className:i}){let l=e[0],d=n&&l&&l.options.length>0;return(0,xe.jsx)("div",{id:a,role:"listbox",className:`${ye.dropdown} ${d?ye.visible:""} ${i??""}`,onMouseDown:g=>g.preventDefault(),children:l&&l.options.length>0&&(0,xe.jsx)(Te,{options:l.options,activeIndex:o,onSelect:t,onHighlight:r,listboxId:a})})}var ae={};var Pe=require("react/jsx-runtime");function lt(e){return e===0?.4:e===1?.3:.15}function Ee({pills:e,activePillIndex:o,onSelectPill:t}){return(0,Pe.jsx)("span",{className:ae.list,children:e.map((r,n)=>(0,Pe.jsx)("button",{type:"button",className:`${ae.pill} ${n===o?ae.active:""}`,style:{opacity:lt(n)},onClick:()=>t(n),children:r.text},`${r.type}-${r.text}`))})}var u=require("react");function se(e,o){let t=o.trimStart();if(!t)return e;let r=t.toLowerCase();return e.filter(n=>!n.is_tappable||n.text.toLowerCase().includes(r))}function Z(e,o){let t=o.trim();if(!t)return null;let r=t.toLowerCase();return e.find(n=>n.is_tappable&&n.text.toLowerCase()===r)??null}function Me(e,o){let t=[],r=0;for(let a of o){let i=e.indexOf(a.text,r);i!==-1&&(i>r&&t.push({type:"text",value:e.slice(r,i)}),t.push({type:"completed",value:a.text,param:a}),r=i+a.text.length)}let n=e.slice(r);return n&&t.push({type:"text",value:n}),t}function Ue(e,o){let t=[],r=[],n=0;for(let a of o){let i=e.indexOf(a.text,n);i===-1?r.push(a):(t.push(a),n=i+a.text.length)}return{valid:t,invalid:r}}var T=require("react");var ut="0.1.4",pt=process?.env.MAGICX_API_ENDPOINT||"/api/suggest",Le=!1;function mt(e){let o=e?.apiKey||process?.env.MAGICX_AI_AUTOCOMPLETE_API_KEY||"";return!o&&!Le&&(Le=!0,console.warn("[AIAutocomplete] No API key set (MAGICX_AI_AUTOCOMPLETE_API_KEY). Requests will be sent without an Authorization header.")),o}function dt(e){return e?.authScheme?e.authScheme:process?.env.MAGICX_AUTH_SCHEME==="Basic"?"Basic":"Bearer"}function ft(){return crypto.randomUUID()}function gt(e,o){return{placeholder:e.placeholder,type:e.type,...o&&{text:e.text},kind:e.kind}}async function Ne(e,o,t){let r=t?.apiConfig,n=mt(r),a=dt(r),i=!t?.maskCompletedText,l=t?.contactAccountCount,d={data:{raw_query:e,completed_params:o.map(b=>gt(b,i)),...l!=null&&{contact_account_count:l}},meta:{request_id:ft(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:ut}},g={"Content-Type":"application/json","X-App-Identifier":process?.env.MAGICX_APP_IDENTIFIER||"active-campaign-demo",...r?.headers};n&&(g.Authorization=a==="Basic"?`Basic ${btoa(n)}`:`Bearer ${n}`);let p=await fetch(pt,{method:"POST",headers:g,body:JSON.stringify(d),signal:t?.signal});if(!p.ok)throw new Error(`API error: ${p.status} ${p.statusText}`);return p.json()}function G(e,o){let t=e,r={},n=[];for(let a of o){let i=(r[a.type]??0)+1;r[a.type]=i;let d=`{{${a.type.toUpperCase().replace(/\s+/g,"_")}_${i}}}`,g=t.indexOf(a.text);g!==-1&&(t=t.slice(0,g)+d+t.slice(g+a.text.length)),n.push({...a,placeholder:d})}return{rawQuery:t,completedParams:n}}function De(e,o){return o?e.map(t=>{let r=o[t.type];if(!r)return t;let n=r("");if(n.length===0)return t;let a=new Set(n.map(l=>l.text)),i=(t.options??[]).filter(l=>!a.has(l.text));return{...t,options:[...n,...i]}}):e}var ht=100,bt=300,yt=2;function Fe({textRef:e,suggestionsRef:o,filterBaseRef:t,maskCompletedTextRef:r,apiConfigRef:n,optionOverridesRef:a,onErrorRef:i,setCompletedParams:l,setSuggestions:d,setActiveDropdownIndex:g}){let[p,b]=(0,T.useState)(!1),[h,S]=(0,T.useState)(null),[k,x]=(0,T.useState)(!1),v=(0,T.useRef)(0),A=(0,T.useRef)(null),m=(0,T.useRef)(""),f=(0,T.useCallback)(async(s,c)=>{A.current?.abort();let P=new AbortController;A.current=P;let U=++v.current,F=e.current.length;o.current.some($=>$.type!=="placeholder")||b(!0),S(null);try{let $=c.find(_=>_.type==="contact"&&_.metadata?.contact_account_count)?.metadata?.contact_account_count,K=await Ne(s,c,{maskCompletedText:r.current,signal:P.signal,contactAccountCount:typeof $=="number"?$:void 0,apiConfig:n.current});if(U!==v.current)return;let R=De(K.data.suggestions??[],a.current);x(K.data.is_ready??!1),m.current=s;let E=K.data.input??[],q=E[E.length-1],H=e.current;if(q?.state==="in_progress"){let _=H.toLowerCase().lastIndexOf(q.text.toLowerCase());_!==-1?t.current=_:t.current=F}else t.current=F;let O=R.filter(_=>_.type!=="placeholder")[0];if(O){let _=H.slice(t.current),B=Z(O.options,_);B&&(l(M=>[...M,{id:crypto.randomUUID(),placeholder:"",type:O.type,text:B.text,kind:B.kind,suggestionType:O.type,suggestionPlaceholder:O.text,options:O.options,metadata:B.metadata}]),R=R.filter(M=>M!==O))}d(R),b(!1),g(-1)}catch($){if(U===v.current){let K=$ instanceof Error?$:new Error(String($));S(K),b(!1),i.current?.(K)}}},[e,o,t,r,n,a,i,l,d,g]);return(0,T.useEffect)(()=>(f("",[]),()=>{A.current?.abort()}),[f]),{doFetch:f,isLoading:p,error:h,isReady:k,lastRawQueryRef:m}}function $e({text:e,completedParams:o,doFetch:t,filterBaseRef:r,skipNextFetchRef:n,suggestionsRef:a,lastRawQueryRef:i}){let l=(0,T.useRef)(null),d=(0,T.useRef)(null),g=(0,T.useRef)(!0);(0,T.useEffect)(()=>{l.current&&clearTimeout(l.current),d.current&&clearTimeout(d.current);let p=b=>{if(n.current)return n.current=!1,!1;if(!e&&o.length===0)return g.current?(t("",[]),!0):(g.current=!0,!1);let h=e.slice(r.current),x=a.current.filter(F=>F.type!=="placeholder")[0],A=(x?se(x.options,h):[]).filter(F=>F.is_tappable),m=x?Z(x.options,h)!==null:!1,f=h.trim().length>0;if(A.length>0&&!m&&f)return!1;let{rawQuery:s,completedParams:c}=G(e,o),P=s.length<i.current.length,U=Math.abs(s.length-i.current.length);return P||U>=b?(t(s,c),!0):!1};return l.current=setTimeout(()=>{p(yt)&&d.current&&clearTimeout(d.current)},ht),d.current=setTimeout(()=>p(1),bt),()=>{l.current&&clearTimeout(l.current),d.current&&clearTimeout(d.current)}},[e,o,t,r,n,a,i])}var ve=require("react");function Ke({activeDropdownIndex:e,setActiveDropdownIndex:o,filteredOptions:t,selectOption:r,onSubmitRef:n,text:a,completedParams:i,isDropdownOpen:l,hasPlaceholder:d,placeholderText:g,suggestions:p,filterBaseRef:b,columns:h,setText:S,setCompletedParams:k,setSuggestions:x}){let v=(0,ve.useCallback)(()=>{let m=t.map((c,P)=>c.is_tappable?P:-1).filter(c=>c!==-1),f=m.filter(c=>c%h===0),s=m.filter(c=>c%h===1);return[...f,...s]},[t,h]);return{handleKeyDown:(0,ve.useCallback)(m=>{let f=v();switch(m.key){case"ArrowDown":{if(m.preventDefault(),f.length===0)return;let s=f.indexOf(e),c=s<f.length-1?s+1:0;o(f[c]);break}case"ArrowUp":{if(m.preventDefault(),f.length===0)return;let s=f.indexOf(e),c=s>0?s-1:f.length-1;o(f[c]);break}case"ArrowRight":{if(e<0)break;if(e%h===0){let s=e+1;s<t.length&&t[s]?.is_tappable&&(m.preventDefault(),o(s))}break}case"ArrowLeft":{if(e<0)break;if(e%h===1){let s=e-1;s>=0&&t[s]?.is_tappable&&(m.preventDefault(),o(s))}break}case"Enter":{if(m.preventDefault(),e>=0&&t[e]?.is_tappable)r(t[e]);else if(n.current){let{rawQuery:s,completedParams:c}=G(a,i),P={query:a.trim(),raw_query:s,completed_params:c};n.current(P)}break}case"Tab":{if(e>=0&&t[e]?.is_tappable)m.preventDefault(),r(t[e]);else if(l){let s=t.find(c=>c.is_tappable);s&&(m.preventDefault(),r(s))}else if(!a&&d){m.preventDefault();let s=p.find(c=>c.type==="placeholder");s?(S(g),b.current=g.length,k(c=>[...c,{id:crypto.randomUUID(),placeholder:"",type:s.type,text:g,kind:null,suggestionType:s.type,suggestionPlaceholder:s.text,options:s.options}]),x(c=>c.filter(P=>P!==s))):(S(g),b.current=g.length)}break}case"Escape":o(-1);break}},[e,h,i,t,b,v,d,l,n,g,r,o,k,x,S,p,a]),getTappableIndices:v}}var ie=require("react");function je({completedParams:e,suggestions:o,setCompletedParams:t,setSuggestions:r,setActiveDropdownIndex:n,filterBaseRef:a,pillTappedRef:i}){let l=(0,ie.useCallback)(p=>{let b=o.filter(x=>x.type!=="placeholder");if(p<0||p>=b.length)return;let h=b[p],S=b.filter((x,v)=>v!==p),k=o.filter(x=>x.type==="placeholder");r([...k,h,...S]),i.current=!0,n(-1)},[o,r,n,i]),d=(0,ie.useCallback)(()=>{if(e.length===0)return;let p=e[e.length-1],b={type:p.suggestionType,text:p.suggestionPlaceholder,required:!0,options:p.options};t(h=>h.slice(0,-1)),r(h=>[b,...h]),n(-1)},[e,t,r,n]),g=(0,ie.useCallback)(p=>{let b={type:p.suggestionType,text:p.suggestionPlaceholder,required:!0,options:p.options};return{apply:h=>{h(S=>{let k=0;for(let x of e){let v=S.indexOf(x.text,k);if(v!==-1){if(x.id===p.id){let A=S.slice(0,v),m=S.slice(v+p.text.length),f=(A+m).replace(/ {2,}/g," ");return a.current=Math.min(a.current,f.length),f}k=v+x.text.length}}return S}),t(S=>S.filter(k=>k.id!==p.id)),r(S=>[b,...S]),n(-1),i.current=!0}}},[e,t,r,n,a,i]);return{setActivePill:l,removeLastParam:d,reEditParam:g}}function ce({onSubmit:e,onError:o,optionOverrides:t,maskCompletedText:r,placeholder:n,apiConfig:a,columns:i=2,value:l,completedParams:d,onChange:g,onParamsChange:p}){let b=l!==void 0,h=d!==void 0,[S,k]=(0,u.useState)(""),[x,v]=(0,u.useState)([]),[A,m]=(0,u.useState)([]),[f,s]=(0,u.useState)(-1),c=b?l:S,P=h?d:x,U=(0,u.useRef)(e);U.current=e;let F=(0,u.useRef)(g);F.current=g;let z=(0,u.useRef)(p);z.current=p;let $=(0,u.useRef)(l);$.current=l;let K=(0,u.useRef)(d);K.current=d;let R=(0,u.useCallback)(y=>{if(typeof y=="function")if(b){let w=y($.current??"");F.current?.(w)}else k(w=>{let Q=y(w);return F.current?.(Q),Q});else b||k(y),F.current?.(y)},[b]),E=(0,u.useCallback)(y=>{if(typeof y=="function")if(h){let w=y(K.current??[]);z.current?.(w)}else v(w=>{let Q=y(w);return z.current?.(Q),Q});else h||v(y),z.current?.(y)},[h]),q=(0,u.useRef)(o);q.current=o;let H=(0,u.useRef)(t);H.current=t;let Y=(0,u.useRef)(r);Y.current=r;let O=(0,u.useRef)(a);O.current=a;let _=(0,u.useRef)(c);_.current=c;let B=(0,u.useRef)(A);B.current=A;let M=(0,u.useRef)(0),ee=(0,u.useRef)(!1),Ae=(0,u.useRef)(!1),le=(0,u.useId)(),{doFetch:ue,isLoading:Ce,error:qe,isReady:Be,lastRawQueryRef:pe}=Fe({textRef:_,suggestionsRef:B,filterBaseRef:M,maskCompletedTextRef:Y,apiConfigRef:O,optionOverridesRef:H,onErrorRef:q,setCompletedParams:E,setSuggestions:m,setActiveDropdownIndex:s});$e({text:c,completedParams:P,doFetch:ue,filterBaseRef:M,skipNextFetchRef:Ae,suggestionsRef:B,lastRawQueryRef:pe});let Qe=(0,u.useMemo)(()=>Me(c,P),[c,P]);M.current=Math.min(M.current,c.length);let me=c.slice(M.current),de=(0,u.useMemo)(()=>A.filter(w=>w.type==="placeholder").map(w=>w.text).join(" ")||n||"",[A,n]),te=(0,u.useMemo)(()=>A.filter(y=>y.type!=="placeholder"),[A]),C=te[0],ke=C?t?.[C.type]:void 0,we=C?ke?ke(me.trim()):C.options??[]:[],fe=(0,u.useMemo)(()=>se(we,me),[we,me]),Oe=de.length>0,ge=!Ce&&fe.length>0&&(!!c||ee.current||!Oe),Ie=(0,u.useCallback)(y=>{if(!C)return;let w={id:crypto.randomUUID(),placeholder:"",type:C.type,text:y.text,kind:y.kind,suggestionType:C.type,suggestionPlaceholder:C.text,options:C.options,metadata:y.metadata},Q=M.current,L=_.current.slice(0,Q);if(L.length>0&&!L.endsWith(" ")){let N=L.split(/\s+/).pop()??"";N&&y.text.toLowerCase().startsWith(N.toLowerCase())&&(L=L.slice(0,L.length-N.length))}let he=L.length>0&&L[L.length-1]!==" ",V=L+(he?" ":"")+y.text+" ";R(V),M.current=V.length,E(N=>[...N,w]),m(N=>N.filter(J=>J!==C)),ee.current=!1,s(-1),te.length-1>0&&(Ae.current=!0)},[C,te,R,E]),He=(0,u.useCallback)(y=>{let w=y.target.value,L=w.length>0&&!y.nativeEvent?.isComposing&&w[0]!==w[0].toUpperCase()?w[0].toUpperCase()+w.slice(1):w;R(L),ee.current=!1,s(-1);let{valid:he,invalid:V}=Ue(L,P);if(V.length>0){E(()=>he);for(let X of V)m(N=>[{type:X.suggestionType,text:X.suggestionPlaceholder,required:!0,options:X.options},...N])}if(C&&V.length===0){let X=L.slice(M.current),N=Z(C.options,X);N&&(E(J=>[...J,{id:crypto.randomUUID(),placeholder:"",type:C.type,text:N.text,kind:N.kind,suggestionType:C.type,suggestionPlaceholder:C.text,options:C.options,metadata:N.metadata}]),m(J=>J.filter(Ye=>Ye!==C)))}},[P,C,R,E]),{handleKeyDown:Ve}=Ke({activeDropdownIndex:f,setActiveDropdownIndex:s,filteredOptions:fe,selectOption:Ie,onSubmitRef:U,text:c,completedParams:P,isDropdownOpen:ge,hasPlaceholder:Oe,placeholderText:de,suggestions:A,filterBaseRef:M,columns:i,setText:R,setCompletedParams:E,setSuggestions:m}),oe=je({completedParams:P,suggestions:A,setCompletedParams:E,setSuggestions:m,setActiveDropdownIndex:s,filterBaseRef:M,pillTappedRef:ee}),Xe=(0,u.useCallback)(y=>{oe.reEditParam(y).apply(R)},[oe,R]),We=(0,u.useCallback)(()=>{R(""),E(()=>[]),m([]),s(-1),M.current=0,pe.current="",ue("",[])},[ue,R,E,pe]),Ge=f>=0?`${le}-option-${f}`:void 0;return{completedParams:P,suggestionPills:te,setActivePill:oe.setActivePill,removeLastParam:oe.removeLastParam,reEditParam:Xe,segments:Qe,suggestions:A,activeIndex:f,isReady:Be,isLoading:Ce,error:qe,inputProps:{value:c,placeholder:de||void 0,onChange:He,onKeyDown:Ve,role:"combobox","aria-expanded":ge,"aria-activedescendant":Ge,"aria-autocomplete":"list","aria-controls":le},reset:We,dropdownProps:{suggestions:C?[{...C,options:fe}]:[],activeIndex:f,onSelect:Ie,onHighlight:s,isOpen:ge,id:le}}}var I=require("react/jsx-runtime"),ze=(0,D.forwardRef)(function({onSubmit:o,onError:t,optionOverrides:r,maskCompletedText:n,placeholder:a,className:i,apiConfig:l,columns:d,value:g,completedParams:p,onChange:b,onParamsChange:h},S){let k=(0,D.useRef)(null),[x,v]=(0,D.useState)(!1),A=(0,D.useRef)(()=>{}),m=(0,D.useRef)(void 0);(0,D.useEffect)(()=>(k.current?.focus(),()=>clearTimeout(m.current)),[]);let{completedParams:f,suggestionPills:s,setActivePill:c,segments:P,inputProps:U,dropdownProps:F,reset:z}=ce({onSubmit:O=>A.current(O),onError:t,optionOverrides:r,maskCompletedText:n,placeholder:a,apiConfig:l,columns:d,value:g,completedParams:p,onChange:b,onParamsChange:h});(0,D.useImperativeHandle)(S,()=>({focus:()=>k.current?.focus(),reset:z}),[z]);let $=()=>{k.current?.focus()},K=!!U.value||f.length>0,R=(0,D.useCallback)(()=>{if(!K)return;let{rawQuery:O,completedParams:_}=G(U.value,f);o({query:U.value.trim(),raw_query:O,completed_params:_}),z(),v(!0),clearTimeout(m.current),m.current=setTimeout(()=>v(!1),3e3)},[K,U.value,f,o,z]);A.current=R;let{onChange:E,placeholder:q,...H}=U,Y=!U.value;return(0,I.jsxs)("div",{className:`${j.container} ${i??""}`,children:[(0,I.jsx)("div",{className:`${j.checkmark} ${x?j.checkmarkVisible:""}`,children:(0,I.jsxs)("svg",{width:"72",height:"72",viewBox:"0 0 24 24",fill:"none",role:"img","aria-label":"Success",children:[(0,I.jsx)("circle",{cx:"12",cy:"12",r:"12",fill:"#34C759"}),(0,I.jsx)("path",{d:"M7 12.5l3.5 3.5L17 9",stroke:"#000",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:j.checkmarkPath})]})}),(0,I.jsx)(re,{...F}),(0,I.jsxs)("div",{className:j.inputWrapper,onClick:$,children:[(0,I.jsxs)("div",{className:j.editorArea,children:[(0,I.jsxs)("div",{className:j.sizerContent,"aria-hidden":"true",children:[Y&&q?(0,I.jsxs)("span",{className:j.placeholderText,children:[q," "]}):(0,I.jsxs)("span",{className:j.sizerText,children:[P.map((O,_)=>(0,I.jsx)("span",{children:O.value},`${_}-${O.type}`)),P.length===0&&"\xA0"]})," ",(0,I.jsx)(Ee,{pills:s,activePillIndex:0,onSelectPill:c})]}),(0,I.jsx)("textarea",{ref:k,className:j.textarea,rows:1,onChange:E,...H})]}),(0,I.jsx)("button",{type:"button",className:j.submitButton,disabled:!K,onClick:O=>{O.stopPropagation(),R()},"aria-label":"Submit",children:(0,I.jsx)("svg",{width:"18",height:"18",viewBox:"0 0 18 18",fill:"none",role:"img","aria-label":"Submit",children:(0,I.jsx)("path",{d:"M9 14V4M9 4L4 9M9 4L14 9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})});0&&(module.exports={AIAutocomplete,AIAutocompleteDropdown,useAIAutocomplete});
1
+ "use strict";var be=Object.defineProperty;var Je=Object.getOwnPropertyDescriptor;var Ze=Object.getOwnPropertyNames;var et=Object.prototype.hasOwnProperty;var tt=(e,o)=>{for(var t in o)be(e,t,{get:o[t],enumerable:!0})},ot=(e,o,t,r)=>{if(o&&typeof o=="object"||typeof o=="function")for(let n of Ze(o))!et.call(e,n)&&n!==t&&be(e,n,{get:()=>o[n],enumerable:!(r=Je(o,n))||r.enumerable});return e};var nt=e=>ot(be({},"__esModule",{value:!0}),e);var St={};tt(St,{AIAutocomplete:()=>ze,AIAutocompleteDropdown:()=>re,useAIAutocomplete:()=>ce});module.exports=nt(St);var D=require("react");var j={};var ye={};var Re={};var W={};var ne=require("react/jsx-runtime");function _e({option:e,isHighlighted:o,onSelect:t,onHighlight:r,id:n}){let a=[W.item,o?W.highlighted:"",e.is_tappable?W.tappable:W.nonTappable].filter(Boolean).join(" ");return(0,ne.jsxs)("div",{id:n,role:"option","aria-selected":o,className:a,tabIndex:e.is_tappable?0:-1,onClick:()=>e.is_tappable&&t(e),onKeyDown:i=>{e.is_tappable&&(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),t(e))},onMouseEnter:r,children:[e.icon?`${e.icon} ${e.text}`:e.text,e.tag&&(0,ne.jsx)("span",{className:W.tag,children:e.tag})]})}var Se=require("react/jsx-runtime");function Te({options:e,activeIndex:o,onSelect:t,onHighlight:r,listboxId:n}){return(0,Se.jsx)("div",{className:Re.grid,children:e.map((a,i)=>(0,Se.jsx)(_e,{option:a,isHighlighted:i===o,onSelect:t,onHighlight:()=>r(i),id:`${n}-option-${i}`},a.text))})}var xe=require("react/jsx-runtime");function re({suggestions:e,activeIndex:o,onSelect:t,onHighlight:r,isOpen:n,id:a,className:i}){let l=e[0],d=n&&l&&l.options.length>0;return(0,xe.jsx)("div",{id:a,role:"listbox",className:`${ye.dropdown} ${d?ye.visible:""} ${i??""}`,onMouseDown:g=>g.preventDefault(),children:l&&l.options.length>0&&(0,xe.jsx)(Te,{options:l.options,activeIndex:o,onSelect:t,onHighlight:r,listboxId:a})})}var ae={};var Pe=require("react/jsx-runtime");function lt(e){return e===0?.4:e===1?.3:.15}function Ee({pills:e,activePillIndex:o,onSelectPill:t}){return(0,Pe.jsx)("span",{className:ae.list,children:e.map((r,n)=>(0,Pe.jsx)("button",{type:"button",className:`${ae.pill} ${n===o?ae.active:""}`,style:{opacity:lt(n)},onClick:()=>t(n),children:r.text},`${r.type}-${r.text}`))})}var u=require("react");function se(e,o){let t=o.trimStart();if(!t)return e;let r=t.toLowerCase();return e.filter(n=>!n.is_tappable||n.text.toLowerCase().includes(r))}function Z(e,o){let t=o.trim();if(!t)return null;let r=t.toLowerCase();return e.find(n=>n.is_tappable&&n.text.toLowerCase()===r)??null}function Me(e,o){let t=[],r=0;for(let a of o){let i=e.indexOf(a.text,r);i!==-1&&(i>r&&t.push({type:"text",value:e.slice(r,i)}),t.push({type:"completed",value:a.text,param:a}),r=i+a.text.length)}let n=e.slice(r);return n&&t.push({type:"text",value:n}),t}function Ue(e,o){let t=[],r=[],n=0;for(let a of o){let i=e.indexOf(a.text,n);i===-1?r.push(a):(t.push(a),n=i+a.text.length)}return{valid:t,invalid:r}}var T=require("react");var ut="0.1.5",pt=process?.env.MAGICX_API_ENDPOINT||"/api/suggest",Le=!1;function mt(e){let o=e?.apiKey||process?.env.MAGICX_AI_AUTOCOMPLETE_API_KEY||"";return!o&&!Le&&(Le=!0,console.warn("[AIAutocomplete] No API key set (MAGICX_AI_AUTOCOMPLETE_API_KEY). Requests will be sent without an Authorization header.")),o}function dt(e){return e?.authScheme?e.authScheme:process?.env.MAGICX_AUTH_SCHEME==="Basic"?"Basic":"Bearer"}function ft(){return crypto.randomUUID()}function gt(e,o){return{placeholder:e.placeholder,type:e.type,...o&&{text:e.text},kind:e.kind}}async function Ne(e,o,t){let r=t?.apiConfig,n=mt(r),a=dt(r),i=!t?.maskCompletedText,l=t?.contactAccountCount,d={data:{raw_query:e,completed_params:o.map(b=>gt(b,i)),...l!=null&&{contact_account_count:l}},meta:{request_id:ft(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:ut}},g={"Content-Type":"application/json","X-App-Identifier":process?.env.MAGICX_APP_IDENTIFIER||"active-campaign-demo",...r?.headers};n&&(g.Authorization=a==="Basic"?`Basic ${btoa(n)}`:`Bearer ${n}`);let p=await fetch(pt,{method:"POST",headers:g,body:JSON.stringify(d),signal:t?.signal});if(!p.ok)throw new Error(`API error: ${p.status} ${p.statusText}`);return p.json()}function G(e,o){let t=e,r={},n=[];for(let a of o){let i=(r[a.type]??0)+1;r[a.type]=i;let d=`{{${a.type.toUpperCase().replace(/\s+/g,"_")}_${i}}}`,g=t.indexOf(a.text);g!==-1&&(t=t.slice(0,g)+d+t.slice(g+a.text.length)),n.push({...a,placeholder:d})}return{rawQuery:t,completedParams:n}}function De(e,o){return o?e.map(t=>{let r=o[t.type];if(!r)return t;let n=r("");if(n.length===0)return t;let a=new Set(n.map(l=>l.text)),i=(t.options??[]).filter(l=>!a.has(l.text));return{...t,options:[...n,...i]}}):e}var ht=100,bt=300,yt=2;function Fe({textRef:e,suggestionsRef:o,filterBaseRef:t,maskCompletedTextRef:r,apiConfigRef:n,optionOverridesRef:a,onErrorRef:i,setCompletedParams:l,setSuggestions:d,setActiveDropdownIndex:g}){let[p,b]=(0,T.useState)(!1),[h,S]=(0,T.useState)(null),[k,x]=(0,T.useState)(!1),v=(0,T.useRef)(0),A=(0,T.useRef)(null),m=(0,T.useRef)(""),f=(0,T.useCallback)(async(s,c)=>{A.current?.abort();let P=new AbortController;A.current=P;let U=++v.current,F=e.current.length;o.current.some($=>$.type!=="placeholder")||b(!0),S(null);try{let $=c.find(_=>_.type==="contact"&&_.metadata?.contact_account_count)?.metadata?.contact_account_count,K=await Ne(s,c,{maskCompletedText:r.current,signal:P.signal,contactAccountCount:typeof $=="number"?$:void 0,apiConfig:n.current});if(U!==v.current)return;let R=De(K.data.suggestions??[],a.current);x(K.data.is_ready??!1),m.current=s;let E=K.data.input??[],q=E[E.length-1],H=e.current;if(q?.state==="in_progress"){let _=H.toLowerCase().lastIndexOf(q.text.toLowerCase());_!==-1?t.current=_:t.current=F}else t.current=F;let O=R.filter(_=>_.type!=="placeholder")[0];if(O){let _=H.slice(t.current),B=Z(O.options,_);B&&(l(M=>[...M,{id:crypto.randomUUID(),placeholder:"",type:O.type,text:B.text,kind:B.kind,suggestionType:O.type,suggestionPlaceholder:O.text,options:O.options,metadata:B.metadata}]),R=R.filter(M=>M!==O))}d(R),b(!1),g(-1)}catch($){if(U===v.current){let K=$ instanceof Error?$:new Error(String($));S(K),b(!1),i.current?.(K)}}},[e,o,t,r,n,a,i,l,d,g]);return(0,T.useEffect)(()=>(f("",[]),()=>{A.current?.abort()}),[f]),{doFetch:f,isLoading:p,error:h,isReady:k,lastRawQueryRef:m}}function $e({text:e,completedParams:o,doFetch:t,filterBaseRef:r,skipNextFetchRef:n,suggestionsRef:a,lastRawQueryRef:i}){let l=(0,T.useRef)(null),d=(0,T.useRef)(null),g=(0,T.useRef)(!0);(0,T.useEffect)(()=>{l.current&&clearTimeout(l.current),d.current&&clearTimeout(d.current);let p=b=>{if(n.current)return n.current=!1,!1;if(!e&&o.length===0)return g.current?(t("",[]),!0):(g.current=!0,!1);let h=e.slice(r.current),x=a.current.filter(F=>F.type!=="placeholder")[0],A=(x?se(x.options,h):[]).filter(F=>F.is_tappable),m=x?Z(x.options,h)!==null:!1,f=h.trim().length>0;if(A.length>0&&!m&&f)return!1;let{rawQuery:s,completedParams:c}=G(e,o),P=s.length<i.current.length,U=Math.abs(s.length-i.current.length);return P||U>=b?(t(s,c),!0):!1};return l.current=setTimeout(()=>{p(yt)&&d.current&&clearTimeout(d.current)},ht),d.current=setTimeout(()=>p(1),bt),()=>{l.current&&clearTimeout(l.current),d.current&&clearTimeout(d.current)}},[e,o,t,r,n,a,i])}var ve=require("react");function Ke({activeDropdownIndex:e,setActiveDropdownIndex:o,filteredOptions:t,selectOption:r,onSubmitRef:n,text:a,completedParams:i,isDropdownOpen:l,hasPlaceholder:d,placeholderText:g,suggestions:p,filterBaseRef:b,columns:h,setText:S,setCompletedParams:k,setSuggestions:x}){let v=(0,ve.useCallback)(()=>{let m=t.map((c,P)=>c.is_tappable?P:-1).filter(c=>c!==-1),f=m.filter(c=>c%h===0),s=m.filter(c=>c%h===1);return[...f,...s]},[t,h]);return{handleKeyDown:(0,ve.useCallback)(m=>{let f=v();switch(m.key){case"ArrowDown":{if(m.preventDefault(),f.length===0)return;let s=f.indexOf(e),c=s<f.length-1?s+1:0;o(f[c]);break}case"ArrowUp":{if(m.preventDefault(),f.length===0)return;let s=f.indexOf(e),c=s>0?s-1:f.length-1;o(f[c]);break}case"ArrowRight":{if(e<0)break;if(e%h===0){let s=e+1;s<t.length&&t[s]?.is_tappable&&(m.preventDefault(),o(s))}break}case"ArrowLeft":{if(e<0)break;if(e%h===1){let s=e-1;s>=0&&t[s]?.is_tappable&&(m.preventDefault(),o(s))}break}case"Enter":{if(m.preventDefault(),e>=0&&t[e]?.is_tappable)r(t[e]);else if(n.current){let{rawQuery:s,completedParams:c}=G(a,i),P={query:a.trim(),raw_query:s,completed_params:c};n.current(P)}break}case"Tab":{if(e>=0&&t[e]?.is_tappable)m.preventDefault(),r(t[e]);else if(l){let s=t.find(c=>c.is_tappable);s&&(m.preventDefault(),r(s))}else if(!a&&d){m.preventDefault();let s=p.find(c=>c.type==="placeholder");s?(S(g),b.current=g.length,k(c=>[...c,{id:crypto.randomUUID(),placeholder:"",type:s.type,text:g,kind:null,suggestionType:s.type,suggestionPlaceholder:s.text,options:s.options}]),x(c=>c.filter(P=>P!==s))):(S(g),b.current=g.length)}break}case"Escape":o(-1);break}},[e,h,i,t,b,v,d,l,n,g,r,o,k,x,S,p,a]),getTappableIndices:v}}var ie=require("react");function je({completedParams:e,suggestions:o,setCompletedParams:t,setSuggestions:r,setActiveDropdownIndex:n,filterBaseRef:a,pillTappedRef:i}){let l=(0,ie.useCallback)(p=>{let b=o.filter(x=>x.type!=="placeholder");if(p<0||p>=b.length)return;let h=b[p],S=b.filter((x,v)=>v!==p),k=o.filter(x=>x.type==="placeholder");r([...k,h,...S]),i.current=!0,n(-1)},[o,r,n,i]),d=(0,ie.useCallback)(()=>{if(e.length===0)return;let p=e[e.length-1],b={type:p.suggestionType,text:p.suggestionPlaceholder,required:!0,options:p.options};t(h=>h.slice(0,-1)),r(h=>[b,...h]),n(-1)},[e,t,r,n]),g=(0,ie.useCallback)(p=>{let b={type:p.suggestionType,text:p.suggestionPlaceholder,required:!0,options:p.options};return{apply:h=>{h(S=>{let k=0;for(let x of e){let v=S.indexOf(x.text,k);if(v!==-1){if(x.id===p.id){let A=S.slice(0,v),m=S.slice(v+p.text.length),f=(A+m).replace(/ {2,}/g," ");return a.current=Math.min(a.current,f.length),f}k=v+x.text.length}}return S}),t(S=>S.filter(k=>k.id!==p.id)),r(S=>[b,...S]),n(-1),i.current=!0}}},[e,t,r,n,a,i]);return{setActivePill:l,removeLastParam:d,reEditParam:g}}function ce({onSubmit:e,onError:o,optionOverrides:t,maskCompletedText:r,placeholder:n,apiConfig:a,columns:i=2,value:l,completedParams:d,onChange:g,onParamsChange:p}){let b=l!==void 0,h=d!==void 0,[S,k]=(0,u.useState)(""),[x,v]=(0,u.useState)([]),[A,m]=(0,u.useState)([]),[f,s]=(0,u.useState)(-1),c=b?l:S,P=h?d:x,U=(0,u.useRef)(e);U.current=e;let F=(0,u.useRef)(g);F.current=g;let z=(0,u.useRef)(p);z.current=p;let $=(0,u.useRef)(l);$.current=l;let K=(0,u.useRef)(d);K.current=d;let R=(0,u.useCallback)(y=>{if(typeof y=="function")if(b){let w=y($.current??"");F.current?.(w)}else k(w=>{let Q=y(w);return F.current?.(Q),Q});else b||k(y),F.current?.(y)},[b]),E=(0,u.useCallback)(y=>{if(typeof y=="function")if(h){let w=y(K.current??[]);z.current?.(w)}else v(w=>{let Q=y(w);return z.current?.(Q),Q});else h||v(y),z.current?.(y)},[h]),q=(0,u.useRef)(o);q.current=o;let H=(0,u.useRef)(t);H.current=t;let Y=(0,u.useRef)(r);Y.current=r;let O=(0,u.useRef)(a);O.current=a;let _=(0,u.useRef)(c);_.current=c;let B=(0,u.useRef)(A);B.current=A;let M=(0,u.useRef)(0),ee=(0,u.useRef)(!1),Ae=(0,u.useRef)(!1),le=(0,u.useId)(),{doFetch:ue,isLoading:Ce,error:qe,isReady:Be,lastRawQueryRef:pe}=Fe({textRef:_,suggestionsRef:B,filterBaseRef:M,maskCompletedTextRef:Y,apiConfigRef:O,optionOverridesRef:H,onErrorRef:q,setCompletedParams:E,setSuggestions:m,setActiveDropdownIndex:s});$e({text:c,completedParams:P,doFetch:ue,filterBaseRef:M,skipNextFetchRef:Ae,suggestionsRef:B,lastRawQueryRef:pe});let Qe=(0,u.useMemo)(()=>Me(c,P),[c,P]);M.current=Math.min(M.current,c.length);let me=c.slice(M.current),de=(0,u.useMemo)(()=>A.filter(w=>w.type==="placeholder").map(w=>w.text).join(" ")||n||"",[A,n]),te=(0,u.useMemo)(()=>A.filter(y=>y.type!=="placeholder"),[A]),C=te[0],ke=C?t?.[C.type]:void 0,we=C?ke?ke(me.trim()):C.options??[]:[],fe=(0,u.useMemo)(()=>se(we,me),[we,me]),Oe=de.length>0,ge=!Ce&&fe.length>0&&(!!c||ee.current||!Oe),Ie=(0,u.useCallback)(y=>{if(!C)return;let w={id:crypto.randomUUID(),placeholder:"",type:C.type,text:y.text,kind:y.kind,suggestionType:C.type,suggestionPlaceholder:C.text,options:C.options,metadata:y.metadata},Q=M.current,L=_.current.slice(0,Q);if(L.length>0&&!L.endsWith(" ")){let N=L.split(/\s+/).pop()??"";N&&y.text.toLowerCase().startsWith(N.toLowerCase())&&(L=L.slice(0,L.length-N.length))}let he=L.length>0&&L[L.length-1]!==" ",V=L+(he?" ":"")+y.text+" ";R(V),M.current=V.length,E(N=>[...N,w]),m(N=>N.filter(J=>J!==C)),ee.current=!1,s(-1),te.length-1>0&&(Ae.current=!0)},[C,te,R,E]),He=(0,u.useCallback)(y=>{let w=y.target.value,L=w.length>0&&!y.nativeEvent?.isComposing&&w[0]!==w[0].toUpperCase()?w[0].toUpperCase()+w.slice(1):w;R(L),ee.current=!1,s(-1);let{valid:he,invalid:V}=Ue(L,P);if(V.length>0){E(()=>he);for(let X of V)m(N=>[{type:X.suggestionType,text:X.suggestionPlaceholder,required:!0,options:X.options},...N])}if(C&&V.length===0){let X=L.slice(M.current),N=Z(C.options,X);N&&(E(J=>[...J,{id:crypto.randomUUID(),placeholder:"",type:C.type,text:N.text,kind:N.kind,suggestionType:C.type,suggestionPlaceholder:C.text,options:C.options,metadata:N.metadata}]),m(J=>J.filter(Ye=>Ye!==C)))}},[P,C,R,E]),{handleKeyDown:Ve}=Ke({activeDropdownIndex:f,setActiveDropdownIndex:s,filteredOptions:fe,selectOption:Ie,onSubmitRef:U,text:c,completedParams:P,isDropdownOpen:ge,hasPlaceholder:Oe,placeholderText:de,suggestions:A,filterBaseRef:M,columns:i,setText:R,setCompletedParams:E,setSuggestions:m}),oe=je({completedParams:P,suggestions:A,setCompletedParams:E,setSuggestions:m,setActiveDropdownIndex:s,filterBaseRef:M,pillTappedRef:ee}),Xe=(0,u.useCallback)(y=>{oe.reEditParam(y).apply(R)},[oe,R]),We=(0,u.useCallback)(()=>{R(""),E(()=>[]),m([]),s(-1),M.current=0,pe.current="",ue("",[])},[ue,R,E,pe]),Ge=f>=0?`${le}-option-${f}`:void 0;return{completedParams:P,suggestionPills:te,setActivePill:oe.setActivePill,removeLastParam:oe.removeLastParam,reEditParam:Xe,segments:Qe,suggestions:A,activeIndex:f,isReady:Be,isLoading:Ce,error:qe,inputProps:{value:c,placeholder:de||void 0,onChange:He,onKeyDown:Ve,role:"combobox","aria-expanded":ge,"aria-activedescendant":Ge,"aria-autocomplete":"list","aria-controls":le},reset:We,dropdownProps:{suggestions:C?[{...C,options:fe}]:[],activeIndex:f,onSelect:Ie,onHighlight:s,isOpen:ge,id:le}}}var I=require("react/jsx-runtime"),ze=(0,D.forwardRef)(function({onSubmit:o,onError:t,optionOverrides:r,maskCompletedText:n,placeholder:a,className:i,apiConfig:l,columns:d,value:g,completedParams:p,onChange:b,onParamsChange:h},S){let k=(0,D.useRef)(null),[x,v]=(0,D.useState)(!1),A=(0,D.useRef)(()=>{}),m=(0,D.useRef)(void 0);(0,D.useEffect)(()=>(k.current?.focus(),()=>clearTimeout(m.current)),[]);let{completedParams:f,suggestionPills:s,setActivePill:c,segments:P,inputProps:U,dropdownProps:F,reset:z}=ce({onSubmit:O=>A.current(O),onError:t,optionOverrides:r,maskCompletedText:n,placeholder:a,apiConfig:l,columns:d,value:g,completedParams:p,onChange:b,onParamsChange:h});(0,D.useImperativeHandle)(S,()=>({focus:()=>k.current?.focus(),reset:z}),[z]);let $=()=>{k.current?.focus()},K=!!U.value||f.length>0,R=(0,D.useCallback)(()=>{if(!K)return;let{rawQuery:O,completedParams:_}=G(U.value,f);o({query:U.value.trim(),raw_query:O,completed_params:_}),z(),v(!0),clearTimeout(m.current),m.current=setTimeout(()=>v(!1),3e3)},[K,U.value,f,o,z]);A.current=R;let{onChange:E,placeholder:q,...H}=U,Y=!U.value;return(0,I.jsxs)("div",{className:`${j.container} ${i??""}`,children:[(0,I.jsx)("div",{className:`${j.checkmark} ${x?j.checkmarkVisible:""}`,children:(0,I.jsxs)("svg",{width:"72",height:"72",viewBox:"0 0 24 24",fill:"none",role:"img","aria-label":"Success",children:[(0,I.jsx)("circle",{cx:"12",cy:"12",r:"12",fill:"#34C759"}),(0,I.jsx)("path",{d:"M7 12.5l3.5 3.5L17 9",stroke:"#000",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:j.checkmarkPath})]})}),(0,I.jsx)(re,{...F}),(0,I.jsxs)("div",{className:j.inputWrapper,onClick:$,children:[(0,I.jsxs)("div",{className:j.editorArea,children:[(0,I.jsxs)("div",{className:j.sizerContent,"aria-hidden":"true",children:[Y&&q?(0,I.jsxs)("span",{className:j.placeholderText,children:[q," "]}):(0,I.jsxs)("span",{className:j.sizerText,children:[P.map((O,_)=>(0,I.jsx)("span",{children:O.value},`${_}-${O.type}`)),P.length===0&&"\xA0"]})," ",(0,I.jsx)(Ee,{pills:s,activePillIndex:0,onSelectPill:c})]}),(0,I.jsx)("textarea",{ref:k,className:j.textarea,rows:1,onChange:E,...H})]}),(0,I.jsx)("button",{type:"button",className:j.submitButton,disabled:!K,onClick:O=>{O.stopPropagation(),R()},"aria-label":"Submit",children:(0,I.jsx)("svg",{width:"18",height:"18",viewBox:"0 0 18 18",fill:"none",role:"img","aria-label":"Submit",children:(0,I.jsx)("path",{d:"M9 14V4M9 4L4 9M9 4L14 9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})});0&&(module.exports={AIAutocomplete,AIAutocompleteDropdown,useAIAutocomplete});
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{forwardRef as xt,useCallback as Pt,useEffect as vt,useImperativeHandle as At,useRef as Pe,useState as Ct}from"react";var F={};var he={};var Ie={};var X={};import{jsx as at,jsxs as st}from"react/jsx-runtime";function Re({option:e,isHighlighted:r,onSelect:t,onHighlight:o,id:n}){let a=[X.item,r?X.highlighted:"",e.is_tappable?X.tappable:X.nonTappable].filter(Boolean).join(" ");return st("div",{id:n,role:"option","aria-selected":r,className:a,tabIndex:e.is_tappable?0:-1,onClick:()=>e.is_tappable&&t(e),onKeyDown:i=>{e.is_tappable&&(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),t(e))},onMouseEnter:o,children:[e.icon?`${e.icon} ${e.text}`:e.text,e.tag&&at("span",{className:X.tag,children:e.tag})]})}import{jsx as _e}from"react/jsx-runtime";function Te({options:e,activeIndex:r,onSelect:t,onHighlight:o,listboxId:n}){return _e("div",{className:Ie.grid,children:e.map((a,i)=>_e(Re,{option:a,isHighlighted:i===r,onSelect:t,onHighlight:()=>o(i),id:`${n}-option-${i}`},a.text))})}import{jsx as Ee}from"react/jsx-runtime";function be({suggestions:e,activeIndex:r,onSelect:t,onHighlight:o,isOpen:n,id:a,className:i}){let l=e[0],m=n&&l&&l.options.length>0;return Ee("div",{id:a,role:"listbox",className:`${he.dropdown} ${m?he.visible:""} ${i??""}`,onMouseDown:f=>f.preventDefault(),children:l&&l.options.length>0&&Ee(Te,{options:l.options,activeIndex:r,onSelect:t,onHighlight:o,listboxId:a})})}var re={};import{jsx as Me}from"react/jsx-runtime";function ct(e){return e===0?.4:e===1?.3:.15}function Ue({pills:e,activePillIndex:r,onSelectPill:t}){return Me("span",{className:re.list,children:e.map((o,n)=>Me("button",{type:"button",className:`${re.pill} ${n===r?re.active:""}`,style:{opacity:ct(n)},onClick:()=>t(n),children:o.text},`${o.type}-${o.text}`))})}import{useCallback as Y,useId as St,useMemo as se,useRef as U,useState as ie}from"react";function ae(e,r){let t=r.trimStart();if(!t)return e;let o=t.toLowerCase();return e.filter(n=>!n.is_tappable||n.text.toLowerCase().includes(o))}function ee(e,r){let t=r.trim();if(!t)return null;let o=t.toLowerCase();return e.find(n=>n.is_tappable&&n.text.toLowerCase()===o)??null}function Le(e,r){let t=[],o=0;for(let a of r){let i=e.indexOf(a.text,o);i!==-1&&(i>o&&t.push({type:"text",value:e.slice(o,i)}),t.push({type:"completed",value:a.text,param:a}),o=i+a.text.length)}let n=e.slice(o);return n&&t.push({type:"text",value:n}),t}function Ne(e,r){let t=[],o=[],n=0;for(let a of r){let i=e.indexOf(a.text,n);i===-1?o.push(a):(t.push(a),n=i+a.text.length)}return{valid:t,invalid:o}}import{useCallback as gt,useEffect as Ke,useRef as G,useState as ye}from"react";var lt="0.1.4",ut=process?.env.MAGICX_API_ENDPOINT||"/api/suggest",De=!1;function pt(e){let r=e?.apiKey||process?.env.MAGICX_AI_AUTOCOMPLETE_API_KEY||"";return!r&&!De&&(De=!0,console.warn("[AIAutocomplete] No API key set (MAGICX_AI_AUTOCOMPLETE_API_KEY). Requests will be sent without an Authorization header.")),r}function mt(e){return e?.authScheme?e.authScheme:process?.env.MAGICX_AUTH_SCHEME==="Basic"?"Basic":"Bearer"}function dt(){return crypto.randomUUID()}function ft(e,r){return{placeholder:e.placeholder,type:e.type,...r&&{text:e.text},kind:e.kind}}async function Fe(e,r,t){let o=t?.apiConfig,n=pt(o),a=mt(o),i=!t?.maskCompletedText,l=t?.contactAccountCount,m={data:{raw_query:e,completed_params:r.map(h=>ft(h,i)),...l!=null&&{contact_account_count:l}},meta:{request_id:dt(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:lt}},f={"Content-Type":"application/json","X-App-Identifier":process?.env.MAGICX_APP_IDENTIFIER||"active-campaign-demo",...o?.headers};n&&(f.Authorization=a==="Basic"?`Basic ${btoa(n)}`:`Bearer ${n}`);let u=await fetch(ut,{method:"POST",headers:f,body:JSON.stringify(m),signal:t?.signal});if(!u.ok)throw new Error(`API error: ${u.status} ${u.statusText}`);return u.json()}function W(e,r){let t=e,o={},n=[];for(let a of r){let i=(o[a.type]??0)+1;o[a.type]=i;let m=`{{${a.type.toUpperCase().replace(/\s+/g,"_")}_${i}}}`,f=t.indexOf(a.text);f!==-1&&(t=t.slice(0,f)+m+t.slice(f+a.text.length)),n.push({...a,placeholder:m})}return{rawQuery:t,completedParams:n}}function $e(e,r){return r?e.map(t=>{let o=r[t.type];if(!o)return t;let n=o("");if(n.length===0)return t;let a=new Set(n.map(l=>l.text)),i=(t.options??[]).filter(l=>!a.has(l.text));return{...t,options:[...n,...i]}}):e}var ht=100,bt=300,yt=2;function je({textRef:e,suggestionsRef:r,filterBaseRef:t,maskCompletedTextRef:o,apiConfigRef:n,optionOverridesRef:a,onErrorRef:i,setCompletedParams:l,setSuggestions:m,setActiveDropdownIndex:f}){let[u,h]=ye(!1),[g,y]=ye(null),[C,S]=ye(!1),P=G(0),v=G(null),p=G(""),d=gt(async(s,c)=>{v.current?.abort();let x=new AbortController;v.current=x;let T=++P.current,L=e.current.length;r.current.some(N=>N.type!=="placeholder")||h(!0),y(null);try{let N=c.find(I=>I.type==="contact"&&I.metadata?.contact_account_count)?.metadata?.contact_account_count,D=await Fe(s,c,{maskCompletedText:o.current,signal:x.signal,contactAccountCount:typeof N=="number"?N:void 0,apiConfig:n.current});if(T!==P.current)return;let O=$e(D.data.suggestions??[],a.current);S(D.data.is_ready??!1),p.current=s;let R=D.data.input??[],j=R[R.length-1],B=e.current;if(j?.state==="in_progress"){let I=B.toLowerCase().lastIndexOf(j.text.toLowerCase());I!==-1?t.current=I:t.current=L}else t.current=L;let w=O.filter(I=>I.type!=="placeholder")[0];if(w){let I=B.slice(t.current),z=ee(w.options,I);z&&(l(_=>[..._,{id:crypto.randomUUID(),placeholder:"",type:w.type,text:z.text,kind:z.kind,suggestionType:w.type,suggestionPlaceholder:w.text,options:w.options,metadata:z.metadata}]),O=O.filter(_=>_!==w))}m(O),h(!1),f(-1)}catch(N){if(T===P.current){let D=N instanceof Error?N:new Error(String(N));y(D),h(!1),i.current?.(D)}}},[e,r,t,o,n,a,i,l,m,f]);return Ke(()=>(d("",[]),()=>{v.current?.abort()}),[d]),{doFetch:d,isLoading:u,error:g,isReady:C,lastRawQueryRef:p}}function ze({text:e,completedParams:r,doFetch:t,filterBaseRef:o,skipNextFetchRef:n,suggestionsRef:a,lastRawQueryRef:i}){let l=G(null),m=G(null),f=G(!0);Ke(()=>{l.current&&clearTimeout(l.current),m.current&&clearTimeout(m.current);let u=h=>{if(n.current)return n.current=!1,!1;if(!e&&r.length===0)return f.current?(t("",[]),!0):(f.current=!0,!1);let g=e.slice(o.current),S=a.current.filter(L=>L.type!=="placeholder")[0],v=(S?ae(S.options,g):[]).filter(L=>L.is_tappable),p=S?ee(S.options,g)!==null:!1,d=g.trim().length>0;if(v.length>0&&!p&&d)return!1;let{rawQuery:s,completedParams:c}=W(e,r),x=s.length<i.current.length,T=Math.abs(s.length-i.current.length);return x||T>=h?(t(s,c),!0):!1};return l.current=setTimeout(()=>{u(yt)&&m.current&&clearTimeout(m.current)},ht),m.current=setTimeout(()=>u(1),bt),()=>{l.current&&clearTimeout(l.current),m.current&&clearTimeout(m.current)}},[e,r,t,o,n,a,i])}import{useCallback as qe}from"react";function Be({activeDropdownIndex:e,setActiveDropdownIndex:r,filteredOptions:t,selectOption:o,onSubmitRef:n,text:a,completedParams:i,isDropdownOpen:l,hasPlaceholder:m,placeholderText:f,suggestions:u,filterBaseRef:h,columns:g,setText:y,setCompletedParams:C,setSuggestions:S}){let P=qe(()=>{let p=t.map((c,x)=>c.is_tappable?x:-1).filter(c=>c!==-1),d=p.filter(c=>c%g===0),s=p.filter(c=>c%g===1);return[...d,...s]},[t,g]);return{handleKeyDown:qe(p=>{let d=P();switch(p.key){case"ArrowDown":{if(p.preventDefault(),d.length===0)return;let s=d.indexOf(e),c=s<d.length-1?s+1:0;r(d[c]);break}case"ArrowUp":{if(p.preventDefault(),d.length===0)return;let s=d.indexOf(e),c=s>0?s-1:d.length-1;r(d[c]);break}case"ArrowRight":{if(e<0)break;if(e%g===0){let s=e+1;s<t.length&&t[s]?.is_tappable&&(p.preventDefault(),r(s))}break}case"ArrowLeft":{if(e<0)break;if(e%g===1){let s=e-1;s>=0&&t[s]?.is_tappable&&(p.preventDefault(),r(s))}break}case"Enter":{if(p.preventDefault(),e>=0&&t[e]?.is_tappable)o(t[e]);else if(n.current){let{rawQuery:s,completedParams:c}=W(a,i),x={query:a.trim(),raw_query:s,completed_params:c};n.current(x)}break}case"Tab":{if(e>=0&&t[e]?.is_tappable)p.preventDefault(),o(t[e]);else if(l){let s=t.find(c=>c.is_tappable);s&&(p.preventDefault(),o(s))}else if(!a&&m){p.preventDefault();let s=u.find(c=>c.type==="placeholder");s?(y(f),h.current=f.length,C(c=>[...c,{id:crypto.randomUUID(),placeholder:"",type:s.type,text:f,kind:null,suggestionType:s.type,suggestionPlaceholder:s.text,options:s.options}]),S(c=>c.filter(x=>x!==s))):(y(f),h.current=f.length)}break}case"Escape":r(-1);break}},[e,g,i,t,h,P,m,l,n,f,o,r,C,S,y,u,a]),getTappableIndices:P}}import{useCallback as Se}from"react";function Qe({completedParams:e,suggestions:r,setCompletedParams:t,setSuggestions:o,setActiveDropdownIndex:n,filterBaseRef:a,pillTappedRef:i}){let l=Se(u=>{let h=r.filter(S=>S.type!=="placeholder");if(u<0||u>=h.length)return;let g=h[u],y=h.filter((S,P)=>P!==u),C=r.filter(S=>S.type==="placeholder");o([...C,g,...y]),i.current=!0,n(-1)},[r,o,n,i]),m=Se(()=>{if(e.length===0)return;let u=e[e.length-1],h={type:u.suggestionType,text:u.suggestionPlaceholder,required:!0,options:u.options};t(g=>g.slice(0,-1)),o(g=>[h,...g]),n(-1)},[e,t,o,n]),f=Se(u=>{let h={type:u.suggestionType,text:u.suggestionPlaceholder,required:!0,options:u.options};return{apply:g=>{g(y=>{let C=0;for(let S of e){let P=y.indexOf(S.text,C);if(P!==-1){if(S.id===u.id){let v=y.slice(0,P),p=y.slice(P+u.text.length),d=(v+p).replace(/ {2,}/g," ");return a.current=Math.min(a.current,d.length),d}C=P+S.text.length}}return y}),t(y=>y.filter(C=>C.id!==u.id)),o(y=>[h,...y]),n(-1),i.current=!0}}},[e,t,o,n,a,i]);return{setActivePill:l,removeLastParam:m,reEditParam:f}}function xe({onSubmit:e,onError:r,optionOverrides:t,maskCompletedText:o,placeholder:n,apiConfig:a,columns:i=2,value:l,completedParams:m,onChange:f,onParamsChange:u}){let h=l!==void 0,g=m!==void 0,[y,C]=ie(""),[S,P]=ie([]),[v,p]=ie([]),[d,s]=ie(-1),c=h?l:y,x=g?m:S,T=U(e);T.current=e;let L=U(f);L.current=f;let $=U(u);$.current=u;let N=U(l);N.current=l;let D=U(m);D.current=m;let O=Y(b=>{if(typeof b=="function")if(h){let k=b(N.current??"");L.current?.(k)}else C(k=>{let q=b(k);return L.current?.(q),q});else h||C(b),L.current?.(b)},[h]),R=Y(b=>{if(typeof b=="function")if(g){let k=b(D.current??[]);$.current?.(k)}else P(k=>{let q=b(k);return $.current?.(q),q});else g||P(b),$.current?.(b)},[g]),j=U(r);j.current=r;let B=U(t);B.current=t;let J=U(o);J.current=o;let w=U(a);w.current=a;let I=U(c);I.current=c;let z=U(v);z.current=v;let _=U(0),te=U(!1),ve=U(!1),ce=St(),{doFetch:le,isLoading:Ae,error:He,isReady:Ve,lastRawQueryRef:ue}=je({textRef:I,suggestionsRef:z,filterBaseRef:_,maskCompletedTextRef:J,apiConfigRef:w,optionOverridesRef:B,onErrorRef:j,setCompletedParams:R,setSuggestions:p,setActiveDropdownIndex:s});ze({text:c,completedParams:x,doFetch:le,filterBaseRef:_,skipNextFetchRef:ve,suggestionsRef:z,lastRawQueryRef:ue});let Xe=se(()=>Le(c,x),[c,x]);_.current=Math.min(_.current,c.length);let pe=c.slice(_.current),me=se(()=>v.filter(k=>k.type==="placeholder").map(k=>k.text).join(" ")||n||"",[v,n]),oe=se(()=>v.filter(b=>b.type!=="placeholder"),[v]),A=oe[0],Ce=A?t?.[A.type]:void 0,ke=A?Ce?Ce(pe.trim()):A.options??[]:[],de=se(()=>ae(ke,pe),[ke,pe]),we=me.length>0,fe=!Ae&&de.length>0&&(!!c||te.current||!we),Oe=Y(b=>{if(!A)return;let k={id:crypto.randomUUID(),placeholder:"",type:A.type,text:b.text,kind:b.kind,suggestionType:A.type,suggestionPlaceholder:A.text,options:A.options,metadata:b.metadata},q=_.current,E=I.current.slice(0,q);if(E.length>0&&!E.endsWith(" ")){let M=E.split(/\s+/).pop()??"";M&&b.text.toLowerCase().startsWith(M.toLowerCase())&&(E=E.slice(0,E.length-M.length))}let ge=E.length>0&&E[E.length-1]!==" ",H=E+(ge?" ":"")+b.text+" ";O(H),_.current=H.length,R(M=>[...M,k]),p(M=>M.filter(Z=>Z!==A)),te.current=!1,s(-1),oe.length-1>0&&(ve.current=!0)},[A,oe,O,R]),We=Y(b=>{let k=b.target.value,E=k.length>0&&!b.nativeEvent?.isComposing&&k[0]!==k[0].toUpperCase()?k[0].toUpperCase()+k.slice(1):k;O(E),te.current=!1,s(-1);let{valid:ge,invalid:H}=Ne(E,x);if(H.length>0){R(()=>ge);for(let V of H)p(M=>[{type:V.suggestionType,text:V.suggestionPlaceholder,required:!0,options:V.options},...M])}if(A&&H.length===0){let V=E.slice(_.current),M=ee(A.options,V);M&&(R(Z=>[...Z,{id:crypto.randomUUID(),placeholder:"",type:A.type,text:M.text,kind:M.kind,suggestionType:A.type,suggestionPlaceholder:A.text,options:A.options,metadata:M.metadata}]),p(Z=>Z.filter(et=>et!==A)))}},[x,A,O,R]),{handleKeyDown:Ge}=Be({activeDropdownIndex:d,setActiveDropdownIndex:s,filteredOptions:de,selectOption:Oe,onSubmitRef:T,text:c,completedParams:x,isDropdownOpen:fe,hasPlaceholder:we,placeholderText:me,suggestions:v,filterBaseRef:_,columns:i,setText:O,setCompletedParams:R,setSuggestions:p}),ne=Qe({completedParams:x,suggestions:v,setCompletedParams:R,setSuggestions:p,setActiveDropdownIndex:s,filterBaseRef:_,pillTappedRef:te}),Ye=Y(b=>{ne.reEditParam(b).apply(O)},[ne,O]),Je=Y(()=>{O(""),R(()=>[]),p([]),s(-1),_.current=0,ue.current="",le("",[])},[le,O,R,ue]),Ze=d>=0?`${ce}-option-${d}`:void 0;return{completedParams:x,suggestionPills:oe,setActivePill:ne.setActivePill,removeLastParam:ne.removeLastParam,reEditParam:Ye,segments:Xe,suggestions:v,activeIndex:d,isReady:Ve,isLoading:Ae,error:He,inputProps:{value:c,placeholder:me||void 0,onChange:We,onKeyDown:Ge,role:"combobox","aria-expanded":fe,"aria-activedescendant":Ze,"aria-autocomplete":"list","aria-controls":ce},reset:Je,dropdownProps:{suggestions:A?[{...A,options:de}]:[],activeIndex:d,onSelect:Oe,onHighlight:s,isOpen:fe,id:ce}}}import{jsx as K,jsxs as Q}from"react/jsx-runtime";var kt=xt(function({onSubmit:r,onError:t,optionOverrides:o,maskCompletedText:n,placeholder:a,className:i,apiConfig:l,columns:m,value:f,completedParams:u,onChange:h,onParamsChange:g},y){let C=Pe(null),[S,P]=Ct(!1),v=Pe(()=>{}),p=Pe(void 0);vt(()=>(C.current?.focus(),()=>clearTimeout(p.current)),[]);let{completedParams:d,suggestionPills:s,setActivePill:c,segments:x,inputProps:T,dropdownProps:L,reset:$}=xe({onSubmit:w=>v.current(w),onError:t,optionOverrides:o,maskCompletedText:n,placeholder:a,apiConfig:l,columns:m,value:f,completedParams:u,onChange:h,onParamsChange:g});At(y,()=>({focus:()=>C.current?.focus(),reset:$}),[$]);let N=()=>{C.current?.focus()},D=!!T.value||d.length>0,O=Pt(()=>{if(!D)return;let{rawQuery:w,completedParams:I}=W(T.value,d);r({query:T.value.trim(),raw_query:w,completed_params:I}),$(),P(!0),clearTimeout(p.current),p.current=setTimeout(()=>P(!1),3e3)},[D,T.value,d,r,$]);v.current=O;let{onChange:R,placeholder:j,...B}=T,J=!T.value;return Q("div",{className:`${F.container} ${i??""}`,children:[K("div",{className:`${F.checkmark} ${S?F.checkmarkVisible:""}`,children:Q("svg",{width:"72",height:"72",viewBox:"0 0 24 24",fill:"none",role:"img","aria-label":"Success",children:[K("circle",{cx:"12",cy:"12",r:"12",fill:"#34C759"}),K("path",{d:"M7 12.5l3.5 3.5L17 9",stroke:"#000",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:F.checkmarkPath})]})}),K(be,{...L}),Q("div",{className:F.inputWrapper,onClick:N,children:[Q("div",{className:F.editorArea,children:[Q("div",{className:F.sizerContent,"aria-hidden":"true",children:[J&&j?Q("span",{className:F.placeholderText,children:[j," "]}):Q("span",{className:F.sizerText,children:[x.map((w,I)=>K("span",{children:w.value},`${I}-${w.type}`)),x.length===0&&"\xA0"]})," ",K(Ue,{pills:s,activePillIndex:0,onSelectPill:c})]}),K("textarea",{ref:C,className:F.textarea,rows:1,onChange:R,...B})]}),K("button",{type:"button",className:F.submitButton,disabled:!D,onClick:w=>{w.stopPropagation(),O()},"aria-label":"Submit",children:K("svg",{width:"18",height:"18",viewBox:"0 0 18 18",fill:"none",role:"img","aria-label":"Submit",children:K("path",{d:"M9 14V4M9 4L4 9M9 4L14 9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})});export{kt as AIAutocomplete,be as AIAutocompleteDropdown,xe as useAIAutocomplete};
1
+ import{forwardRef as xt,useCallback as Pt,useEffect as vt,useImperativeHandle as At,useRef as Pe,useState as Ct}from"react";var F={};var he={};var Ie={};var X={};import{jsx as at,jsxs as st}from"react/jsx-runtime";function Re({option:e,isHighlighted:r,onSelect:t,onHighlight:o,id:n}){let a=[X.item,r?X.highlighted:"",e.is_tappable?X.tappable:X.nonTappable].filter(Boolean).join(" ");return st("div",{id:n,role:"option","aria-selected":r,className:a,tabIndex:e.is_tappable?0:-1,onClick:()=>e.is_tappable&&t(e),onKeyDown:i=>{e.is_tappable&&(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),t(e))},onMouseEnter:o,children:[e.icon?`${e.icon} ${e.text}`:e.text,e.tag&&at("span",{className:X.tag,children:e.tag})]})}import{jsx as _e}from"react/jsx-runtime";function Te({options:e,activeIndex:r,onSelect:t,onHighlight:o,listboxId:n}){return _e("div",{className:Ie.grid,children:e.map((a,i)=>_e(Re,{option:a,isHighlighted:i===r,onSelect:t,onHighlight:()=>o(i),id:`${n}-option-${i}`},a.text))})}import{jsx as Ee}from"react/jsx-runtime";function be({suggestions:e,activeIndex:r,onSelect:t,onHighlight:o,isOpen:n,id:a,className:i}){let l=e[0],m=n&&l&&l.options.length>0;return Ee("div",{id:a,role:"listbox",className:`${he.dropdown} ${m?he.visible:""} ${i??""}`,onMouseDown:f=>f.preventDefault(),children:l&&l.options.length>0&&Ee(Te,{options:l.options,activeIndex:r,onSelect:t,onHighlight:o,listboxId:a})})}var re={};import{jsx as Me}from"react/jsx-runtime";function ct(e){return e===0?.4:e===1?.3:.15}function Ue({pills:e,activePillIndex:r,onSelectPill:t}){return Me("span",{className:re.list,children:e.map((o,n)=>Me("button",{type:"button",className:`${re.pill} ${n===r?re.active:""}`,style:{opacity:ct(n)},onClick:()=>t(n),children:o.text},`${o.type}-${o.text}`))})}import{useCallback as Y,useId as St,useMemo as se,useRef as U,useState as ie}from"react";function ae(e,r){let t=r.trimStart();if(!t)return e;let o=t.toLowerCase();return e.filter(n=>!n.is_tappable||n.text.toLowerCase().includes(o))}function ee(e,r){let t=r.trim();if(!t)return null;let o=t.toLowerCase();return e.find(n=>n.is_tappable&&n.text.toLowerCase()===o)??null}function Le(e,r){let t=[],o=0;for(let a of r){let i=e.indexOf(a.text,o);i!==-1&&(i>o&&t.push({type:"text",value:e.slice(o,i)}),t.push({type:"completed",value:a.text,param:a}),o=i+a.text.length)}let n=e.slice(o);return n&&t.push({type:"text",value:n}),t}function Ne(e,r){let t=[],o=[],n=0;for(let a of r){let i=e.indexOf(a.text,n);i===-1?o.push(a):(t.push(a),n=i+a.text.length)}return{valid:t,invalid:o}}import{useCallback as gt,useEffect as Ke,useRef as G,useState as ye}from"react";var lt="0.1.5",ut=process?.env.MAGICX_API_ENDPOINT||"/api/suggest",De=!1;function pt(e){let r=e?.apiKey||process?.env.MAGICX_AI_AUTOCOMPLETE_API_KEY||"";return!r&&!De&&(De=!0,console.warn("[AIAutocomplete] No API key set (MAGICX_AI_AUTOCOMPLETE_API_KEY). Requests will be sent without an Authorization header.")),r}function mt(e){return e?.authScheme?e.authScheme:process?.env.MAGICX_AUTH_SCHEME==="Basic"?"Basic":"Bearer"}function dt(){return crypto.randomUUID()}function ft(e,r){return{placeholder:e.placeholder,type:e.type,...r&&{text:e.text},kind:e.kind}}async function Fe(e,r,t){let o=t?.apiConfig,n=pt(o),a=mt(o),i=!t?.maskCompletedText,l=t?.contactAccountCount,m={data:{raw_query:e,completed_params:r.map(h=>ft(h,i)),...l!=null&&{contact_account_count:l}},meta:{request_id:dt(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:lt}},f={"Content-Type":"application/json","X-App-Identifier":process?.env.MAGICX_APP_IDENTIFIER||"active-campaign-demo",...o?.headers};n&&(f.Authorization=a==="Basic"?`Basic ${btoa(n)}`:`Bearer ${n}`);let u=await fetch(ut,{method:"POST",headers:f,body:JSON.stringify(m),signal:t?.signal});if(!u.ok)throw new Error(`API error: ${u.status} ${u.statusText}`);return u.json()}function W(e,r){let t=e,o={},n=[];for(let a of r){let i=(o[a.type]??0)+1;o[a.type]=i;let m=`{{${a.type.toUpperCase().replace(/\s+/g,"_")}_${i}}}`,f=t.indexOf(a.text);f!==-1&&(t=t.slice(0,f)+m+t.slice(f+a.text.length)),n.push({...a,placeholder:m})}return{rawQuery:t,completedParams:n}}function $e(e,r){return r?e.map(t=>{let o=r[t.type];if(!o)return t;let n=o("");if(n.length===0)return t;let a=new Set(n.map(l=>l.text)),i=(t.options??[]).filter(l=>!a.has(l.text));return{...t,options:[...n,...i]}}):e}var ht=100,bt=300,yt=2;function je({textRef:e,suggestionsRef:r,filterBaseRef:t,maskCompletedTextRef:o,apiConfigRef:n,optionOverridesRef:a,onErrorRef:i,setCompletedParams:l,setSuggestions:m,setActiveDropdownIndex:f}){let[u,h]=ye(!1),[g,y]=ye(null),[C,S]=ye(!1),P=G(0),v=G(null),p=G(""),d=gt(async(s,c)=>{v.current?.abort();let x=new AbortController;v.current=x;let T=++P.current,L=e.current.length;r.current.some(N=>N.type!=="placeholder")||h(!0),y(null);try{let N=c.find(I=>I.type==="contact"&&I.metadata?.contact_account_count)?.metadata?.contact_account_count,D=await Fe(s,c,{maskCompletedText:o.current,signal:x.signal,contactAccountCount:typeof N=="number"?N:void 0,apiConfig:n.current});if(T!==P.current)return;let O=$e(D.data.suggestions??[],a.current);S(D.data.is_ready??!1),p.current=s;let R=D.data.input??[],j=R[R.length-1],B=e.current;if(j?.state==="in_progress"){let I=B.toLowerCase().lastIndexOf(j.text.toLowerCase());I!==-1?t.current=I:t.current=L}else t.current=L;let w=O.filter(I=>I.type!=="placeholder")[0];if(w){let I=B.slice(t.current),z=ee(w.options,I);z&&(l(_=>[..._,{id:crypto.randomUUID(),placeholder:"",type:w.type,text:z.text,kind:z.kind,suggestionType:w.type,suggestionPlaceholder:w.text,options:w.options,metadata:z.metadata}]),O=O.filter(_=>_!==w))}m(O),h(!1),f(-1)}catch(N){if(T===P.current){let D=N instanceof Error?N:new Error(String(N));y(D),h(!1),i.current?.(D)}}},[e,r,t,o,n,a,i,l,m,f]);return Ke(()=>(d("",[]),()=>{v.current?.abort()}),[d]),{doFetch:d,isLoading:u,error:g,isReady:C,lastRawQueryRef:p}}function ze({text:e,completedParams:r,doFetch:t,filterBaseRef:o,skipNextFetchRef:n,suggestionsRef:a,lastRawQueryRef:i}){let l=G(null),m=G(null),f=G(!0);Ke(()=>{l.current&&clearTimeout(l.current),m.current&&clearTimeout(m.current);let u=h=>{if(n.current)return n.current=!1,!1;if(!e&&r.length===0)return f.current?(t("",[]),!0):(f.current=!0,!1);let g=e.slice(o.current),S=a.current.filter(L=>L.type!=="placeholder")[0],v=(S?ae(S.options,g):[]).filter(L=>L.is_tappable),p=S?ee(S.options,g)!==null:!1,d=g.trim().length>0;if(v.length>0&&!p&&d)return!1;let{rawQuery:s,completedParams:c}=W(e,r),x=s.length<i.current.length,T=Math.abs(s.length-i.current.length);return x||T>=h?(t(s,c),!0):!1};return l.current=setTimeout(()=>{u(yt)&&m.current&&clearTimeout(m.current)},ht),m.current=setTimeout(()=>u(1),bt),()=>{l.current&&clearTimeout(l.current),m.current&&clearTimeout(m.current)}},[e,r,t,o,n,a,i])}import{useCallback as qe}from"react";function Be({activeDropdownIndex:e,setActiveDropdownIndex:r,filteredOptions:t,selectOption:o,onSubmitRef:n,text:a,completedParams:i,isDropdownOpen:l,hasPlaceholder:m,placeholderText:f,suggestions:u,filterBaseRef:h,columns:g,setText:y,setCompletedParams:C,setSuggestions:S}){let P=qe(()=>{let p=t.map((c,x)=>c.is_tappable?x:-1).filter(c=>c!==-1),d=p.filter(c=>c%g===0),s=p.filter(c=>c%g===1);return[...d,...s]},[t,g]);return{handleKeyDown:qe(p=>{let d=P();switch(p.key){case"ArrowDown":{if(p.preventDefault(),d.length===0)return;let s=d.indexOf(e),c=s<d.length-1?s+1:0;r(d[c]);break}case"ArrowUp":{if(p.preventDefault(),d.length===0)return;let s=d.indexOf(e),c=s>0?s-1:d.length-1;r(d[c]);break}case"ArrowRight":{if(e<0)break;if(e%g===0){let s=e+1;s<t.length&&t[s]?.is_tappable&&(p.preventDefault(),r(s))}break}case"ArrowLeft":{if(e<0)break;if(e%g===1){let s=e-1;s>=0&&t[s]?.is_tappable&&(p.preventDefault(),r(s))}break}case"Enter":{if(p.preventDefault(),e>=0&&t[e]?.is_tappable)o(t[e]);else if(n.current){let{rawQuery:s,completedParams:c}=W(a,i),x={query:a.trim(),raw_query:s,completed_params:c};n.current(x)}break}case"Tab":{if(e>=0&&t[e]?.is_tappable)p.preventDefault(),o(t[e]);else if(l){let s=t.find(c=>c.is_tappable);s&&(p.preventDefault(),o(s))}else if(!a&&m){p.preventDefault();let s=u.find(c=>c.type==="placeholder");s?(y(f),h.current=f.length,C(c=>[...c,{id:crypto.randomUUID(),placeholder:"",type:s.type,text:f,kind:null,suggestionType:s.type,suggestionPlaceholder:s.text,options:s.options}]),S(c=>c.filter(x=>x!==s))):(y(f),h.current=f.length)}break}case"Escape":r(-1);break}},[e,g,i,t,h,P,m,l,n,f,o,r,C,S,y,u,a]),getTappableIndices:P}}import{useCallback as Se}from"react";function Qe({completedParams:e,suggestions:r,setCompletedParams:t,setSuggestions:o,setActiveDropdownIndex:n,filterBaseRef:a,pillTappedRef:i}){let l=Se(u=>{let h=r.filter(S=>S.type!=="placeholder");if(u<0||u>=h.length)return;let g=h[u],y=h.filter((S,P)=>P!==u),C=r.filter(S=>S.type==="placeholder");o([...C,g,...y]),i.current=!0,n(-1)},[r,o,n,i]),m=Se(()=>{if(e.length===0)return;let u=e[e.length-1],h={type:u.suggestionType,text:u.suggestionPlaceholder,required:!0,options:u.options};t(g=>g.slice(0,-1)),o(g=>[h,...g]),n(-1)},[e,t,o,n]),f=Se(u=>{let h={type:u.suggestionType,text:u.suggestionPlaceholder,required:!0,options:u.options};return{apply:g=>{g(y=>{let C=0;for(let S of e){let P=y.indexOf(S.text,C);if(P!==-1){if(S.id===u.id){let v=y.slice(0,P),p=y.slice(P+u.text.length),d=(v+p).replace(/ {2,}/g," ");return a.current=Math.min(a.current,d.length),d}C=P+S.text.length}}return y}),t(y=>y.filter(C=>C.id!==u.id)),o(y=>[h,...y]),n(-1),i.current=!0}}},[e,t,o,n,a,i]);return{setActivePill:l,removeLastParam:m,reEditParam:f}}function xe({onSubmit:e,onError:r,optionOverrides:t,maskCompletedText:o,placeholder:n,apiConfig:a,columns:i=2,value:l,completedParams:m,onChange:f,onParamsChange:u}){let h=l!==void 0,g=m!==void 0,[y,C]=ie(""),[S,P]=ie([]),[v,p]=ie([]),[d,s]=ie(-1),c=h?l:y,x=g?m:S,T=U(e);T.current=e;let L=U(f);L.current=f;let $=U(u);$.current=u;let N=U(l);N.current=l;let D=U(m);D.current=m;let O=Y(b=>{if(typeof b=="function")if(h){let k=b(N.current??"");L.current?.(k)}else C(k=>{let q=b(k);return L.current?.(q),q});else h||C(b),L.current?.(b)},[h]),R=Y(b=>{if(typeof b=="function")if(g){let k=b(D.current??[]);$.current?.(k)}else P(k=>{let q=b(k);return $.current?.(q),q});else g||P(b),$.current?.(b)},[g]),j=U(r);j.current=r;let B=U(t);B.current=t;let J=U(o);J.current=o;let w=U(a);w.current=a;let I=U(c);I.current=c;let z=U(v);z.current=v;let _=U(0),te=U(!1),ve=U(!1),ce=St(),{doFetch:le,isLoading:Ae,error:He,isReady:Ve,lastRawQueryRef:ue}=je({textRef:I,suggestionsRef:z,filterBaseRef:_,maskCompletedTextRef:J,apiConfigRef:w,optionOverridesRef:B,onErrorRef:j,setCompletedParams:R,setSuggestions:p,setActiveDropdownIndex:s});ze({text:c,completedParams:x,doFetch:le,filterBaseRef:_,skipNextFetchRef:ve,suggestionsRef:z,lastRawQueryRef:ue});let Xe=se(()=>Le(c,x),[c,x]);_.current=Math.min(_.current,c.length);let pe=c.slice(_.current),me=se(()=>v.filter(k=>k.type==="placeholder").map(k=>k.text).join(" ")||n||"",[v,n]),oe=se(()=>v.filter(b=>b.type!=="placeholder"),[v]),A=oe[0],Ce=A?t?.[A.type]:void 0,ke=A?Ce?Ce(pe.trim()):A.options??[]:[],de=se(()=>ae(ke,pe),[ke,pe]),we=me.length>0,fe=!Ae&&de.length>0&&(!!c||te.current||!we),Oe=Y(b=>{if(!A)return;let k={id:crypto.randomUUID(),placeholder:"",type:A.type,text:b.text,kind:b.kind,suggestionType:A.type,suggestionPlaceholder:A.text,options:A.options,metadata:b.metadata},q=_.current,E=I.current.slice(0,q);if(E.length>0&&!E.endsWith(" ")){let M=E.split(/\s+/).pop()??"";M&&b.text.toLowerCase().startsWith(M.toLowerCase())&&(E=E.slice(0,E.length-M.length))}let ge=E.length>0&&E[E.length-1]!==" ",H=E+(ge?" ":"")+b.text+" ";O(H),_.current=H.length,R(M=>[...M,k]),p(M=>M.filter(Z=>Z!==A)),te.current=!1,s(-1),oe.length-1>0&&(ve.current=!0)},[A,oe,O,R]),We=Y(b=>{let k=b.target.value,E=k.length>0&&!b.nativeEvent?.isComposing&&k[0]!==k[0].toUpperCase()?k[0].toUpperCase()+k.slice(1):k;O(E),te.current=!1,s(-1);let{valid:ge,invalid:H}=Ne(E,x);if(H.length>0){R(()=>ge);for(let V of H)p(M=>[{type:V.suggestionType,text:V.suggestionPlaceholder,required:!0,options:V.options},...M])}if(A&&H.length===0){let V=E.slice(_.current),M=ee(A.options,V);M&&(R(Z=>[...Z,{id:crypto.randomUUID(),placeholder:"",type:A.type,text:M.text,kind:M.kind,suggestionType:A.type,suggestionPlaceholder:A.text,options:A.options,metadata:M.metadata}]),p(Z=>Z.filter(et=>et!==A)))}},[x,A,O,R]),{handleKeyDown:Ge}=Be({activeDropdownIndex:d,setActiveDropdownIndex:s,filteredOptions:de,selectOption:Oe,onSubmitRef:T,text:c,completedParams:x,isDropdownOpen:fe,hasPlaceholder:we,placeholderText:me,suggestions:v,filterBaseRef:_,columns:i,setText:O,setCompletedParams:R,setSuggestions:p}),ne=Qe({completedParams:x,suggestions:v,setCompletedParams:R,setSuggestions:p,setActiveDropdownIndex:s,filterBaseRef:_,pillTappedRef:te}),Ye=Y(b=>{ne.reEditParam(b).apply(O)},[ne,O]),Je=Y(()=>{O(""),R(()=>[]),p([]),s(-1),_.current=0,ue.current="",le("",[])},[le,O,R,ue]),Ze=d>=0?`${ce}-option-${d}`:void 0;return{completedParams:x,suggestionPills:oe,setActivePill:ne.setActivePill,removeLastParam:ne.removeLastParam,reEditParam:Ye,segments:Xe,suggestions:v,activeIndex:d,isReady:Ve,isLoading:Ae,error:He,inputProps:{value:c,placeholder:me||void 0,onChange:We,onKeyDown:Ge,role:"combobox","aria-expanded":fe,"aria-activedescendant":Ze,"aria-autocomplete":"list","aria-controls":ce},reset:Je,dropdownProps:{suggestions:A?[{...A,options:de}]:[],activeIndex:d,onSelect:Oe,onHighlight:s,isOpen:fe,id:ce}}}import{jsx as K,jsxs as Q}from"react/jsx-runtime";var kt=xt(function({onSubmit:r,onError:t,optionOverrides:o,maskCompletedText:n,placeholder:a,className:i,apiConfig:l,columns:m,value:f,completedParams:u,onChange:h,onParamsChange:g},y){let C=Pe(null),[S,P]=Ct(!1),v=Pe(()=>{}),p=Pe(void 0);vt(()=>(C.current?.focus(),()=>clearTimeout(p.current)),[]);let{completedParams:d,suggestionPills:s,setActivePill:c,segments:x,inputProps:T,dropdownProps:L,reset:$}=xe({onSubmit:w=>v.current(w),onError:t,optionOverrides:o,maskCompletedText:n,placeholder:a,apiConfig:l,columns:m,value:f,completedParams:u,onChange:h,onParamsChange:g});At(y,()=>({focus:()=>C.current?.focus(),reset:$}),[$]);let N=()=>{C.current?.focus()},D=!!T.value||d.length>0,O=Pt(()=>{if(!D)return;let{rawQuery:w,completedParams:I}=W(T.value,d);r({query:T.value.trim(),raw_query:w,completed_params:I}),$(),P(!0),clearTimeout(p.current),p.current=setTimeout(()=>P(!1),3e3)},[D,T.value,d,r,$]);v.current=O;let{onChange:R,placeholder:j,...B}=T,J=!T.value;return Q("div",{className:`${F.container} ${i??""}`,children:[K("div",{className:`${F.checkmark} ${S?F.checkmarkVisible:""}`,children:Q("svg",{width:"72",height:"72",viewBox:"0 0 24 24",fill:"none",role:"img","aria-label":"Success",children:[K("circle",{cx:"12",cy:"12",r:"12",fill:"#34C759"}),K("path",{d:"M7 12.5l3.5 3.5L17 9",stroke:"#000",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:F.checkmarkPath})]})}),K(be,{...L}),Q("div",{className:F.inputWrapper,onClick:N,children:[Q("div",{className:F.editorArea,children:[Q("div",{className:F.sizerContent,"aria-hidden":"true",children:[J&&j?Q("span",{className:F.placeholderText,children:[j," "]}):Q("span",{className:F.sizerText,children:[x.map((w,I)=>K("span",{children:w.value},`${I}-${w.type}`)),x.length===0&&"\xA0"]})," ",K(Ue,{pills:s,activePillIndex:0,onSelectPill:c})]}),K("textarea",{ref:C,className:F.textarea,rows:1,onChange:R,...B})]}),K("button",{type:"button",className:F.submitButton,disabled:!D,onClick:w=>{w.stopPropagation(),O()},"aria-label":"Submit",children:K("svg",{width:"18",height:"18",viewBox:"0 0 18 18",fill:"none",role:"img","aria-label":"Submit",children:K("path",{d:"M9 14V4M9 4L4 9M9 4L14 9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})});export{kt as AIAutocomplete,be as AIAutocompleteDropdown,xe as useAIAutocomplete};
2
2
  //# sourceMappingURL=index.mjs.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magicx-eng/ai-autocomplete-react",
3
- "version": "0.1.4",
3
+ "version": "0.1.5",
4
4
  "description": "AI Autocomplete React SDK — guided autocomplete with pill-based input and dropdown suggestions",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",