@magicx-eng/ai-autocomplete-react 0.1.33 → 0.1.35

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.mjs CHANGED
@@ -151,7 +151,7 @@ import{forwardRef as St,useCallback as It,useEffect as Te,useImperativeHandle as
151
151
  left: 0;
152
152
  right: 0;
153
153
  top: 100%;
154
- max-width: 100cqi;
154
+ max-width: 516px;
155
155
  margin-top: 6px;
156
156
  display: flex;
157
157
  flex-direction: column;
@@ -689,5 +689,5 @@ import{forwardRef as St,useCallback as It,useEffect as Te,useImperativeHandle as
689
689
  animation-duration: 0s !important;
690
690
  transition-duration: 0s !important;
691
691
  }
692
- `,document.head.appendChild(o)}import{useCallback as A,useEffect as pe,useRef as D,useState as wt}from"react";function G(o,e,t){let i=o.slice(e);if(t||e===0||o[e-1]===" ")return i;let r=i.indexOf(" ");return r===-1?"":i.slice(r+1)}function Re(o,e){let t=o.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let i=t.split(" "),r=e.toLowerCase();for(let n=0;n<i.length;n++){let a=i.slice(n).join(" ");if(r.startsWith(a.toLowerCase())){let p=t.length-a.length;return o.length-p}}return 0}function te(o,e){if(!o)return[];let t=e.trimStart();if(!t)return o;let i=t.toLowerCase();return o.filter(r=>!r.is_tappable||r.text.toLowerCase().includes(i))}function _e(o,e){if(!o)return null;let t=e.trim();if(!t)return null;let i=t.toLowerCase();return o.find(r=>r.is_tappable&&r.text.toLowerCase()===i)??null}var N=class{constructor(e,t="auto"){this.container=e;this.mode=t;this.mediaQuery=null;this.onSystemChange=e=>{this.container.dataset.mode=e.matches?"dark":"light"};this.apply()}setMode(e){this.detachListener(),this.mode=e,this.apply()}destroy(){this.detachListener()}apply(){this.mode==="auto"?(this.mediaQuery??(this.mediaQuery=window.matchMedia("(prefers-color-scheme: dark)")),this.mediaQuery.addEventListener("change",this.onSystemChange),this.container.dataset.mode=this.mediaQuery.matches?"dark":"light"):this.container.dataset.mode=this.mode}detachListener(){this.mediaQuery?.removeEventListener("change",this.onSystemChange)}};function Me(o,e){let t=[],i=0;for(let n of e){let a=o.indexOf(n.text,i);a!==-1&&(a>i&&t.push({type:"text",value:o.slice(i,a)}),t.push({type:"completed",value:n.text,param:n}),i=a+n.text.length)}let r=o.slice(i);return r&&t.push({type:"text",value:r}),t}function He(o,e){let t=[],i=[],r=0;for(let n of e){let a=o.indexOf(n.text,r);a===-1?i.push(n):(t.push(n),r=a+n.text.length)}return{valid:t,invalid:i}}var oe=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;this.inFlightRefresh=null;e.accessToken&&(this.current=e.accessToken)}async getToken(e=!1){if(!e&&this.current&&!this.isExpired())return this.current;if(!e&&this.inFlightRefresh)return this.inFlightRefresh;this.inFlightRefresh=this.refresh();try{return await this.inFlightRefresh}finally{this.inFlightRefresh=null}}async refresh(){let e=await this.config.getAccessToken();return this.current=e.accessToken,this.expiresAt=e.expiresAt??null,this.current}isExpired(){return this.expiresAt==null?!1:Date.now()>=this.expiresAt-3e4}};var nt="0.1.33",Be=!1;function rt(){return crypto.randomUUID()}function st(o,e){return{placeholder:o.placeholder,type:o.type,...e&&{text:o.text},kind:o.kind}}function Ne(o){return o?.type==="accessToken"}function at(o){if(!(!o||Ne(o)))return o}var ze=new WeakMap;function lt(o){let e=ze.get(o.getAccessToken);return e||(e=new oe(o),ze.set(o.getAccessToken,e)),e}function dt(o,e,t,i){let r=e.find(a=>a.type==="contact"&&a.metadata?.contact_account_count)?.metadata?.contact_account_count,n=typeof r=="number"?r:void 0;return{data:{raw_query:o,completed_params:e.map(a=>st(a,t)),...n!=null&&{contact_account_count:n}},meta:{request_id:rt(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:nt,session_id:i}}}function pt(o){return{"Content-Type":"application/json",...o?.appIdentifier&&{"X-App-Identifier":o.appIdentifier},...o?.headers}}async function Fe(o,e,t,i,r){return fetch(o,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:r})}async function Ke(o,e,t){let i=t.apiConfig,r=!t.maskCompletedText,n=dt(o,e,r,t.sessionId),a=pt(i),p=i?.endpoint??"https://api.ai-autocomplete.com/api/suggest",s=JSON.stringify(n);if(Ne(i)){let u=lt(i),f=await u.getToken(),m=await Fe(p,a,f,s,t.signal);if(m.status===401){let w=await u.getToken(!0);m=await Fe(p,a,w,s,t.signal)}if(!m.ok)throw new Error(`API error: ${m.status} ${m.statusText}`);return m.json()}let l=at(i),d=l?.apiKey??"";if(!d&&!Be&&(Be=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),d){let u=l?.authScheme??"Bearer";a.Authorization=u==="Basic"?`Basic ${btoa(d)}`:`Bearer ${d}`}let c=await fetch(p,{method:"POST",headers:a,body:s,signal:t.signal});if(!c.ok)throw new Error(`API error: ${c.status} ${c.statusText}`);return c.json()}function L(o,e){let t=o,i={},r=[];for(let n of e){let a=(i[n.type]??0)+1;i[n.type]=a;let s=`{{${n.type.toUpperCase().replace(/\s+/g,"_")}_${a}}}`,l=t.indexOf(n.text);l!==-1&&(t=t.slice(0,l)+s+t.slice(l+n.text.length)),r.push({...n,placeholder:s})}return{rawQuery:t,completedParams:r}}function $e(o,e){return e?o.map(t=>{let i=e[t.type];if(!i)return t;let r=i("");if(r.length===0)return t;let n=new Set(r.map(p=>p.text)),a=(t.options??[]).filter(p=>!n.has(p.text));return{...t,options:[...r,...a]}}):o}var ct=100,ut=300,mt=2,ie=class{constructor(e,t,i,r,n,a){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=r;this.getOnError=n;this.getSessionId=a;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null}start(){this.doFetch("",[]);let e=this.store.get().text,t=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(i=>{(i.text!==e||i.completedParams!==t)&&(e=i.text,t=i.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let i=new AbortController;this.abortController=i;let r=++this.fetchVersion,n=this.store.get(),a=n.text.length;n.suggestions.some(s=>s.type!=="placeholder")||this.store.set({isLoading:!0}),this.store.set({error:null});try{let s=await Ke(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig()});if(r!==this.fetchVersion)return;let l=$e(s.data.suggestions??[],this.getOptionOverrides()),d=s.data.input??[],c=d[d.length-1],u=this.store.get().text,f,m;if(c?.state==="in_progress"){m=!0;let C=u.toLowerCase().lastIndexOf(c.text.toLowerCase());f=C!==-1?C:a}else m=!1,f=a;let x=l.filter(C=>C.type!=="placeholder")[0],b=null;if(x){let C=G(u,f,m),T=_e(x.options,C);T&&(b={id:crypto.randomUUID(),placeholder:"",type:x.type,text:T.text,kind:T.kind,suggestionType:x.type,suggestionPlaceholder:x.text,options:x.options??[],metadata:T.metadata},l=l.filter(M=>M!==x))}this.store.set(C=>({suggestions:l,isLoading:!1,isReady:s.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:f,filterInProgress:m,...b?{completedParams:[...C.completedParams,b]}:{}}))}catch(s){if(r===this.fetchVersion){let l=s instanceof Error?s:new Error(String(s));this.store.set({error:l,isLoading:!1}),this.getOnError()?.(l)}}}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}let t=i=>{let r=this.store.get();if(!r.text&&r.completedParams.length===0)return this.doFetch("",[]),!0;let n=G(r.text,r.filterBase,r.filterInProgress),p=r.suggestions.filter(x=>x.type!=="placeholder")[0],l=(p?te(p.options,n):[]).filter(x=>x.is_tappable),d=p?_e(p.options,n)!==null:!1,c=n.trim().length>0;if(l.length>0&&!d&&c)return!1;if(r.completedParams.length===0&&r.text.length>0){let x=r.suggestions.filter(b=>b.type==="placeholder").map(b=>b.text).join(" ");if(x.length>0&&x.toLowerCase().startsWith(r.text.toLowerCase()))return!1}let{rawQuery:u,completedParams:f}=L(r.text,r.completedParams),m=u.length<r.lastRawQuery.length,w=Math.abs(u.length-r.lastRawQuery.length);return m||w>=i?(this.doFetch(u,f),!0):!1};this.debounceTimer=setTimeout(()=>{t(mt)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},ct),this.slowDebounceTimer=setTimeout(()=>t(1),ut)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var ne=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:r}=this.ctx,n=this.getEffectiveColumns(),a=r(),p=this.getTappableIndices(n);switch(e.key){case"ArrowDown":{let s=e.target;if(!(s.selectionStart!=null&&s.selectionStart===s.value.length)&&t.activeDropdownIndex<0)break;if(e.preventDefault(),!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:p[0]??0});break}if(p.length===0)return;let d=p.indexOf(t.activeDropdownIndex),c=d<p.length-1?d+1:0;this.store.set({activeDropdownIndex:p[c]});break}case"ArrowUp":{if(p.length===0||t.activeDropdownIndex<0)break;if(e.preventDefault(),t.activeDropdownIndex<n){this.store.set({activeDropdownIndex:-1});break}let s=p.indexOf(t.activeDropdownIndex),l=s>0?s-1:p.length-1;this.store.set({activeDropdownIndex:p[l]});break}case"ArrowRight":{if(t.activeDropdownIndex<0){let l=e.target;l.selectionStart!=null&&l.selectionStart===l.value.length&&t.actionableSuggestions.length>1&&(e.preventDefault(),this.pillsSetActivePill(1));break}if(t.activeDropdownIndex%n<n-1){let l=t.activeDropdownIndex+1;l<t.filteredOptions.length&&t.filteredOptions[l]?.is_tappable&&(e.preventDefault(),this.store.set({activeDropdownIndex:l}))}break}case"ArrowLeft":{if(t.activeDropdownIndex<0)break;if(t.activeDropdownIndex%n>0){let s=t.activeDropdownIndex-1;s>=0&&t.filteredOptions[s]?.is_tappable&&(e.preventDefault(),this.store.set({activeDropdownIndex:s}))}break}case"Enter":{if(e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable)this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i);else if(a){let{rawQuery:s,completedParams:l}=L(t.text,t.completedParams);a({query:t.text.trim(),raw_query:s,completed_params:l})}break}case"Tab":{let s=!t.text&&!!t.placeholderText,l=t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable;if(s&&!l){e.preventDefault();let d=t.suggestions.find(c=>c.type==="placeholder");d?this.store.set(c=>({text:t.placeholderText,filterBase:t.placeholderText.length,completedParams:[...c.completedParams,{id:crypto.randomUUID(),placeholder:"",type:d.type,text:t.placeholderText,kind:null,suggestionType:d.type,suggestionPlaceholder:d.text,options:d.options??[]}],suggestions:c.suggestions.filter(u=>u!==d)})):this.store.set({text:t.placeholderText,filterBase:t.placeholderText.length})}else if(l)e.preventDefault(),this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i);else if(t.isDropdownOpen){let d=t.filteredOptions.findIndex(c=>c.is_tappable);d>=0&&(e.preventDefault(),this.clickOrSelect(d,t.filteredOptions,i))}break}case"Escape":this.store.set({activeDropdownIndex:-1});break}}getTappableIndices(e){let i=this.store.get().filteredOptions.map((n,a)=>n.is_tappable?a:-1).filter(n=>n!==-1),r=Array.from({length:e},()=>[]);for(let n of i)r[n%e].push(n);return r.flat()}getEffectiveColumns(){let t=document.getElementById(`${this.ctx.listboxId}-option-0`)?.parentElement;if(!t)return this.ctx.columns;let i=getComputedStyle(t).gridTemplateColumns.split(" ").filter(Boolean).length;return i>0?i:this.ctx.columns}clickOrSelect(e,t,i){let r=document.getElementById(`${i}-option-${e}`);r?r.click():this.ctx.selectOption(t[e])}pillsSetActivePill(e){let t=this.store.get(),i=t.suggestions.filter(p=>p.type!=="placeholder");if(e<0||e>=i.length)return;let r=i[e],n=i.filter((p,s)=>s!==e),a=t.suggestions.filter(p=>p.type==="placeholder");this.store.set({suggestions:[...a,r,...n],pillTapped:!0,activeDropdownIndex:-1})}};var re=class{constructor(e){this.store=e}setActivePill(e){let t=this.store.get(),i=t.suggestions.filter(p=>p.type!=="placeholder");if(e<0||e>=i.length)return;let r=i[e],n=i.filter((p,s)=>s!==e),a=t.suggestions.filter(p=>p.type==="placeholder");this.store.set({suggestions:[...a,r,...n],pillTapped:!0,activeDropdownIndex:-1})}removeLastParam(){let e=this.store.get();if(e.completedParams.length===0)return;let t=e.completedParams[e.completedParams.length-1],i={type:t.suggestionType,text:t.suggestionPlaceholder,required:!0,options:t.options};this.store.set(r=>({completedParams:r.completedParams.slice(0,-1),suggestions:[i,...r.suggestions],activeDropdownIndex:-1}))}};function gt(o){return o===0?.4:o===1?.3:.15}function se(o,e,t,i,r=!1){let n=o.querySelector(".magicx-aia-pill-list");n||(n=document.createElement("span"),n.className="magicx-aia-pill-list",o.appendChild(n));let a=new Map;for(let s of n.querySelectorAll(".magicx-aia-pill"))a.set(s.dataset.pillKey??"",s);let p=new Set;for(let s=0;s<e.length;s++){let l=e[s],d=`${l.type}-${l.text}`;p.add(d);let c=a.get(d);c||(c=document.createElement("button"),c.type="button",c.dataset.pillKey=d,c.setAttribute("data-aia-pill",""),c.textContent=l.text),c.className=`magicx-aia-pill${r?" magicx-aia-pill--rounded":""}${s===t?" magicx-aia-pill--active":""}`,c.style.opacity=String(gt(s)),c.onclick=()=>i(s),n.children[s]!==c&&n.insertBefore(c,n.children[s]??null)}for(let[s,l]of a)p.has(s)||l.remove()}function ae(o){let e=document.createElement("div");return e.id=o,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",t=>t.preventDefault()),e}function le(o,e){let{filteredOptions:t,activeIndex:i,isOpen:r,pills:n,showPills:a,onSelect:p,onHighlight:s,onPillClick:l}=e,d=a&&n.length>0;r&&t.length>0||r&&d?o.classList.add("magicx-aia-dropdown--visible"):o.classList.remove("magicx-aia-dropdown--visible");let f=o.querySelector(".magicx-aia-pill-bar");d?(f||(f=document.createElement("div"),f.className="magicx-aia-pill-bar",f.setAttribute("data-aia-pillbar",""),o.insertBefore(f,o.firstChild)),se(f,n,0,l,!0)):f&&f.remove();let m=o.querySelector(".magicx-aia-grid");t.length>0?(m||(m=document.createElement("div"),m.className="magicx-aia-grid",o.appendChild(m)),ft(m,t,i,p,s,e.listboxId)):m&&(m.innerHTML="")}function ft(o,e,t,i,r,n){let a=e.map(l=>l.text).join("\0"),p=o.dataset.optionsKey??"",s=a!==p;if(o.dataset.optionsKey=a,s){let l=document.createDocumentFragment();for(let d=0;d<e.length;d++){let c=e[d],u=ht(c,d,t,i,r,n);l.appendChild(u)}o.innerHTML="",o.appendChild(l)}else{let l=o.querySelectorAll(".magicx-aia-option");for(let d=0;d<l.length;d++){let c=l[d],u=d===t;c.setAttribute("aria-selected",String(u)),u?c.classList.add("magicx-aia-option--highlighted"):c.classList.remove("magicx-aia-option--highlighted")}}}function ht(o,e,t,i,r,n){let a=document.createElement("div");a.id=`${n}-option-${e}`,a.setAttribute("role","option"),a.setAttribute("data-aia-option",""),a.setAttribute("aria-selected",String(e===t)),a.tabIndex=o.is_tappable?0:-1;let p=["magicx-aia-option"];e===t&&p.push("magicx-aia-option--highlighted"),o.is_tappable?p.push("magicx-aia-option--tappable"):p.push("magicx-aia-option--non-tappable"),a.className=p.join(" ");let s=document.createElement("div");s.className="magicx-aia-streaks",a.appendChild(s);let l=document.createElement("div");l.className="magicx-aia-streaks-vert",a.appendChild(l);let d=document.createElement("span");if(d.className="magicx-aia-option-content",d.textContent=o.icon?`${o.icon} ${o.text}`:o.text,o.tag){let c=document.createElement("span");c.className="magicx-aia-option-tag",c.textContent=o.tag,d.appendChild(c)}return a.appendChild(d),o.is_tappable&&(a.addEventListener("click",()=>{a.classList.add("magicx-aia-option--pressed"),i(o),setTimeout(()=>a.classList.remove("magicx-aia-option--pressed"),400)}),a.addEventListener("mouseenter",()=>r(e))),a}function qe(o,e){let t=ae(e.listboxId);return o.appendChild(t),{dropdown:t}}function Ce(o,e,t){le(o.dropdown,{suggestions:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,onSelect:t.selectOption,onHighlight:i=>t.store.set({activeDropdownIndex:i}),onPillClick:t.setActivePill})}function Ve(o,e,t,i,r){let n=o.querySelector(".magicx-aia-sizer-text"),a=o.querySelector(".magicx-aia-placeholder");if(i&&r){n&&(n.style.display="none"),a||(a=document.createElement("span"),a.className="magicx-aia-placeholder",o.insertBefore(a,o.firstChild)),a.style.display="",a.textContent=`${r} `,o.dataset.segmentKey="";return}a&&(a.style.display="none"),n||(n=document.createElement("span"),n.className="magicx-aia-sizer-text",o.insertBefore(n,o.firstChild)),n.style.display="",n.className=`magicx-aia-sizer-text${t?" magicx-aia-sizer-text--visible":""}`;let p=e.map(d=>`${d.type}:${d.value}`).join("\0"),s=o.dataset.segmentKey??"",l=o.dataset.newParamId??"";if(!(p===s&&(t??"")===l)){o.dataset.segmentKey=p,o.dataset.newParamId=t??"",n.innerHTML="";for(let d of e){let c=document.createElement("span");d.type==="completed"&&(d.param.id===t?c.className="magicx-aia-shimmer-revealed magicx-aia-shimmer-sweep":c.className="magicx-aia-segment magicx-aia-segment--completed"),c.textContent=d.value,n.appendChild(c)}e.length===0&&(n.textContent="\xA0")}}var xt='<svg width="18" height="18" viewBox="0 0 18 18" fill="none" role="img" aria-label="Submit"><path d="M9 14V4M9 4L4 9M9 4L14 9" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';function Ue(o,e){let{listboxId:t}=e,i=ae(t);o.appendChild(i);let r=document.createElement("div");r.className="magicx-aia-input-wrapper",o.appendChild(r);let n=document.createElement("div");n.className="magicx-aia-editor",n.setAttribute("data-aia-editor",""),r.appendChild(n);let a=document.createElement("div");a.className="magicx-aia-sizer",a.setAttribute("aria-hidden","true"),n.appendChild(a);let p=document.createElement("span");a.appendChild(document.createTextNode(" ")),a.appendChild(p);let s=document.createElement("textarea");s.className="magicx-aia-textarea",s.rows=1,s.setAttribute("role","combobox"),s.setAttribute("aria-autocomplete","list"),s.setAttribute("aria-controls",t),s.setAttribute("data-aia-textarea",""),n.appendChild(s);let l=null,d=null;return e.submitButton===void 0?(l=document.createElement("button"),l.type="button",l.className="magicx-aia-submit",l.setAttribute("aria-label","Submit"),l.setAttribute("data-aia-submit",""),l.innerHTML=xt,r.appendChild(l),d=l):e.submitButton!==null&&(d=e.submitButton,d.hasAttribute("data-aia-submit")||d.setAttribute("data-aia-submit",""),r.appendChild(d)),r.addEventListener("click",()=>s.focus()),s.addEventListener("input",()=>{let c=s.value,f=c.length>0&&c[0]!==c[0].toUpperCase()?c[0].toUpperCase()+c.slice(1):c;e.handleChange(f)}),s.addEventListener("keydown",c=>e.handleKeyDown(c)),s.addEventListener("focus",()=>e.store.set({isFocused:!0})),s.addEventListener("blur",()=>e.store.set({isFocused:!1})),d&&d.addEventListener("click",c=>{let u=e.store.get();if(!(!!u.text||u.completedParams.length>0)||!e.onSubmit)return;c.stopPropagation();let{rawQuery:m,completedParams:w}=L(u.text,u.completedParams);e.onSubmit({query:u.text.trim(),raw_query:m,completed_params:w})}),e.autoFocus!==!1&&s.focus(),{textarea:s,dropdown:i,sizer:a,submitButton:l,inlinePillContainer:p}}function Ae(o,e,t){let{textarea:i,dropdown:r,sizer:n,submitButton:a,inlinePillContainer:p}=o,{pillPlacement:s,setActivePill:l,selectOption:d,store:c}=t;i.value!==e.text&&(i.value=e.text),e.placeholderText?i.placeholder=e.placeholderText:i.removeAttribute("placeholder"),i.setAttribute("aria-expanded",String(e.isDropdownOpen));let u=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(u?i.setAttribute("aria-activedescendant",u):i.removeAttribute("aria-activedescendant"),e.newParamId?i.classList.add("magicx-aia-textarea--hidden"):i.classList.remove("magicx-aia-textarea--hidden"),a){let f=!!e.text||e.completedParams.length>0;a.disabled=!f}Ve(n,e.segments,e.newParamId,!e.text,e.placeholderText),s==="inline"?se(p,e.actionableSuggestions,0,l):p.innerHTML="",le(r,{suggestions:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:s==="dropdown",onSelect:d,onHighlight:f=>c.set({activeDropdownIndex:f}),onPillClick:l})}function Qe(o){let e=o,t=new Set;return{get:()=>e,set:i=>{let r=typeof i=="function"?i(e):i,n={...e,...r},a=e;e=n;for(let p of t)p(n,a)},subscribe:i=>(t.add(i),()=>{t.delete(i)})}}var Pe=!1;function Ge(){if(Pe||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){Pe=!0;return}Pe=!0;let o=document.createElement("style");o.setAttribute("data-magicx-aia",""),o.textContent=bt,document.head.appendChild(o)}var bt="";var vt=0;function yt(){return`:ac-${++vt}:`}function We(){return{text:"",completedParams:[],suggestions:[],activeDropdownIndex:-1,newParamId:null,isLoading:!1,isReady:!1,error:null,segments:[],actionableSuggestions:[],filteredOptions:[],placeholderText:"",isDropdownOpen:!1,filterBase:0,filterInProgress:!1,pillTapped:!1,skipNextFetch:!1,lastRawQuery:"",isFocused:!1}}var de=class{constructor(e,t={}){this.store=Qe(We());this._listboxId=yt();this.modeController=null;this.unsubscribers=[];this.derivedInProgress=!1;this.domRefs=null;this.dropdownRefs=null;this.externalListeners=new Set;this.sessionId=crypto.randomUUID();this.container=e,this.opts=t,this.renderMode=t.renderMode??"full",t.value!==void 0&&this.store.set({text:t.value}),t.completedParams!==void 0&&this.store.set({completedParams:t.completedParams}),this.pillsController=new re(this.store),this.fetchController=new ie(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.opts.onError,()=>this.sessionId),this.keyboardController=new ne(this.store,{columns:t.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.opts.onSubmit,selectOption:i=>this.selectOption(i)}),this.unsubscribers.push(this.store.subscribe((i,r)=>{this.recomputeDerived(i,r)})),this.unsubscribers.push(this.store.subscribe((i,r)=>{i.text!==r.text&&this.opts.onChange?.(i.text),i.completedParams!==r.completedParams&&this.opts.onParamsChange?.(i.completedParams),i.isFocused!==r.isFocused&&(i.isFocused?this.opts.onFocus?.():this.opts.onBlur?.()),this.opts.onStateChange?.(i)})),this.renderMode!=="headless"&&(Ge(),this.setupContainer()),this.renderMode==="full"?this.buildAndRenderFull():this.renderMode==="dropdown"&&this.buildAndRenderDropdown(),this.fetchController.start()}focus(){this.domRefs?.textarea.focus()}blur(){this.domRefs?.textarea.blur()}reset(){this.store.set({...We(),skipNextFetch:!0}),this.sessionId=crypto.randomUUID(),this.fetchController.doFetch("",[])}destroy(){this.fetchController.dispose(),this.modeController?.destroy(),this.newParamTimer&&clearTimeout(this.newParamTimer),this.suggestionRemovalTimer&&clearTimeout(this.suggestionRemovalTimer),this.externalListeners.clear();for(let e of this.unsubscribers)e();this.unsubscribers=[],this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}setValue(e){this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e)}removeLastParam(){this.pillsController.removeLastParam()}clearNewParamId(){this.store.set({newParamId:null})}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}handleTextChange(e){this.handleChange(e)}handleKeyDown(e){this.keyboardController.handleKeyDown(e)}setFocused(e){this.store.get().isFocused!==e&&this.store.set({isFocused:e})}subscribe(e){return this.externalListeners.add(e),()=>{this.externalListeners.delete(e)}}getState(){return this.store.get()}get listboxId(){return this._listboxId}get isReady(){return this.store.get().isReady}on(e,t){switch(e){case"submit":return this.opts.onSubmit=t,()=>{this.opts.onSubmit=void 0};case"error":return this.opts.onError=t,()=>{this.opts.onError=void 0};case"change":return this.opts.onChange=t,()=>{this.opts.onChange=void 0};case"paramsChange":return this.opts.onParamsChange=t,()=>{this.opts.onParamsChange=void 0};case"stateChange":return this.opts.onStateChange=t,()=>{this.opts.onStateChange=void 0};case"focus":return this.opts.onFocus=t,()=>{this.opts.onFocus=void 0};case"blur":return this.opts.onBlur=t,()=>{this.opts.onBlur=void 0};default:return()=>{}}}update(e){Object.assign(this.opts,e),e.mode!==void 0&&this.modeController?.setMode(e.mode),e.optionsPosition!==void 0&&(this.container.dataset.optionsPosition=e.optionsPosition),e.animations!==void 0&&(this.container.dataset.animations=e.animations?"on":"off"),e.pillPlacement!==void 0&&(this.container.dataset.pillPlacement=e.pillPlacement,this.store.set({})),(e.dropdownTrigger!==void 0||e.closeDropdownOnBlur!==void 0)&&this.store.set({}),e.value!==void 0&&this.store.set({text:e.value}),e.completedParams!==void 0&&this.store.set({completedParams:e.completedParams})}selectOption(e){let t=this.store.get(),i=t.actionableSuggestions[0];if(!i)return;let r=t.filterBase,n=t.text.slice(0,r),a=n.length===0&&t.text.length===0,p=n.length===0&&t.text.length>0&&t.placeholderText.length>0&&t.placeholderText.toLowerCase().startsWith(t.text.toLowerCase());(a||p)&&t.placeholderText&&(n=`${t.placeholderText} `);let s=Re(n,e.text);s>0&&(n=n.slice(0,n.length-s));let l=n.length>0&&n[n.length-1]!==" ",d=`${n}${l?" ":""}${e.text} `,c=(a||p)&&d.length>0?d[0].toUpperCase()+d.slice(1):d,u=c.toLowerCase().lastIndexOf(e.text.toLowerCase()),f=u>=0?c.slice(u,u+e.text.length):e.text,m={id:crypto.randomUUID(),placeholder:"",type:i.type,text:f,kind:e.kind,suggestionType:i.type,suggestionPlaceholder:i.text,options:i.options??[],metadata:e.metadata},w=t.actionableSuggestions.length-1;this.store.set(x=>({text:c,filterBase:c.length,completedParams:[...x.completedParams,m],newParamId:m.id,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:w>0})),this.suggestionRemovalTimer=window.setTimeout(()=>{this.store.set(x=>({suggestions:x.suggestions.filter(b=>b!==i)}))},400)}recomputeDerived(e,t){if(this.derivedInProgress)return;this.derivedInProgress=!0;let i=Me(e.text,e.completedParams),r=e.suggestions.filter(b=>b.type!=="placeholder"),n=r[0],a=n?this.opts.optionOverrides?.[n.type]:void 0,p=Math.min(e.filterBase,e.text.length),l=e.lastRawQuery!==""||p>0?G(e.text,p,e.filterInProgress):"",d=n?a?a(l.trim()):n.options??[]:[],c=te(d,l),u=e.suggestions.filter(b=>b.type==="placeholder").map(b=>b.text).join(" "),f=this.opts.dropdownTrigger??"auto",m=this.opts.closeDropdownOnBlur??!0,w=!1;if(f==="auto"){let b=m?e.isFocused:!0;w=!e.isLoading&&c.length>0&&b}else f==="manual"&&(w=!e.isLoading&&c.length>0&&e.pillTapped);this.store.set({segments:i,actionableSuggestions:r,filteredOptions:c,placeholderText:u,isDropdownOpen:w}),this.derivedInProgress=!1;let x=this.store.get();for(let b of this.externalListeners)b(x)}setupContainer(){this.container.classList.add("magicx-aia"),this.container.dataset.pillPlacement=this.renderMode==="dropdown"?"dropdown":this.opts.pillPlacement??"inline",this.container.dataset.optionsPosition=this.opts.optionsPosition??"below",this.container.dataset.animations=this.opts.animations??!0?"on":"off",this.modeController=new N(this.container,this.opts.mode??"auto")}buildAndRenderFull(){let e=this,t={store:this.store,listboxId:this.listboxId,get pillPlacement(){return e.opts.pillPlacement??"inline"},get onSubmit(){return e.opts.onSubmit},submitButton:this.opts.submitButton,autoFocus:this.opts.autoFocus??!0,selectOption:i=>this.selectOption(i),setActivePill:i=>this.pillsController.setActivePill(i),handleKeyDown:i=>this.keyboardController.handleKeyDown(i),handleChange:i=>this.handleChange(i)};this.domRefs=Ue(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&Ae(this.domRefs,this.store.get(),t)}),Ae(this.domRefs,this.store.get(),t),this.subscribeNewParamTimer()}buildAndRenderDropdown(){let e={store:this.store,listboxId:this.listboxId,selectOption:t=>this.selectOption(t),setActivePill:t=>this.pillsController.setActivePill(t)};this.dropdownRefs=qe(this.container,e),this.subscribeBatchedRender(()=>{this.dropdownRefs&&Ce(this.dropdownRefs,this.store.get(),e)}),Ce(this.dropdownRefs,this.store.get(),e),this.subscribeNewParamTimer()}subscribeBatchedRender(e){let t=!1;this.unsubscribers.push(this.store.subscribe(()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,t)=>{e.newParamId&&e.newParamId!==t.newParamId&&(this.newParamTimer&&clearTimeout(this.newParamTimer),this.newParamTimer=window.setTimeout(()=>{this.store.set({newParamId:null})},650))}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:r}=He(e,t.completedParams);r.length>0&&this.store.set(n=>({completedParams:i,suggestions:[...r.map(a=>({type:a.suggestionType,text:a.suggestionPlaceholder,required:!0,options:a.options})),...n.suggestions]}))}};function ke({onSubmit:o,onError:e,optionOverrides:t,maskCompletedText:i,apiConfig:r,columns:n=2,dropdownTrigger:a,closeDropdownOnBlur:p,onFocus:s,onBlur:l,value:d,completedParams:c,onChange:u,onParamsChange:f}){let m=D(null),[w,x]=wt(null),b=D(o);b.current=o;let C=D(e);C.current=e;let T=D(u);T.current=u;let M=D(f);M.current=f;let H=D(s);H.current=s;let W=D(l);W.current=l,pe(()=>{if(typeof document>"u")return;let y=new de(document.createElement("div"),{renderMode:"headless",apiConfig:r,optionOverrides:t,maskCompletedText:i,columns:n,dropdownTrigger:a,closeDropdownOnBlur:p,value:d,completedParams:c,onSubmit:(...I)=>b.current?.(...I),onError:(...I)=>C.current?.(...I),onChange:(...I)=>T.current?.(...I),onParamsChange:(...I)=>M.current?.(...I),onFocus:()=>H.current?.(),onBlur:()=>W.current?.()});m.current=y,x(y.getState());let g=y.subscribe(I=>x(I));return()=>{g(),y.destroy(),m.current===y&&(m.current=null)}},[]);let h=m.current,S=A(()=>{},[]);pe(()=>{d!==void 0&&h?.setValue(d)},[d,h]),pe(()=>{c!==void 0&&h?.setCompletedParams(c)},[c,h]);let j=JSON.stringify(r??null),P=D(t),B=D(0);if(t!==P.current){let y=P.current,g=t,I=Object.keys(y??{}),V=Object.keys(g??{});(I.length!==V.length||V.some(U=>!y?.[U]||g[U]!==y[U]))&&B.current++,P.current=t}pe(()=>{h?.update({apiConfig:r,optionOverrides:t,dropdownTrigger:a,closeDropdownOnBlur:p})},[j,B.current,a,p,h]);let ue=A(y=>{if(!h)return;let g=y.target.value,V=g.length>0&&!y.nativeEvent?.isComposing&&g[0]!==g[0].toUpperCase()?g[0].toUpperCase()+g.slice(1):g;h.handleTextChange(V)},[h]),me=A(y=>{h?.handleKeyDown(y.nativeEvent)},[h]),X=A(()=>h?.setFocused(!0),[h]),R=A(()=>h?.setFocused(!1),[h]),$=A(y=>h?.setActivePill(y),[h]),O=A(()=>h?.removeLastParam(),[h]),ge=A(()=>h?.clearNewParamId(),[h]),z=A(()=>h?.reset(),[h]),J=A(y=>h?.selectOption(y),[h]),fe=A(y=>h?.setActiveDropdownIndex(y),[h]);if(!h)return{completedParams:c??[],suggestionPills:[],setActivePill:S,removeLastParam:S,segments:[],newParamId:null,clearNewParamId:S,suggestions:[],activeIndex:-1,isReady:!1,isLoading:!0,error:null,inputProps:{value:d??"",placeholder:void 0,onChange:S,onKeyDown:S,onFocus:S,onBlur:S,role:"combobox","aria-expanded":!1,"aria-activedescendant":void 0,"aria-autocomplete":"list","aria-controls":""},reset:S,dropdownProps:{suggestions:[],activeIndex:-1,onSelect:S,onHighlight:S,isOpen:!1,id:"",pills:[],onPillClick:S}};let v=w??h.getState(),q=d!==void 0?d:v.text,he=c!==void 0?c:v.completedParams,F=v.actionableSuggestions,Y=F[0],xe=v.filteredOptions,be=v.activeDropdownIndex>=0?`${h.listboxId}-option-${v.activeDropdownIndex}`:void 0;return{completedParams:he,suggestionPills:F,setActivePill:$,removeLastParam:O,segments:v.segments,newParamId:v.newParamId,clearNewParamId:ge,suggestions:v.suggestions,activeIndex:v.activeDropdownIndex,isReady:v.isReady,isLoading:v.isLoading,error:v.error,inputProps:{value:q,placeholder:v.placeholderText||void 0,onChange:ue,onKeyDown:me,onFocus:X,onBlur:R,role:"combobox","aria-expanded":v.isDropdownOpen,"aria-activedescendant":be,"aria-autocomplete":"list","aria-controls":h.listboxId},reset:z,dropdownProps:{suggestions:Y?[{...Y,options:xe}]:[],activeIndex:v.activeDropdownIndex,onSelect:J,onHighlight:fe,isOpen:v.isDropdownOpen,id:h.listboxId,pills:F,onPillClick:$}}}import{jsx as E,jsxs as K}from"react/jsx-runtime";function Ct(o){return o!=="auto"?o:typeof window>"u"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}var At=St(function({onSubmit:e,onError:t,optionOverrides:i,maskCompletedText:r,className:n,apiConfig:a,columns:p,pillPlacement:s="inline",mode:l="auto",optionsPosition:d="below",animations:c=!0,dropdownTrigger:u,closeDropdownOnBlur:f,autoFocus:m=!0,onFocus:w,onBlur:x,value:b,completedParams:C,onChange:T,onParamsChange:M,submitButton:H},W){let h=ce(null),S=ce(null),j=ce(()=>{}),P=ce(null);Te(()=>{let g=h.current;if(g)return P.current?P.current.setMode(l):P.current=new N(g,l),()=>{P.current?.destroy(),P.current=null}},[l]);let{completedParams:B,suggestionPills:ue,setActivePill:me,segments:X,newParamId:R,clearNewParamId:$,inputProps:O,dropdownProps:ge,reset:z}=ke({onSubmit:g=>j.current(g),onError:t,optionOverrides:i,maskCompletedText:r,apiConfig:a,columns:p,dropdownTrigger:u,closeDropdownOnBlur:f,onFocus:w,onBlur:x,value:b,completedParams:C,onChange:T,onParamsChange:M}),J=O.onFocus;Te(()=>{if(!m)return;let g=S.current;g&&(document.activeElement===g?J():g.focus())},[J,m]),Te(()=>{if(!R)return;let g=window.setTimeout(()=>$(),650);return()=>window.clearTimeout(g)},[R,$]),_t(W,()=>({focus:()=>S.current?.focus(),blur:()=>S.current?.blur(),reset:z,setMode:g=>P.current?.setMode(g)}),[z]);let fe=()=>{S.current?.focus()},v=!!O.value||B.length>0,q=It(()=>{if(!v)return;let{rawQuery:g,completedParams:I}=L(O.value,B);e({query:O.value.trim(),raw_query:g,completed_params:I}),z()},[v,O.value,B,e,z]);j.current=q;let{onChange:he,placeholder:F,...Y}=O,xe=!O.value,be=s==="inline",y=s==="dropdown";return K("div",{ref:h,className:`magicx-aia ${_.container} ${n??""}`,"data-pill-placement":s,"data-options-position":d,"data-animations":c?"on":"off","data-mode":Ct(l),children:[E(Ie,{...ge,showPills:y}),K("div",{className:_.inputWrapper,onClick:fe,children:[K("div",{className:_.editorArea,"data-aia-editor":"",children:[K("div",{className:_.sizerContent,"aria-hidden":"true",children:[xe&&F?K("span",{className:_.placeholderText,children:[F," "]}):K("span",{className:`${_.sizerText} ${R?_.sizerTextVisible:""}`,children:[X.map((g,I)=>{if(g.type==="completed"&&g.param.id===R){let U=`${_.shimmerRevealed} ${_.shimmerSweep}`;return E("span",{className:U,children:g.value},`${I}-${g.type}`)}return E("span",{children:g.value},`${I}-${g.type}`)}),X.length===0&&"\xA0"]})," ",be&&E(ee,{pills:ue,activePillIndex:0,onSelectPill:me})]}),E("textarea",{ref:S,"data-aia-textarea":"",className:`${_.textarea} ${R?_.textareaHidden:""}`,rows:1,onChange:he,...Y})]}),H===null?null:H===void 0?E("button",{type:"button","data-aia-submit":"",className:_.submitButton,disabled:!v,onClick:g=>{g.stopPropagation(),q()},"aria-label":"Submit",children:E("svg",{width:"18",height:"18",viewBox:"0 0 18 18",fill:"none",role:"img","aria-label":"Submit",children:E("path",{d:"M9 14V4M9 4L4 9M9 4L14 9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}):E("span",{"data-aia-submit":"",className:_.submitSlot,onClick:g=>{v&&(g.stopPropagation(),q())},children:H})]})]})});export{At as AIAutocomplete,Ie as AIAutocompleteDropdown,ke as useAIAutocomplete};
692
+ `,document.head.appendChild(o)}import{useCallback as A,useEffect as pe,useRef as D,useState as wt}from"react";function G(o,e,t){let i=o.slice(e);if(t||e===0||o[e-1]===" ")return i;let r=i.indexOf(" ");return r===-1?"":i.slice(r+1)}function Re(o,e){let t=o.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let i=t.split(" "),r=e.toLowerCase();for(let n=0;n<i.length;n++){let a=i.slice(n).join(" ");if(r.startsWith(a.toLowerCase())){let p=t.length-a.length;return o.length-p}}return 0}function te(o,e){if(!o)return[];let t=e.trimStart();if(!t)return o;let i=t.toLowerCase();return o.filter(r=>!r.is_tappable||r.text.toLowerCase().includes(i))}function _e(o,e){if(!o)return null;let t=e.trim();if(!t)return null;let i=t.toLowerCase();return o.find(r=>r.is_tappable&&r.text.toLowerCase()===i)??null}var N=class{constructor(e,t="auto"){this.container=e;this.mode=t;this.mediaQuery=null;this.onSystemChange=e=>{this.container.dataset.mode=e.matches?"dark":"light"};this.apply()}setMode(e){this.detachListener(),this.mode=e,this.apply()}destroy(){this.detachListener()}apply(){this.mode==="auto"?(this.mediaQuery??(this.mediaQuery=window.matchMedia("(prefers-color-scheme: dark)")),this.mediaQuery.addEventListener("change",this.onSystemChange),this.container.dataset.mode=this.mediaQuery.matches?"dark":"light"):this.container.dataset.mode=this.mode}detachListener(){this.mediaQuery?.removeEventListener("change",this.onSystemChange)}};function Me(o,e){let t=[],i=0;for(let n of e){let a=o.indexOf(n.text,i);a!==-1&&(a>i&&t.push({type:"text",value:o.slice(i,a)}),t.push({type:"completed",value:n.text,param:n}),i=a+n.text.length)}let r=o.slice(i);return r&&t.push({type:"text",value:r}),t}function He(o,e){let t=[],i=[],r=0;for(let n of e){let a=o.indexOf(n.text,r);a===-1?i.push(n):(t.push(n),r=a+n.text.length)}return{valid:t,invalid:i}}var oe=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;this.inFlightRefresh=null;e.accessToken&&(this.current=e.accessToken)}async getToken(e=!1){if(!e&&this.current&&!this.isExpired())return this.current;if(!e&&this.inFlightRefresh)return this.inFlightRefresh;this.inFlightRefresh=this.refresh();try{return await this.inFlightRefresh}finally{this.inFlightRefresh=null}}async refresh(){let e=await this.config.getAccessToken();return this.current=e.accessToken,this.expiresAt=e.expiresAt??null,this.current}isExpired(){return this.expiresAt==null?!1:Date.now()>=this.expiresAt-3e4}};var nt="0.1.35",Be=!1;function rt(){return crypto.randomUUID()}function st(o,e){return{placeholder:o.placeholder,type:o.type,...e&&{text:o.text},kind:o.kind}}function Ne(o){return o?.type==="accessToken"}function at(o){if(!(!o||Ne(o)))return o}var ze=new WeakMap;function lt(o){let e=ze.get(o.getAccessToken);return e||(e=new oe(o),ze.set(o.getAccessToken,e)),e}function dt(o,e,t,i){let r=e.find(a=>a.type==="contact"&&a.metadata?.contact_account_count)?.metadata?.contact_account_count,n=typeof r=="number"?r:void 0;return{data:{raw_query:o,completed_params:e.map(a=>st(a,t)),...n!=null&&{contact_account_count:n}},meta:{request_id:rt(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:nt,session_id:i}}}function pt(o){return{"Content-Type":"application/json",...o?.appIdentifier&&{"X-App-Identifier":o.appIdentifier},...o?.headers}}async function Fe(o,e,t,i,r){return fetch(o,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:r})}async function Ke(o,e,t){let i=t.apiConfig,r=!t.maskCompletedText,n=dt(o,e,r,t.sessionId),a=pt(i),p=i?.endpoint??"https://api.ai-autocomplete.com/api/suggest",s=JSON.stringify(n);if(Ne(i)){let u=lt(i),f=await u.getToken(),m=await Fe(p,a,f,s,t.signal);if(m.status===401){let w=await u.getToken(!0);m=await Fe(p,a,w,s,t.signal)}if(!m.ok)throw new Error(`API error: ${m.status} ${m.statusText}`);return m.json()}let l=at(i),d=l?.apiKey??"";if(!d&&!Be&&(Be=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),d){let u=l?.authScheme??"Bearer";a.Authorization=u==="Basic"?`Basic ${btoa(d)}`:`Bearer ${d}`}let c=await fetch(p,{method:"POST",headers:a,body:s,signal:t.signal});if(!c.ok)throw new Error(`API error: ${c.status} ${c.statusText}`);return c.json()}function L(o,e){let t=o,i={},r=[];for(let n of e){let a=(i[n.type]??0)+1;i[n.type]=a;let s=`{{${n.type.toUpperCase().replace(/\s+/g,"_")}_${a}}}`,l=t.indexOf(n.text);l!==-1&&(t=t.slice(0,l)+s+t.slice(l+n.text.length)),r.push({...n,placeholder:s})}return{rawQuery:t,completedParams:r}}function $e(o,e){return e?o.map(t=>{let i=e[t.type];if(!i)return t;let r=i("");if(r.length===0)return t;let n=new Set(r.map(p=>p.text)),a=(t.options??[]).filter(p=>!n.has(p.text));return{...t,options:[...r,...a]}}):o}var ct=100,ut=300,mt=2,ie=class{constructor(e,t,i,r,n,a){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=r;this.getOnError=n;this.getSessionId=a;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null}start(){this.doFetch("",[]);let e=this.store.get().text,t=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(i=>{(i.text!==e||i.completedParams!==t)&&(e=i.text,t=i.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let i=new AbortController;this.abortController=i;let r=++this.fetchVersion,n=this.store.get(),a=n.text.length;n.suggestions.some(s=>s.type!=="placeholder")||this.store.set({isLoading:!0}),this.store.set({error:null});try{let s=await Ke(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig()});if(r!==this.fetchVersion)return;let l=$e(s.data.suggestions??[],this.getOptionOverrides()),d=s.data.input??[],c=d[d.length-1],u=this.store.get().text,f,m;if(c?.state==="in_progress"){m=!0;let C=u.toLowerCase().lastIndexOf(c.text.toLowerCase());f=C!==-1?C:a}else m=!1,f=a;let x=l.filter(C=>C.type!=="placeholder")[0],b=null;if(x){let C=G(u,f,m),T=_e(x.options,C);T&&(b={id:crypto.randomUUID(),placeholder:"",type:x.type,text:T.text,kind:T.kind,suggestionType:x.type,suggestionPlaceholder:x.text,options:x.options??[],metadata:T.metadata},l=l.filter(M=>M!==x))}this.store.set(C=>({suggestions:l,isLoading:!1,isReady:s.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:f,filterInProgress:m,...b?{completedParams:[...C.completedParams,b]}:{}}))}catch(s){if(r===this.fetchVersion){let l=s instanceof Error?s:new Error(String(s));this.store.set({error:l,isLoading:!1}),this.getOnError()?.(l)}}}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}let t=i=>{let r=this.store.get();if(!r.text&&r.completedParams.length===0)return this.doFetch("",[]),!0;let n=G(r.text,r.filterBase,r.filterInProgress),p=r.suggestions.filter(x=>x.type!=="placeholder")[0],l=(p?te(p.options,n):[]).filter(x=>x.is_tappable),d=p?_e(p.options,n)!==null:!1,c=n.trim().length>0;if(l.length>0&&!d&&c)return!1;if(r.completedParams.length===0&&r.text.length>0){let x=r.suggestions.filter(b=>b.type==="placeholder").map(b=>b.text).join(" ");if(x.length>0&&x.toLowerCase().startsWith(r.text.toLowerCase()))return!1}let{rawQuery:u,completedParams:f}=L(r.text,r.completedParams),m=u.length<r.lastRawQuery.length,w=Math.abs(u.length-r.lastRawQuery.length);return m||w>=i?(this.doFetch(u,f),!0):!1};this.debounceTimer=setTimeout(()=>{t(mt)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},ct),this.slowDebounceTimer=setTimeout(()=>t(1),ut)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var ne=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:r}=this.ctx,n=this.getEffectiveColumns(),a=r(),p=this.getTappableIndices(n);switch(e.key){case"ArrowDown":{let s=e.target;if(!(s.selectionStart!=null&&s.selectionStart===s.value.length)&&t.activeDropdownIndex<0)break;if(e.preventDefault(),!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:p[0]??0});break}if(p.length===0)return;let d=p.indexOf(t.activeDropdownIndex),c=d<p.length-1?d+1:0;this.store.set({activeDropdownIndex:p[c]});break}case"ArrowUp":{if(p.length===0||t.activeDropdownIndex<0)break;if(e.preventDefault(),t.activeDropdownIndex<n){this.store.set({activeDropdownIndex:-1});break}let s=p.indexOf(t.activeDropdownIndex),l=s>0?s-1:p.length-1;this.store.set({activeDropdownIndex:p[l]});break}case"ArrowRight":{if(t.activeDropdownIndex<0){let l=e.target;l.selectionStart!=null&&l.selectionStart===l.value.length&&t.actionableSuggestions.length>1&&(e.preventDefault(),this.pillsSetActivePill(1));break}if(t.activeDropdownIndex%n<n-1){let l=t.activeDropdownIndex+1;l<t.filteredOptions.length&&t.filteredOptions[l]?.is_tappable&&(e.preventDefault(),this.store.set({activeDropdownIndex:l}))}break}case"ArrowLeft":{if(t.activeDropdownIndex<0)break;if(t.activeDropdownIndex%n>0){let s=t.activeDropdownIndex-1;s>=0&&t.filteredOptions[s]?.is_tappable&&(e.preventDefault(),this.store.set({activeDropdownIndex:s}))}break}case"Enter":{if(e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable)this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i);else if(a){let{rawQuery:s,completedParams:l}=L(t.text,t.completedParams);a({query:t.text.trim(),raw_query:s,completed_params:l}),this.ctx.afterSubmit?.()}break}case"Tab":{let s=!t.text&&!!t.placeholderText,l=t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable;if(s&&!l){e.preventDefault();let d=t.suggestions.find(c=>c.type==="placeholder");d?this.store.set(c=>({text:t.placeholderText,filterBase:t.placeholderText.length,completedParams:[...c.completedParams,{id:crypto.randomUUID(),placeholder:"",type:d.type,text:t.placeholderText,kind:null,suggestionType:d.type,suggestionPlaceholder:d.text,options:d.options??[]}],suggestions:c.suggestions.filter(u=>u!==d)})):this.store.set({text:t.placeholderText,filterBase:t.placeholderText.length})}else if(l)e.preventDefault(),this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i);else if(t.isDropdownOpen){let d=t.filteredOptions.findIndex(c=>c.is_tappable);d>=0&&(e.preventDefault(),this.clickOrSelect(d,t.filteredOptions,i))}break}case"Escape":this.store.set({activeDropdownIndex:-1});break}}getTappableIndices(e){let i=this.store.get().filteredOptions.map((n,a)=>n.is_tappable?a:-1).filter(n=>n!==-1),r=Array.from({length:e},()=>[]);for(let n of i)r[n%e].push(n);return r.flat()}getEffectiveColumns(){let t=document.getElementById(`${this.ctx.listboxId}-option-0`)?.parentElement;if(!t)return this.ctx.columns;let i=getComputedStyle(t).gridTemplateColumns.split(" ").filter(Boolean).length;return i>0?i:this.ctx.columns}clickOrSelect(e,t,i){let r=document.getElementById(`${i}-option-${e}`);r?r.click():this.ctx.selectOption(t[e])}pillsSetActivePill(e){let t=this.store.get(),i=t.suggestions.filter(p=>p.type!=="placeholder");if(e<0||e>=i.length)return;let r=i[e],n=i.filter((p,s)=>s!==e),a=t.suggestions.filter(p=>p.type==="placeholder");this.store.set({suggestions:[...a,r,...n],pillTapped:!0,activeDropdownIndex:-1})}};var re=class{constructor(e){this.store=e}setActivePill(e){let t=this.store.get(),i=t.suggestions.filter(p=>p.type!=="placeholder");if(e<0||e>=i.length)return;let r=i[e],n=i.filter((p,s)=>s!==e),a=t.suggestions.filter(p=>p.type==="placeholder");this.store.set({suggestions:[...a,r,...n],pillTapped:!0,activeDropdownIndex:-1})}removeLastParam(){let e=this.store.get();if(e.completedParams.length===0)return;let t=e.completedParams[e.completedParams.length-1],i={type:t.suggestionType,text:t.suggestionPlaceholder,required:!0,options:t.options};this.store.set(r=>({completedParams:r.completedParams.slice(0,-1),suggestions:[i,...r.suggestions],activeDropdownIndex:-1}))}};function gt(o){return o===0?.4:o===1?.3:.15}function se(o,e,t,i,r=!1){let n=o.querySelector(".magicx-aia-pill-list");n||(n=document.createElement("span"),n.className="magicx-aia-pill-list",o.appendChild(n));let a=new Map;for(let s of n.querySelectorAll(".magicx-aia-pill"))a.set(s.dataset.pillKey??"",s);let p=new Set;for(let s=0;s<e.length;s++){let l=e[s],d=`${l.type}-${l.text}`;p.add(d);let c=a.get(d);c||(c=document.createElement("button"),c.type="button",c.dataset.pillKey=d,c.setAttribute("data-aia-pill",""),c.textContent=l.text),c.className=`magicx-aia-pill${r?" magicx-aia-pill--rounded":""}${s===t?" magicx-aia-pill--active":""}`,c.style.opacity=String(gt(s)),c.onclick=()=>i(s),n.children[s]!==c&&n.insertBefore(c,n.children[s]??null)}for(let[s,l]of a)p.has(s)||l.remove()}function ae(o){let e=document.createElement("div");return e.id=o,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",t=>t.preventDefault()),e}function le(o,e){let{filteredOptions:t,activeIndex:i,isOpen:r,pills:n,showPills:a,onSelect:p,onHighlight:s,onPillClick:l}=e,d=a&&n.length>0;r&&t.length>0||r&&d?o.classList.add("magicx-aia-dropdown--visible"):o.classList.remove("magicx-aia-dropdown--visible");let f=o.querySelector(".magicx-aia-pill-bar");d?(f||(f=document.createElement("div"),f.className="magicx-aia-pill-bar",f.setAttribute("data-aia-pillbar",""),o.insertBefore(f,o.firstChild)),se(f,n,0,l,!0)):f&&f.remove();let m=o.querySelector(".magicx-aia-grid");t.length>0?(m||(m=document.createElement("div"),m.className="magicx-aia-grid",o.appendChild(m)),ft(m,t,i,p,s,e.listboxId)):m&&(m.innerHTML="")}function ft(o,e,t,i,r,n){let a=e.map(l=>l.text).join("\0"),p=o.dataset.optionsKey??"",s=a!==p;if(o.dataset.optionsKey=a,s){let l=document.createDocumentFragment();for(let d=0;d<e.length;d++){let c=e[d],u=ht(c,d,t,i,r,n);l.appendChild(u)}o.innerHTML="",o.appendChild(l)}else{let l=o.querySelectorAll(".magicx-aia-option");for(let d=0;d<l.length;d++){let c=l[d],u=d===t;c.setAttribute("aria-selected",String(u)),u?c.classList.add("magicx-aia-option--highlighted"):c.classList.remove("magicx-aia-option--highlighted")}}}function ht(o,e,t,i,r,n){let a=document.createElement("div");a.id=`${n}-option-${e}`,a.setAttribute("role","option"),a.setAttribute("data-aia-option",""),a.setAttribute("aria-selected",String(e===t)),a.tabIndex=o.is_tappable?0:-1;let p=["magicx-aia-option"];e===t&&p.push("magicx-aia-option--highlighted"),o.is_tappable?p.push("magicx-aia-option--tappable"):p.push("magicx-aia-option--non-tappable"),a.className=p.join(" ");let s=document.createElement("div");s.className="magicx-aia-streaks",a.appendChild(s);let l=document.createElement("div");l.className="magicx-aia-streaks-vert",a.appendChild(l);let d=document.createElement("span");if(d.className="magicx-aia-option-content",d.textContent=o.icon?`${o.icon} ${o.text}`:o.text,o.tag){let c=document.createElement("span");c.className="magicx-aia-option-tag",c.textContent=o.tag,d.appendChild(c)}return a.appendChild(d),o.is_tappable&&(a.addEventListener("click",()=>{a.classList.add("magicx-aia-option--pressed"),i(o),setTimeout(()=>a.classList.remove("magicx-aia-option--pressed"),400)}),a.addEventListener("mouseenter",()=>r(e))),a}function qe(o,e){let t=ae(e.listboxId);return o.appendChild(t),{dropdown:t}}function Ce(o,e,t){le(o.dropdown,{suggestions:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,onSelect:t.selectOption,onHighlight:i=>t.store.set({activeDropdownIndex:i}),onPillClick:t.setActivePill})}function Ve(o,e,t,i,r){let n=o.querySelector(".magicx-aia-sizer-text"),a=o.querySelector(".magicx-aia-placeholder");if(i&&r){n&&(n.style.display="none"),a||(a=document.createElement("span"),a.className="magicx-aia-placeholder",o.insertBefore(a,o.firstChild)),a.style.display="",a.textContent=`${r} `,o.dataset.segmentKey="";return}a&&(a.style.display="none"),n||(n=document.createElement("span"),n.className="magicx-aia-sizer-text",o.insertBefore(n,o.firstChild)),n.style.display="",n.className=`magicx-aia-sizer-text${t?" magicx-aia-sizer-text--visible":""}`;let p=e.map(d=>`${d.type}:${d.value}`).join("\0"),s=o.dataset.segmentKey??"",l=o.dataset.newParamId??"";if(!(p===s&&(t??"")===l)){o.dataset.segmentKey=p,o.dataset.newParamId=t??"",n.innerHTML="";for(let d of e){let c=document.createElement("span");d.type==="completed"&&(d.param.id===t?c.className="magicx-aia-shimmer-revealed magicx-aia-shimmer-sweep":c.className="magicx-aia-segment magicx-aia-segment--completed"),c.textContent=d.value,n.appendChild(c)}e.length===0&&(n.textContent="\xA0")}}var xt='<svg width="18" height="18" viewBox="0 0 18 18" fill="none" role="img" aria-label="Submit"><path d="M9 14V4M9 4L4 9M9 4L14 9" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';function Ue(o,e){let{listboxId:t}=e,i=ae(t);o.appendChild(i);let r=document.createElement("div");r.className="magicx-aia-input-wrapper",o.appendChild(r);let n=document.createElement("div");n.className="magicx-aia-editor",n.setAttribute("data-aia-editor",""),r.appendChild(n);let a=document.createElement("div");a.className="magicx-aia-sizer",a.setAttribute("aria-hidden","true"),n.appendChild(a);let p=document.createElement("span");a.appendChild(document.createTextNode(" ")),a.appendChild(p);let s=document.createElement("textarea");s.className="magicx-aia-textarea",s.rows=1,s.setAttribute("role","combobox"),s.setAttribute("aria-autocomplete","list"),s.setAttribute("aria-controls",t),s.setAttribute("data-aia-textarea",""),n.appendChild(s);let l=null,d=null;return e.submitButton===void 0?(l=document.createElement("button"),l.type="button",l.className="magicx-aia-submit",l.setAttribute("aria-label","Submit"),l.setAttribute("data-aia-submit",""),l.innerHTML=xt,r.appendChild(l),d=l):e.submitButton!==null&&(d=e.submitButton,d.hasAttribute("data-aia-submit")||d.setAttribute("data-aia-submit",""),r.appendChild(d)),r.addEventListener("click",()=>s.focus()),s.addEventListener("input",()=>{let c=s.value,f=c.length>0&&c[0]!==c[0].toUpperCase()?c[0].toUpperCase()+c.slice(1):c;e.handleChange(f)}),s.addEventListener("keydown",c=>e.handleKeyDown(c)),s.addEventListener("focus",()=>e.store.set({isFocused:!0})),s.addEventListener("blur",()=>e.store.set({isFocused:!1})),d&&d.addEventListener("click",c=>{let u=e.store.get();if(!(!!u.text||u.completedParams.length>0)||!e.onSubmit)return;c.stopPropagation();let{rawQuery:m,completedParams:w}=L(u.text,u.completedParams);e.onSubmit({query:u.text.trim(),raw_query:m,completed_params:w}),e.afterSubmit?.()}),e.autoFocus!==!1&&s.focus(),{textarea:s,dropdown:i,sizer:a,submitButton:l,inlinePillContainer:p}}function Ae(o,e,t){let{textarea:i,dropdown:r,sizer:n,submitButton:a,inlinePillContainer:p}=o,{pillPlacement:s,setActivePill:l,selectOption:d,store:c}=t;i.value!==e.text&&(i.value=e.text),e.placeholderText?i.placeholder=e.placeholderText:i.removeAttribute("placeholder"),i.setAttribute("aria-expanded",String(e.isDropdownOpen));let u=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(u?i.setAttribute("aria-activedescendant",u):i.removeAttribute("aria-activedescendant"),e.newParamId?i.classList.add("magicx-aia-textarea--hidden"):i.classList.remove("magicx-aia-textarea--hidden"),a){let f=!!e.text||e.completedParams.length>0;a.disabled=!f}Ve(n,e.segments,e.newParamId,!e.text,e.placeholderText),s==="inline"?se(p,e.actionableSuggestions,0,l):p.innerHTML="",le(r,{suggestions:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:s==="dropdown",onSelect:d,onHighlight:f=>c.set({activeDropdownIndex:f}),onPillClick:l})}function Qe(o){let e=o,t=new Set;return{get:()=>e,set:i=>{let r=typeof i=="function"?i(e):i,n={...e,...r},a=e;e=n;for(let p of t)p(n,a)},subscribe:i=>(t.add(i),()=>{t.delete(i)})}}var Pe=!1;function Ge(){if(Pe||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){Pe=!0;return}Pe=!0;let o=document.createElement("style");o.setAttribute("data-magicx-aia",""),o.textContent=bt,document.head.appendChild(o)}var bt="";var vt=0;function yt(){return`:ac-${++vt}:`}function We(){return{text:"",completedParams:[],suggestions:[],activeDropdownIndex:-1,newParamId:null,isLoading:!1,isReady:!1,error:null,segments:[],actionableSuggestions:[],filteredOptions:[],placeholderText:"",isDropdownOpen:!1,filterBase:0,filterInProgress:!1,pillTapped:!1,skipNextFetch:!1,lastRawQuery:"",isFocused:!1}}var de=class{constructor(e,t={}){this.store=Qe(We());this._listboxId=yt();this.modeController=null;this.unsubscribers=[];this.derivedInProgress=!1;this.domRefs=null;this.dropdownRefs=null;this.externalListeners=new Set;this.sessionId=crypto.randomUUID();this.container=e,this.opts=t,this.renderMode=t.renderMode??"full",t.value!==void 0&&this.store.set({text:t.value}),t.completedParams!==void 0&&this.store.set({completedParams:t.completedParams}),this.pillsController=new re(this.store),this.fetchController=new ie(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.opts.onError,()=>this.sessionId),this.keyboardController=new ne(this.store,{columns:t.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.opts.onSubmit,afterSubmit:this.renderMode==="full"?()=>this.reset():void 0,selectOption:i=>this.selectOption(i)}),this.unsubscribers.push(this.store.subscribe((i,r)=>{this.recomputeDerived(i,r)})),this.unsubscribers.push(this.store.subscribe((i,r)=>{i.text!==r.text&&this.opts.onChange?.(i.text),i.completedParams!==r.completedParams&&this.opts.onParamsChange?.(i.completedParams),i.isFocused!==r.isFocused&&(i.isFocused?this.opts.onFocus?.():this.opts.onBlur?.()),this.opts.onStateChange?.(i)})),this.renderMode!=="headless"&&(Ge(),this.setupContainer()),this.renderMode==="full"?this.buildAndRenderFull():this.renderMode==="dropdown"&&this.buildAndRenderDropdown(),this.fetchController.start()}focus(){this.domRefs?.textarea.focus()}blur(){this.domRefs?.textarea.blur()}reset(){this.store.set({...We(),skipNextFetch:!0}),this.sessionId=crypto.randomUUID(),this.fetchController.doFetch("",[])}destroy(){this.fetchController.dispose(),this.modeController?.destroy(),this.newParamTimer&&clearTimeout(this.newParamTimer),this.suggestionRemovalTimer&&clearTimeout(this.suggestionRemovalTimer),this.externalListeners.clear();for(let e of this.unsubscribers)e();this.unsubscribers=[],this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}setValue(e){this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e)}removeLastParam(){this.pillsController.removeLastParam()}clearNewParamId(){this.store.set({newParamId:null})}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}handleTextChange(e){this.handleChange(e)}handleKeyDown(e){this.keyboardController.handleKeyDown(e)}setFocused(e){this.store.get().isFocused!==e&&this.store.set({isFocused:e})}subscribe(e){return this.externalListeners.add(e),()=>{this.externalListeners.delete(e)}}getState(){return this.store.get()}get listboxId(){return this._listboxId}get isReady(){return this.store.get().isReady}on(e,t){switch(e){case"submit":return this.opts.onSubmit=t,()=>{this.opts.onSubmit=void 0};case"error":return this.opts.onError=t,()=>{this.opts.onError=void 0};case"change":return this.opts.onChange=t,()=>{this.opts.onChange=void 0};case"paramsChange":return this.opts.onParamsChange=t,()=>{this.opts.onParamsChange=void 0};case"stateChange":return this.opts.onStateChange=t,()=>{this.opts.onStateChange=void 0};case"focus":return this.opts.onFocus=t,()=>{this.opts.onFocus=void 0};case"blur":return this.opts.onBlur=t,()=>{this.opts.onBlur=void 0};default:return()=>{}}}update(e){Object.assign(this.opts,e),e.mode!==void 0&&this.modeController?.setMode(e.mode),e.optionsPosition!==void 0&&(this.container.dataset.optionsPosition=e.optionsPosition),e.animations!==void 0&&(this.container.dataset.animations=e.animations?"on":"off"),e.pillPlacement!==void 0&&(this.container.dataset.pillPlacement=e.pillPlacement,this.store.set({})),(e.dropdownTrigger!==void 0||e.closeDropdownOnBlur!==void 0)&&this.store.set({}),e.value!==void 0&&this.store.set({text:e.value}),e.completedParams!==void 0&&this.store.set({completedParams:e.completedParams})}selectOption(e){let t=this.store.get(),i=t.actionableSuggestions[0];if(!i)return;let r=t.filterBase,n=t.text.slice(0,r),a=n.length===0&&t.text.length===0,p=n.length===0&&t.text.length>0&&t.placeholderText.length>0&&t.placeholderText.toLowerCase().startsWith(t.text.toLowerCase());(a||p)&&t.placeholderText&&(n=`${t.placeholderText} `);let s=Re(n,e.text);s>0&&(n=n.slice(0,n.length-s));let l=n.length>0&&n[n.length-1]!==" ",d=`${n}${l?" ":""}${e.text} `,c=(a||p)&&d.length>0?d[0].toUpperCase()+d.slice(1):d,u=c.toLowerCase().lastIndexOf(e.text.toLowerCase()),f=u>=0?c.slice(u,u+e.text.length):e.text,m={id:crypto.randomUUID(),placeholder:"",type:i.type,text:f,kind:e.kind,suggestionType:i.type,suggestionPlaceholder:i.text,options:i.options??[],metadata:e.metadata},w=t.actionableSuggestions.length-1;this.store.set(x=>({text:c,filterBase:c.length,completedParams:[...x.completedParams,m],newParamId:m.id,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:w>0})),this.suggestionRemovalTimer=window.setTimeout(()=>{this.store.set(x=>({suggestions:x.suggestions.filter(b=>b!==i)}))},400)}recomputeDerived(e,t){if(this.derivedInProgress)return;this.derivedInProgress=!0;let i=Me(e.text,e.completedParams),r=e.suggestions.filter(b=>b.type!=="placeholder"),n=r[0],a=n?this.opts.optionOverrides?.[n.type]:void 0,p=Math.min(e.filterBase,e.text.length),l=e.lastRawQuery!==""||p>0?G(e.text,p,e.filterInProgress):"",d=n?a?a(l.trim()):n.options??[]:[],c=te(d,l),u=e.suggestions.filter(b=>b.type==="placeholder").map(b=>b.text).join(" "),f=this.opts.dropdownTrigger??"auto",m=this.opts.closeDropdownOnBlur??!0,w=!1;if(f==="auto"){let b=m?e.isFocused:!0;w=!e.isLoading&&c.length>0&&b}else f==="manual"&&(w=!e.isLoading&&c.length>0&&e.pillTapped);this.store.set({segments:i,actionableSuggestions:r,filteredOptions:c,placeholderText:u,isDropdownOpen:w}),this.derivedInProgress=!1;let x=this.store.get();for(let b of this.externalListeners)b(x)}setupContainer(){this.container.classList.add("magicx-aia"),this.container.dataset.pillPlacement=this.renderMode==="dropdown"?"dropdown":this.opts.pillPlacement??"inline",this.container.dataset.optionsPosition=this.opts.optionsPosition??"below",this.container.dataset.animations=this.opts.animations??!0?"on":"off",this.modeController=new N(this.container,this.opts.mode??"auto")}buildAndRenderFull(){let e=this,t={store:this.store,listboxId:this.listboxId,get pillPlacement(){return e.opts.pillPlacement??"inline"},get onSubmit(){return e.opts.onSubmit},afterSubmit:()=>e.reset(),submitButton:this.opts.submitButton,autoFocus:this.opts.autoFocus??!0,selectOption:i=>this.selectOption(i),setActivePill:i=>this.pillsController.setActivePill(i),handleKeyDown:i=>this.keyboardController.handleKeyDown(i),handleChange:i=>this.handleChange(i)};this.domRefs=Ue(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&Ae(this.domRefs,this.store.get(),t)}),Ae(this.domRefs,this.store.get(),t),this.subscribeNewParamTimer()}buildAndRenderDropdown(){let e={store:this.store,listboxId:this.listboxId,selectOption:t=>this.selectOption(t),setActivePill:t=>this.pillsController.setActivePill(t)};this.dropdownRefs=qe(this.container,e),this.subscribeBatchedRender(()=>{this.dropdownRefs&&Ce(this.dropdownRefs,this.store.get(),e)}),Ce(this.dropdownRefs,this.store.get(),e),this.subscribeNewParamTimer()}subscribeBatchedRender(e){let t=!1;this.unsubscribers.push(this.store.subscribe(()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,t)=>{e.newParamId&&e.newParamId!==t.newParamId&&(this.newParamTimer&&clearTimeout(this.newParamTimer),this.newParamTimer=window.setTimeout(()=>{this.store.set({newParamId:null})},650))}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:r}=He(e,t.completedParams);r.length>0&&this.store.set(n=>({completedParams:i,suggestions:[...r.map(a=>({type:a.suggestionType,text:a.suggestionPlaceholder,required:!0,options:a.options})),...n.suggestions]}))}};function ke({onSubmit:o,onError:e,optionOverrides:t,maskCompletedText:i,apiConfig:r,columns:n=2,dropdownTrigger:a,closeDropdownOnBlur:p,onFocus:s,onBlur:l,value:d,completedParams:c,onChange:u,onParamsChange:f}){let m=D(null),[w,x]=wt(null),b=D(o);b.current=o;let C=D(e);C.current=e;let T=D(u);T.current=u;let M=D(f);M.current=f;let H=D(s);H.current=s;let W=D(l);W.current=l,pe(()=>{if(typeof document>"u")return;let y=new de(document.createElement("div"),{renderMode:"headless",apiConfig:r,optionOverrides:t,maskCompletedText:i,columns:n,dropdownTrigger:a,closeDropdownOnBlur:p,value:d,completedParams:c,onSubmit:(...I)=>b.current?.(...I),onError:(...I)=>C.current?.(...I),onChange:(...I)=>T.current?.(...I),onParamsChange:(...I)=>M.current?.(...I),onFocus:()=>H.current?.(),onBlur:()=>W.current?.()});m.current=y,x(y.getState());let g=y.subscribe(I=>x(I));return()=>{g(),y.destroy(),m.current===y&&(m.current=null)}},[]);let h=m.current,S=A(()=>{},[]);pe(()=>{d!==void 0&&h?.setValue(d)},[d,h]),pe(()=>{c!==void 0&&h?.setCompletedParams(c)},[c,h]);let j=JSON.stringify(r??null),P=D(t),B=D(0);if(t!==P.current){let y=P.current,g=t,I=Object.keys(y??{}),V=Object.keys(g??{});(I.length!==V.length||V.some(U=>!y?.[U]||g[U]!==y[U]))&&B.current++,P.current=t}pe(()=>{h?.update({apiConfig:r,optionOverrides:t,dropdownTrigger:a,closeDropdownOnBlur:p})},[j,B.current,a,p,h]);let ue=A(y=>{if(!h)return;let g=y.target.value,V=g.length>0&&!y.nativeEvent?.isComposing&&g[0]!==g[0].toUpperCase()?g[0].toUpperCase()+g.slice(1):g;h.handleTextChange(V)},[h]),me=A(y=>{h?.handleKeyDown(y.nativeEvent)},[h]),X=A(()=>h?.setFocused(!0),[h]),R=A(()=>h?.setFocused(!1),[h]),$=A(y=>h?.setActivePill(y),[h]),O=A(()=>h?.removeLastParam(),[h]),ge=A(()=>h?.clearNewParamId(),[h]),z=A(()=>h?.reset(),[h]),J=A(y=>h?.selectOption(y),[h]),fe=A(y=>h?.setActiveDropdownIndex(y),[h]);if(!h)return{completedParams:c??[],suggestionPills:[],setActivePill:S,removeLastParam:S,segments:[],newParamId:null,clearNewParamId:S,suggestions:[],activeIndex:-1,isReady:!1,isLoading:!0,error:null,inputProps:{value:d??"",placeholder:void 0,onChange:S,onKeyDown:S,onFocus:S,onBlur:S,role:"combobox","aria-expanded":!1,"aria-activedescendant":void 0,"aria-autocomplete":"list","aria-controls":""},reset:S,dropdownProps:{suggestions:[],activeIndex:-1,onSelect:S,onHighlight:S,isOpen:!1,id:"",pills:[],onPillClick:S}};let v=w??h.getState(),q=d!==void 0?d:v.text,he=c!==void 0?c:v.completedParams,F=v.actionableSuggestions,Y=F[0],xe=v.filteredOptions,be=v.activeDropdownIndex>=0?`${h.listboxId}-option-${v.activeDropdownIndex}`:void 0;return{completedParams:he,suggestionPills:F,setActivePill:$,removeLastParam:O,segments:v.segments,newParamId:v.newParamId,clearNewParamId:ge,suggestions:v.suggestions,activeIndex:v.activeDropdownIndex,isReady:v.isReady,isLoading:v.isLoading,error:v.error,inputProps:{value:q,placeholder:v.placeholderText||void 0,onChange:ue,onKeyDown:me,onFocus:X,onBlur:R,role:"combobox","aria-expanded":v.isDropdownOpen,"aria-activedescendant":be,"aria-autocomplete":"list","aria-controls":h.listboxId},reset:z,dropdownProps:{suggestions:Y?[{...Y,options:xe}]:[],activeIndex:v.activeDropdownIndex,onSelect:J,onHighlight:fe,isOpen:v.isDropdownOpen,id:h.listboxId,pills:F,onPillClick:$}}}import{jsx as E,jsxs as K}from"react/jsx-runtime";function Ct(o){return o!=="auto"?o:typeof window>"u"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}var At=St(function({onSubmit:e,onError:t,optionOverrides:i,maskCompletedText:r,className:n,apiConfig:a,columns:p,pillPlacement:s="inline",mode:l="auto",optionsPosition:d="below",animations:c=!0,dropdownTrigger:u,closeDropdownOnBlur:f,autoFocus:m=!0,onFocus:w,onBlur:x,value:b,completedParams:C,onChange:T,onParamsChange:M,submitButton:H},W){let h=ce(null),S=ce(null),j=ce(()=>{}),P=ce(null);Te(()=>{let g=h.current;if(g)return P.current?P.current.setMode(l):P.current=new N(g,l),()=>{P.current?.destroy(),P.current=null}},[l]);let{completedParams:B,suggestionPills:ue,setActivePill:me,segments:X,newParamId:R,clearNewParamId:$,inputProps:O,dropdownProps:ge,reset:z}=ke({onSubmit:g=>j.current(g),onError:t,optionOverrides:i,maskCompletedText:r,apiConfig:a,columns:p,dropdownTrigger:u,closeDropdownOnBlur:f,onFocus:w,onBlur:x,value:b,completedParams:C,onChange:T,onParamsChange:M}),J=O.onFocus;Te(()=>{if(!m)return;let g=S.current;g&&(document.activeElement===g?J():g.focus())},[J,m]),Te(()=>{if(!R)return;let g=window.setTimeout(()=>$(),650);return()=>window.clearTimeout(g)},[R,$]),_t(W,()=>({focus:()=>S.current?.focus(),blur:()=>S.current?.blur(),reset:z,setMode:g=>P.current?.setMode(g)}),[z]);let fe=()=>{S.current?.focus()},v=!!O.value||B.length>0,q=It(()=>{if(!v)return;let{rawQuery:g,completedParams:I}=L(O.value,B);e({query:O.value.trim(),raw_query:g,completed_params:I}),z()},[v,O.value,B,e,z]);j.current=q;let{onChange:he,placeholder:F,...Y}=O,xe=!O.value,be=s==="inline",y=s==="dropdown";return K("div",{ref:h,className:`magicx-aia ${_.container} ${n??""}`,"data-pill-placement":s,"data-options-position":d,"data-animations":c?"on":"off","data-mode":Ct(l),children:[E(Ie,{...ge,showPills:y}),K("div",{className:_.inputWrapper,onClick:fe,children:[K("div",{className:_.editorArea,"data-aia-editor":"",children:[K("div",{className:_.sizerContent,"aria-hidden":"true",children:[xe&&F?K("span",{className:_.placeholderText,children:[F," "]}):K("span",{className:`${_.sizerText} ${R?_.sizerTextVisible:""}`,children:[X.map((g,I)=>{if(g.type==="completed"&&g.param.id===R){let U=`${_.shimmerRevealed} ${_.shimmerSweep}`;return E("span",{className:U,children:g.value},`${I}-${g.type}`)}return E("span",{children:g.value},`${I}-${g.type}`)}),X.length===0&&"\xA0"]})," ",be&&E(ee,{pills:ue,activePillIndex:0,onSelectPill:me})]}),E("textarea",{ref:S,"data-aia-textarea":"",className:`${_.textarea} ${R?_.textareaHidden:""}`,rows:1,onChange:he,...Y})]}),H===null?null:H===void 0?E("button",{type:"button","data-aia-submit":"",className:_.submitButton,disabled:!v,onClick:g=>{g.stopPropagation(),q()},"aria-label":"Submit",children:E("svg",{width:"18",height:"18",viewBox:"0 0 18 18",fill:"none",role:"img","aria-label":"Submit",children:E("path",{d:"M9 14V4M9 4L4 9M9 4L14 9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}):E("span",{"data-aia-submit":"",className:_.submitSlot,onClick:g=>{v&&(g.stopPropagation(),q())},children:H})]})]})});export{At as AIAutocomplete,Ie as AIAutocompleteDropdown,ke as useAIAutocomplete};
693
693
  //# sourceMappingURL=index.mjs.map