@magicx-eng/ai-autocomplete-react 0.1.26 → 0.1.27

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
@@ -1,4 +1,4 @@
1
- import{forwardRef as xt,useCallback as bt,useEffect as _e,useImperativeHandle as vt,useRef as se}from"react";if(typeof document<"u"&&!document.getElementById("ac-style-cc65f4cc")){let o=document.createElement("style");o.id="ac-style-cc65f4cc",o.textContent=`.AIAutocomplete-module_container_KKjFU {
1
+ import{forwardRef as St,useCallback as It,useEffect as Te,useImperativeHandle as _t,useRef as ce}from"react";if(typeof document<"u"&&!document.getElementById("ac-style-cc65f4cc")){let o=document.createElement("style");o.id="ac-style-cc65f4cc",o.textContent=`.AIAutocomplete-module_container_KKjFU {
2
2
  position: relative;
3
3
  font-family: "IBM Plex Sans", sans-serif;
4
4
  container-type: inline-size;
@@ -142,7 +142,7 @@ import{forwardRef as xt,useCallback as bt,useEffect as _e,useImperativeHandle as
142
142
  .AIAutocomplete-module_shimmerHidden_45-Pf {
143
143
  color: transparent !important;
144
144
  }
145
- `,document.head.appendChild(o)}var _={container:"AIAutocomplete-module_container_KKjFU",inputWrapper:"AIAutocomplete-module_inputWrapper_FLq1b",editorArea:"AIAutocomplete-module_editorArea_7rBWq",sizerContent:"AIAutocomplete-module_sizerContent_DQgmV",sizerText:"AIAutocomplete-module_sizerText_iZIMK",sizerTextVisible:"AIAutocomplete-module_sizerTextVisible_HR-5h",textareaHidden:"AIAutocomplete-module_textareaHidden_UayJt",placeholderText:"AIAutocomplete-module_placeholderText_K3ayy",textarea:"AIAutocomplete-module_textarea_eyn6A",submitButton:"AIAutocomplete-module_submitButton_sl1Mi",shimmer:"AIAutocomplete-module_shimmer_13AnY",shimmerRevealed:"AIAutocomplete-module_shimmerRevealed_RR8dp",shimmerSweep:"AIAutocomplete-module_shimmerSweep_ARCon",textShimmer:"AIAutocomplete-module_textShimmer_eCLdq",shimmerHidden:"AIAutocomplete-module_shimmerHidden_45-Pf"};if(typeof document<"u"&&!document.getElementById("ac-style-2eef895d")){let o=document.createElement("style");o.id="ac-style-2eef895d",o.textContent=`.AIAutocompleteDropdown-module_dropdown_yz2KC {
145
+ `,document.head.appendChild(o)}var C={container:"AIAutocomplete-module_container_KKjFU",inputWrapper:"AIAutocomplete-module_inputWrapper_FLq1b",editorArea:"AIAutocomplete-module_editorArea_7rBWq",sizerContent:"AIAutocomplete-module_sizerContent_DQgmV",sizerText:"AIAutocomplete-module_sizerText_iZIMK",sizerTextVisible:"AIAutocomplete-module_sizerTextVisible_HR-5h",textareaHidden:"AIAutocomplete-module_textareaHidden_UayJt",placeholderText:"AIAutocomplete-module_placeholderText_K3ayy",textarea:"AIAutocomplete-module_textarea_eyn6A",submitButton:"AIAutocomplete-module_submitButton_sl1Mi",shimmer:"AIAutocomplete-module_shimmer_13AnY",shimmerRevealed:"AIAutocomplete-module_shimmerRevealed_RR8dp",shimmerSweep:"AIAutocomplete-module_shimmerSweep_ARCon",textShimmer:"AIAutocomplete-module_textShimmer_eCLdq",shimmerHidden:"AIAutocomplete-module_shimmerHidden_45-Pf"};if(typeof document<"u"&&!document.getElementById("ac-style-2eef895d")){let o=document.createElement("style");o.id="ac-style-2eef895d",o.textContent=`.AIAutocompleteDropdown-module_dropdown_yz2KC {
146
146
  position: absolute;
147
147
  left: 0;
148
148
  top: 100%;
@@ -178,7 +178,7 @@ import{forwardRef as xt,useCallback as bt,useEffect as _e,useImperativeHandle as
178
178
  .AIAutocompleteDropdown-module_pillBar_pwTXe {
179
179
  padding: 27px 27px 0px 27px;
180
180
  }
181
- `,document.head.appendChild(o)}var j={dropdown:"AIAutocompleteDropdown-module_dropdown_yz2KC",visible:"AIAutocompleteDropdown-module_visible_QCoXj",pillBar:"AIAutocompleteDropdown-module_pillBar_pwTXe"};if(typeof document<"u"&&!document.getElementById("ac-style-b745b4fb")){let o=document.createElement("style");o.id="ac-style-b745b4fb",o.textContent=`.PillList-module_list_qvLqO {
181
+ `,document.head.appendChild(o)}var Z={dropdown:"AIAutocompleteDropdown-module_dropdown_yz2KC",visible:"AIAutocompleteDropdown-module_visible_QCoXj",pillBar:"AIAutocompleteDropdown-module_pillBar_pwTXe"};if(typeof document<"u"&&!document.getElementById("ac-style-b745b4fb")){let o=document.createElement("style");o.id="ac-style-b745b4fb",o.textContent=`.PillList-module_list_qvLqO {
182
182
  position: relative;
183
183
  z-index: 1;
184
184
  pointer-events: auto;
@@ -241,7 +241,7 @@ import{forwardRef as xt,useCallback as bt,useEffect as _e,useImperativeHandle as
241
241
  opacity: 0;
242
242
  }
243
243
  }
244
- `,document.head.appendChild(o)}var $={list:"PillList-module_list_qvLqO",pill:"PillList-module_pill_osSyz",fadeIn:"PillList-module_fadeIn_Aezob",rounded:"PillList-module_rounded_WvXy4",active:"PillList-module_active_Oll--"};import{jsx as Ce}from"react/jsx-runtime";function Ve(o){return o===0?.4:o===1?.3:.15}function G({pills:o,activePillIndex:e,onSelectPill:t,rounded:i}){return Ce("span",{className:$.list,children:o.map((s,n)=>Ce("button",{type:"button","data-aia-pill":"",className:`${$.pill} ${i?$.rounded:""} ${n===e?$.active:""}`,style:{opacity:Ve(n)},onClick:()=>t(n),children:s.text},`${s.type}-${s.text}`))})}import{useEffect as je,useLayoutEffect as Ge,useRef as Xe,useState as Je}from"react";if(typeof document<"u"&&!document.getElementById("ac-style-d91f2b06")){let o=document.createElement("style");o.id="ac-style-d91f2b06",o.textContent=`.SuggestionGrid-module_scrollWrapper_MOqfw {
244
+ `,document.head.appendChild(o)}var V={list:"PillList-module_list_qvLqO",pill:"PillList-module_pill_osSyz",fadeIn:"PillList-module_fadeIn_Aezob",rounded:"PillList-module_rounded_WvXy4",active:"PillList-module_active_Oll--"};import{jsx as Oe}from"react/jsx-runtime";function Ge(o){return o===0?.4:o===1?.3:.15}function ee({pills:o,activePillIndex:e,onSelectPill:t,rounded:i}){return Oe("span",{className:V.list,children:o.map((r,n)=>Oe("button",{type:"button","data-aia-pill":"",className:`${V.pill} ${i?V.rounded:""} ${n===e?V.active:""}`,style:{opacity:Ge(n)},onClick:()=>t(n),children:r.text},`${r.type}-${r.text}`))})}import{useEffect as Ze,useLayoutEffect as et,useRef as tt,useState as ot}from"react";if(typeof document<"u"&&!document.getElementById("ac-style-d91f2b06")){let o=document.createElement("style");o.id="ac-style-d91f2b06",o.textContent=`.SuggestionGrid-module_scrollWrapper_MOqfw {
245
245
  position: relative;
246
246
  }
247
247
 
@@ -293,7 +293,7 @@ import{forwardRef as xt,useCallback as bt,useEffect as _e,useImperativeHandle as
293
293
  background: var(--aia-scrollbar-thumb, rgba(0, 0, 0, 0.3));
294
294
  border-radius: 3px;
295
295
  }
296
- `,document.head.appendChild(o)}var ge={scrollWrapper:"SuggestionGrid-module_scrollWrapper_MOqfw",grid:"SuggestionGrid-module_grid_jvaPb"};import{useEffect as Ue,useRef as Qe,useState as We}from"react";if(typeof document<"u"&&!document.getElementById("ac-style-f6bdc634")){let o=document.createElement("style");o.id="ac-style-f6bdc634",o.textContent=`.SuggestionItem-module_item_d4vpD {
296
+ `,document.head.appendChild(o)}var ve={scrollWrapper:"SuggestionGrid-module_scrollWrapper_MOqfw",grid:"SuggestionGrid-module_grid_jvaPb"};import{useEffect as Xe,useRef as Je,useState as Ye}from"react";if(typeof document<"u"&&!document.getElementById("ac-style-f6bdc634")){let o=document.createElement("style");o.id="ac-style-f6bdc634",o.textContent=`.SuggestionItem-module_item_d4vpD {
297
297
  position: relative;
298
298
  overflow: visible;
299
299
  display: flex;
@@ -604,7 +604,7 @@ import{forwardRef as xt,useCallback as bt,useEffect as _e,useImperativeHandle as
604
604
  box-shadow: 0 0 24px 10px rgba(var(--aia-streak-rgb, 255, 255, 255), 0.02);
605
605
  }
606
606
  }
607
- `,document.head.appendChild(o)}var A={item:"SuggestionItem-module_item_d4vpD",fadeIn:"SuggestionItem-module_fadeIn_I8u35",content:"SuggestionItem-module_content_T-Qba",tappable:"SuggestionItem-module_tappable_70KcX",nonTappable:"SuggestionItem-module_nonTappable_xSZM-",highlighted:"SuggestionItem-module_highlighted_Hb0SU",tag:"SuggestionItem-module_tag_e3Fwe",pressed:"SuggestionItem-module_pressed_98o-r",glassFade:"SuggestionItem-module_glassFade_oyiSj",tapDown:"SuggestionItem-module_tapDown_G3WGz",streaks:"SuggestionItem-module_streaks_d9PEB",streaksVert:"SuggestionItem-module_streaksVert_ERlV1",streakHorizRight:"SuggestionItem-module_streakHorizRight_aboGz",streakHorizLeft:"SuggestionItem-module_streakHorizLeft_BreWJ",streakVertUp:"SuggestionItem-module_streakVertUp_to1GD",streakVertDown:"SuggestionItem-module_streakVertDown_OrcLh"};import{jsx as fe,jsxs as Pe}from"react/jsx-runtime";function Ae({option:o,isHighlighted:e,onSelect:t,onHighlight:i,id:s}){let[n,a]=We(!1),d=Qe(void 0);Ue(()=>()=>clearTimeout(d.current),[]);let r=()=>{!o.is_tappable||n||(a(!0),t(o),clearTimeout(d.current),d.current=setTimeout(()=>a(!1),400))},l=[A.item,e?A.highlighted:"",o.is_tappable?A.tappable:A.nonTappable,n?A.pressed:""].filter(Boolean).join(" ");return Pe("div",{id:s,role:"option","data-aia-option":"","aria-selected":e,className:l,tabIndex:o.is_tappable?0:-1,onClick:r,onKeyDown:p=>{o.is_tappable&&(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),r())},onMouseEnter:o.is_tappable?i:void 0,children:[fe("div",{className:A.streaks}),fe("div",{className:A.streaksVert}),Pe("span",{className:A.content,children:[o.icon?`${o.icon} ${o.text}`:o.text,o.tag&&fe("span",{className:A.tag,children:o.tag})]})]})}import{jsx as he}from"react/jsx-runtime";function ke({options:o,activeIndex:e,onSelect:t,onHighlight:i,listboxId:s}){let n=Xe(null),[a,d]=Je(!1);return je(()=>{let r=n.current;if(!r)return;let l=()=>{d(r.scrollHeight-r.scrollTop-r.clientHeight>1)};r.addEventListener("scroll",l,{passive:!0});let p=new ResizeObserver(l);return p.observe(r),()=>{r.removeEventListener("scroll",l),p.disconnect()}},[]),Ge(()=>{let r=n.current;r&&d(r.scrollHeight-r.scrollTop-r.clientHeight>1)},[o]),he("div",{className:ge.scrollWrapper,"data-fade":a?"":void 0,children:he("div",{ref:n,className:ge.grid,children:o.map((r,l)=>he(Ae,{option:r,isHighlighted:l===e,onSelect:t,onHighlight:()=>i(l),id:`${s}-option-${l}`},r.text))})})}import{jsx as xe,jsxs as Ye}from"react/jsx-runtime";function be({suggestions:o,activeIndex:e,onSelect:t,onHighlight:i,isOpen:s,id:n,className:a,pills:d,onPillClick:r,showPills:l=!0}){let c=o[0]?.options??[],m=l&&d&&d.length>0&&r,g=s&&c.length>0||s&&m;return Ye("div",{id:n,role:"listbox","data-aia-dropdown":"",className:`${j.dropdown} ${g?j.visible:""} ${a??""}`,onMouseDown:S=>S.preventDefault(),children:[m&&xe("div",{className:j.pillBar,"data-aia-pillbar":"",children:xe(G,{pills:d,activePillIndex:0,onSelectPill:r,rounded:!0})}),c.length>0&&xe(ke,{options:c,activeIndex:e,onSelect:t,onHighlight:i,listboxId:n})]})}if(typeof document<"u"&&!document.getElementById("ac-style-dc8da745")){let o=document.createElement("style");o.id="ac-style-dc8da745",o.textContent=`/*
607
+ `,document.head.appendChild(o)}var k={item:"SuggestionItem-module_item_d4vpD",fadeIn:"SuggestionItem-module_fadeIn_I8u35",content:"SuggestionItem-module_content_T-Qba",tappable:"SuggestionItem-module_tappable_70KcX",nonTappable:"SuggestionItem-module_nonTappable_xSZM-",highlighted:"SuggestionItem-module_highlighted_Hb0SU",tag:"SuggestionItem-module_tag_e3Fwe",pressed:"SuggestionItem-module_pressed_98o-r",glassFade:"SuggestionItem-module_glassFade_oyiSj",tapDown:"SuggestionItem-module_tapDown_G3WGz",streaks:"SuggestionItem-module_streaks_d9PEB",streaksVert:"SuggestionItem-module_streaksVert_ERlV1",streakHorizRight:"SuggestionItem-module_streakHorizRight_aboGz",streakHorizLeft:"SuggestionItem-module_streakHorizLeft_BreWJ",streakVertUp:"SuggestionItem-module_streakVertUp_to1GD",streakVertDown:"SuggestionItem-module_streakVertDown_OrcLh"};import{jsx as ye,jsxs as De}from"react/jsx-runtime";function Ee({option:o,isHighlighted:e,onSelect:t,onHighlight:i,id:r}){let[n,a]=Ye(!1),p=Je(void 0);Xe(()=>()=>clearTimeout(p.current),[]);let s=()=>{!o.is_tappable||n||(a(!0),t(o),clearTimeout(p.current),p.current=setTimeout(()=>a(!1),400))},l=[k.item,e?k.highlighted:"",o.is_tappable?k.tappable:k.nonTappable,n?k.pressed:""].filter(Boolean).join(" ");return De("div",{id:r,role:"option","data-aia-option":"","aria-selected":e,className:l,tabIndex:o.is_tappable?0:-1,onClick:s,onKeyDown:d=>{o.is_tappable&&(d.key==="Enter"||d.key===" ")&&(d.preventDefault(),s())},onMouseEnter:o.is_tappable?i:void 0,children:[ye("div",{className:k.streaks}),ye("div",{className:k.streaksVert}),De("span",{className:k.content,children:[o.icon?`${o.icon} ${o.text}`:o.text,o.tag&&ye("span",{className:k.tag,children:o.tag})]})]})}import{jsx as we}from"react/jsx-runtime";function Le({options:o,activeIndex:e,onSelect:t,onHighlight:i,listboxId:r}){let n=tt(null),[a,p]=ot(!1);return Ze(()=>{let s=n.current;if(!s)return;let l=()=>{p(s.scrollHeight-s.scrollTop-s.clientHeight>1)};s.addEventListener("scroll",l,{passive:!0});let d=new ResizeObserver(l);return d.observe(s),()=>{s.removeEventListener("scroll",l),d.disconnect()}},[]),et(()=>{let s=n.current;s&&p(s.scrollHeight-s.scrollTop-s.clientHeight>1)},[o]),we("div",{className:ve.scrollWrapper,"data-fade":a?"":void 0,children:we("div",{ref:n,className:ve.grid,children:o.map((s,l)=>we(Ee,{option:s,isHighlighted:l===e,onSelect:t,onHighlight:()=>i(l),id:`${r}-option-${l}`},s.text))})})}import{jsx as Se,jsxs as it}from"react/jsx-runtime";function Ie({suggestions:o,activeIndex:e,onSelect:t,onHighlight:i,isOpen:r,id:n,className:a,pills:p,onPillClick:s,showPills:l=!0}){let c=o[0]?.options??[],m=l&&p&&p.length>0&&s,g=r&&c.length>0||r&&m;return it("div",{id:n,role:"listbox","data-aia-dropdown":"",className:`${Z.dropdown} ${g?Z.visible:""} ${a??""}`,onMouseDown:y=>y.preventDefault(),children:[m&&Se("div",{className:Z.pillBar,"data-aia-pillbar":"",children:Se(ee,{pills:p,activePillIndex:0,onSelectPill:s,rounded:!0})}),c.length>0&&Se(Le,{options:c,activeIndex:e,onSelect:t,onHighlight:i,listboxId:n})]})}if(typeof document<"u"&&!document.getElementById("ac-style-dc8da745")){let o=document.createElement("style");o.id="ac-style-dc8da745",o.textContent=`/*
608
608
  * Built-in appearance defaults \u2014 zero specificity via :where().
609
609
  * Consumer CSS always wins without !important.
610
610
  *
@@ -683,5 +683,5 @@ import{forwardRef as xt,useCallback as bt,useEffect as _e,useImperativeHandle as
683
683
  animation-duration: 0s !important;
684
684
  transition-duration: 0s !important;
685
685
  }
686
- `,document.head.appendChild(o)}import{useCallback as C,useEffect as re,useRef as E,useState as ht}from"react";function q(o,e,t){let i=o.slice(e);if(t||e===0||o[e-1]===" ")return i;let s=i.indexOf(" ");return s===-1?"":i.slice(s+1)}function Te(o,e){let t=o.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let i=t.split(" "),s=e.toLowerCase();for(let n=0;n<i.length;n++){let a=i.slice(n).join(" ");if(s.startsWith(a.toLowerCase())){let d=t.length-a.length;return o.length-d}}return 0}function X(o,e){if(!o)return[];let t=e.trimStart();if(!t)return o;let i=t.toLowerCase();return o.filter(s=>!s.is_tappable||s.text.toLowerCase().includes(i))}function ve(o,e){if(!o)return null;let t=e.trim();if(!t)return null;let i=t.toLowerCase();return o.find(s=>s.is_tappable&&s.text.toLowerCase()===i)??null}var z=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 Oe(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 s=o.slice(i);return s&&t.push({type:"text",value:s}),t}function De(o,e){let t=[],i=[],s=0;for(let n of e){let a=o.indexOf(n.text,s);a===-1?i.push(n):(t.push(n),s=a+n.text.length)}return{valid:t,invalid:i}}var J=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 Ze="0.1.26",Ee=!1;function et(){return crypto.randomUUID()}function tt(o,e){return{placeholder:o.placeholder,type:o.type,...e&&{text:o.text},kind:o.kind}}function Me(o){return o?.type==="accessToken"}function ot(o){if(!(!o||Me(o)))return o}var Le=new WeakMap;function it(o){let e=Le.get(o.getAccessToken);return e||(e=new J(o),Le.set(o.getAccessToken,e)),e}function nt(o,e,t){let i=e.find(n=>n.type==="contact"&&n.metadata?.contact_account_count)?.metadata?.contact_account_count,s=typeof i=="number"?i:void 0;return{data:{raw_query:o,completed_params:e.map(n=>tt(n,t)),...s!=null&&{contact_account_count:s}},meta:{request_id:et(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:Ze}}}function rt(o){return{"Content-Type":"application/json",...o?.appIdentifier&&{"X-App-Identifier":o.appIdentifier},...o?.headers}}async function Re(o,e,t,i,s){return fetch(o,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:s})}async function He(o,e,t){let i=t?.apiConfig,s=!t?.maskCompletedText,n=nt(o,e,s),a=rt(i),d=i?.endpoint??"/ac/suggest",r=JSON.stringify(n);if(Me(i)){let m=it(i),h=await m.getToken(),g=await Re(d,a,h,r,t?.signal);if(g.status===401){let S=await m.getToken(!0);g=await Re(d,a,S,r,t?.signal)}if(!g.ok)throw new Error(`API error: ${g.status} ${g.statusText}`);return g.json()}let l=ot(i),p=l?.apiKey??"";if(!p&&!Ee&&(Ee=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),p){let m=l?.authScheme??"Bearer";a.Authorization=m==="Basic"?`Basic ${btoa(p)}`:`Bearer ${p}`}let c=await fetch(d,{method:"POST",headers:a,body:r,signal:t?.signal});if(!c.ok)throw new Error(`API error: ${c.status} ${c.statusText}`);return c.json()}function T(o,e){let t=o,i={},s=[];for(let n of e){let a=(i[n.type]??0)+1;i[n.type]=a;let r=`{{${n.type.toUpperCase().replace(/\s+/g,"_")}_${a}}}`,l=t.indexOf(n.text);l!==-1&&(t=t.slice(0,l)+r+t.slice(l+n.text.length)),s.push({...n,placeholder:r})}return{rawQuery:t,completedParams:s}}function ze(o,e){return e?o.map(t=>{let i=e[t.type];if(!i)return t;let s=i("");if(s.length===0)return t;let n=new Set(s.map(d=>d.text)),a=(t.options??[]).filter(d=>!n.has(d.text));return{...t,options:[...s,...a]}}):o}var st=100,at=300,lt=2,Y=class{constructor(e,t,i,s,n){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=s;this.getOnError=n;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 s=++this.fetchVersion,n=this.store.get(),a=n.text.length;n.suggestions.some(r=>r.type!=="placeholder")||this.store.set({isLoading:!0}),this.store.set({error:null});try{let r=await He(e,t,{maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig()});if(s!==this.fetchVersion)return;let l=ze(r.data.suggestions??[],this.getOptionOverrides()),p=r.data.input??[],c=p[p.length-1],m=this.store.get().text,h,g;if(c?.state==="in_progress"){g=!0;let u=m.toLowerCase().lastIndexOf(c.text.toLowerCase());h=u!==-1?u:a}else g=!1,h=a;let x=l.filter(u=>u.type!=="placeholder")[0],I=null;if(x){let u=q(m,h,g),v=ve(x.options,u);v&&(I={id:crypto.randomUUID(),placeholder:"",type:x.type,text:v.text,kind:v.kind,suggestionType:x.type,suggestionPlaceholder:x.text,options:x.options??[],metadata:v.metadata},l=l.filter(L=>L!==x))}this.store.set(u=>({suggestions:l,isLoading:!1,isReady:r.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:h,filterInProgress:g,...I?{completedParams:[...u.completedParams,I]}:{}}))}catch(r){if(s===this.fetchVersion){let l=r instanceof Error?r:new Error(String(r));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 s=this.store.get();if(!s.text&&s.completedParams.length===0)return this.doFetch("",[]),!0;let n=q(s.text,s.filterBase,s.filterInProgress),d=s.suggestions.filter(x=>x.type!=="placeholder")[0],l=(d?X(d.options,n):[]).filter(x=>x.is_tappable),p=d?ve(d.options,n)!==null:!1,c=n.trim().length>0;if(l.length>0&&!p&&c)return!1;if(s.completedParams.length===0&&s.text.length>0){let x=s.suggestions.filter(I=>I.type==="placeholder").map(I=>I.text).join(" ");if(x.length>0&&x.toLowerCase().startsWith(s.text.toLowerCase()))return!1}let{rawQuery:m,completedParams:h}=T(s.text,s.completedParams),g=m.length<s.lastRawQuery.length,S=Math.abs(m.length-s.lastRawQuery.length);return g||S>=i?(this.doFetch(m,h),!0):!1};this.debounceTimer=setTimeout(()=>{t(lt)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},st),this.slowDebounceTimer=setTimeout(()=>t(1),at)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var Z=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:s}=this.ctx,n=this.getEffectiveColumns(),a=s(),d=this.getTappableIndices(n);switch(e.key){case"ArrowDown":{let r=e.target;if(!(r.selectionStart!=null&&r.selectionStart===r.value.length)&&t.activeDropdownIndex<0)break;if(e.preventDefault(),!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:d[0]??0});break}if(d.length===0)return;let p=d.indexOf(t.activeDropdownIndex),c=p<d.length-1?p+1:0;this.store.set({activeDropdownIndex:d[c]});break}case"ArrowUp":{if(d.length===0||t.activeDropdownIndex<0)break;if(e.preventDefault(),t.activeDropdownIndex<n){this.store.set({activeDropdownIndex:-1});break}let r=d.indexOf(t.activeDropdownIndex),l=r>0?r-1:d.length-1;this.store.set({activeDropdownIndex:d[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 r=t.activeDropdownIndex-1;r>=0&&t.filteredOptions[r]?.is_tappable&&(e.preventDefault(),this.store.set({activeDropdownIndex:r}))}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:r,completedParams:l}=T(t.text,t.completedParams);a({query:t.text.trim(),raw_query:r,completed_params:l})}break}case"Tab":{let r=!t.text&&!!t.placeholderText,l=t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable;if(r&&!l){e.preventDefault();let p=t.suggestions.find(c=>c.type==="placeholder");p?this.store.set(c=>({text:t.placeholderText,filterBase:t.placeholderText.length,completedParams:[...c.completedParams,{id:crypto.randomUUID(),placeholder:"",type:p.type,text:t.placeholderText,kind:null,suggestionType:p.type,suggestionPlaceholder:p.text,options:p.options??[]}],suggestions:c.suggestions.filter(m=>m!==p)})):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 p=t.filteredOptions.findIndex(c=>c.is_tappable);p>=0&&(e.preventDefault(),this.clickOrSelect(p,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),s=Array.from({length:e},()=>[]);for(let n of i)s[n%e].push(n);return s.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 s=document.getElementById(`${i}-option-${e}`);s?s.click():this.ctx.selectOption(t[e])}pillsSetActivePill(e){let t=this.store.get(),i=t.suggestions.filter(d=>d.type!=="placeholder");if(e<0||e>=i.length)return;let s=i[e],n=i.filter((d,r)=>r!==e),a=t.suggestions.filter(d=>d.type==="placeholder");this.store.set({suggestions:[...a,s,...n],pillTapped:!0,activeDropdownIndex:-1})}};var ee=class{constructor(e){this.store=e}setActivePill(e){let t=this.store.get(),i=t.suggestions.filter(d=>d.type!=="placeholder");if(e<0||e>=i.length)return;let s=i[e],n=i.filter((d,r)=>r!==e),a=t.suggestions.filter(d=>d.type==="placeholder");this.store.set({suggestions:[...a,s,...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(s=>({completedParams:s.completedParams.slice(0,-1),suggestions:[i,...s.suggestions],activeDropdownIndex:-1}))}};function dt(o){return o===0?.4:o===1?.3:.15}function te(o,e,t,i,s=!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 r of n.querySelectorAll(".magicx-aia-pill"))a.set(r.dataset.pillKey??"",r);let d=new Set;for(let r=0;r<e.length;r++){let l=e[r],p=`${l.type}-${l.text}`;d.add(p);let c=a.get(p);c||(c=document.createElement("button"),c.type="button",c.dataset.pillKey=p,c.setAttribute("data-aia-pill",""),c.textContent=l.text),c.className=`magicx-aia-pill${s?" magicx-aia-pill--rounded":""}${r===t?" magicx-aia-pill--active":""}`,c.style.opacity=String(dt(r)),c.onclick=()=>i(r),n.children[r]!==c&&n.insertBefore(c,n.children[r]??null)}for(let[r,l]of a)d.has(r)||l.remove()}function oe(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 ie(o,e){let{filteredOptions:t,activeIndex:i,isOpen:s,pills:n,showPills:a,onSelect:d,onHighlight:r,onPillClick:l}=e,p=a&&n.length>0;s&&t.length>0||s&&p?o.classList.add("magicx-aia-dropdown--visible"):o.classList.remove("magicx-aia-dropdown--visible");let h=o.querySelector(".magicx-aia-pill-bar");p?(h||(h=document.createElement("div"),h.className="magicx-aia-pill-bar",h.setAttribute("data-aia-pillbar",""),o.insertBefore(h,o.firstChild)),te(h,n,0,l,!0)):h&&h.remove();let g=o.querySelector(".magicx-aia-grid");t.length>0?(g||(g=document.createElement("div"),g.className="magicx-aia-grid",o.appendChild(g)),pt(g,t,i,d,r,e.listboxId)):g&&(g.innerHTML="")}function pt(o,e,t,i,s,n){let a=e.map(l=>l.text).join("\0"),d=o.dataset.optionsKey??"",r=a!==d;if(o.dataset.optionsKey=a,r){let l=document.createDocumentFragment();for(let p=0;p<e.length;p++){let c=e[p],m=ct(c,p,t,i,s,n);l.appendChild(m)}o.innerHTML="",o.appendChild(l)}else{let l=o.querySelectorAll(".magicx-aia-option");for(let p=0;p<l.length;p++){let c=l[p],m=p===t;c.setAttribute("aria-selected",String(m)),m?c.classList.add("magicx-aia-option--highlighted"):c.classList.remove("magicx-aia-option--highlighted")}}}function ct(o,e,t,i,s,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 d=["magicx-aia-option"];e===t&&d.push("magicx-aia-option--highlighted"),o.is_tappable?d.push("magicx-aia-option--tappable"):d.push("magicx-aia-option--non-tappable"),a.className=d.join(" ");let r=document.createElement("div");r.className="magicx-aia-streaks",a.appendChild(r);let l=document.createElement("div");l.className="magicx-aia-streaks-vert",a.appendChild(l);let p=document.createElement("span");if(p.className="magicx-aia-option-content",p.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,p.appendChild(c)}return a.appendChild(p),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",()=>s(e))),a}function Be(o,e){let t=oe(e.listboxId);return o.appendChild(t),{dropdown:t}}function ye(o,e,t){ie(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 Ne(o,e,t,i,s){let n=o.querySelector(".magicx-aia-sizer-text"),a=o.querySelector(".magicx-aia-placeholder");if(i&&s){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=`${s} `,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 d=e.map(p=>`${p.type}:${p.value}`).join("\0"),r=o.dataset.segmentKey??"",l=o.dataset.newParamId??"";if(!(d===r&&(t??"")===l)){o.dataset.segmentKey=d,o.dataset.newParamId=t??"",n.innerHTML="";for(let p of e){let c=document.createElement("span");p.type==="completed"&&(p.param.id===t?c.className="magicx-aia-shimmer-revealed magicx-aia-shimmer-sweep":c.className="magicx-aia-segment magicx-aia-segment--completed"),c.textContent=p.value,n.appendChild(c)}e.length===0&&(n.textContent="\xA0")}}var ut='<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 Ke(o,e){let{listboxId:t}=e,i=oe(t);o.appendChild(i);let s=document.createElement("div");s.className="magicx-aia-input-wrapper",o.appendChild(s);let n=document.createElement("div");n.className="magicx-aia-editor",n.setAttribute("data-aia-editor",""),s.appendChild(n);let a=document.createElement("div");a.className="magicx-aia-sizer",a.setAttribute("aria-hidden","true"),n.appendChild(a);let d=document.createElement("span");a.appendChild(document.createTextNode(" ")),a.appendChild(d);let r=document.createElement("textarea");r.className="magicx-aia-textarea",r.rows=1,r.setAttribute("role","combobox"),r.setAttribute("aria-autocomplete","list"),r.setAttribute("aria-controls",t),r.setAttribute("data-aia-textarea",""),n.appendChild(r);let l=document.createElement("button");return l.type="button",l.className="magicx-aia-submit",l.setAttribute("aria-label","Submit"),l.setAttribute("data-aia-submit",""),l.innerHTML=ut,s.appendChild(l),s.addEventListener("click",()=>r.focus()),r.addEventListener("input",()=>{let p=r.value,m=p.length>0&&p[0]!==p[0].toUpperCase()?p[0].toUpperCase()+p.slice(1):p;e.handleChange(m)}),r.addEventListener("keydown",p=>e.handleKeyDown(p)),r.addEventListener("focus",()=>e.store.set({isFocused:!0})),r.addEventListener("blur",()=>e.store.set({isFocused:!1})),l.addEventListener("click",p=>{p.stopPropagation();let c=e.store.get();if(!(!!c.text||c.completedParams.length>0)||!e.onSubmit)return;let{rawQuery:h,completedParams:g}=T(c.text,c.completedParams);e.onSubmit({query:c.text.trim(),raw_query:h,completed_params:g})}),r.focus(),{textarea:r,dropdown:i,sizer:a,submitButton:l,inlinePillContainer:d}}function we(o,e,t){let{textarea:i,dropdown:s,sizer:n,submitButton:a,inlinePillContainer:d}=o,{pillPlacement:r,setActivePill:l,selectOption:p,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 m=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";m?i.setAttribute("aria-activedescendant",m):i.removeAttribute("aria-activedescendant"),e.newParamId?i.classList.add("magicx-aia-textarea--hidden"):i.classList.remove("magicx-aia-textarea--hidden");let h=!!e.text||e.completedParams.length>0;a.disabled=!h,Ne(n,e.segments,e.newParamId,!e.text,e.placeholderText),r==="inline"?te(d,e.actionableSuggestions,0,l):d.innerHTML="",ie(s,{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:r==="dropdown",onSelect:p,onHighlight:g=>c.set({activeDropdownIndex:g}),onPillClick:l})}function Fe(o){let e=o,t=new Set;return{get:()=>e,set:i=>{let s=typeof i=="function"?i(e):i,n={...e,...s},a=e;e=n;for(let d of t)d(n,a)},subscribe:i=>(t.add(i),()=>{t.delete(i)})}}var Se=!1;function $e(){if(Se||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){Se=!0;return}Se=!0;let o=document.createElement("style");o.setAttribute("data-magicx-aia",""),o.textContent=mt,document.head.appendChild(o)}var mt="";var gt=0;function ft(){return`:ac-${++gt}:`}function qe(){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 ne=class{constructor(e,t={}){this.store=Fe(qe());this._listboxId=ft();this.modeController=null;this.unsubscribers=[];this.derivedInProgress=!1;this.domRefs=null;this.dropdownRefs=null;this.externalListeners=new Set;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 ee(this.store),this.fetchController=new Y(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.opts.onError),this.keyboardController=new Z(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,s)=>{this.recomputeDerived(i,s)})),this.unsubscribers.push(this.store.subscribe((i,s)=>{i.text!==s.text&&this.opts.onChange?.(i.text),i.completedParams!==s.completedParams&&this.opts.onParamsChange?.(i.completedParams),this.opts.onStateChange?.(i)})),this.renderMode!=="headless"&&($e(),this.setupContainer()),this.renderMode==="full"?this.buildAndRenderFull():this.renderMode==="dropdown"&&this.buildAndRenderDropdown(),this.fetchController.start()}focus(){this.domRefs?.textarea.focus()}reset(){this.store.set({...qe()}),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};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&&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 s=t.filterBase,n=t.text.slice(0,s),a=n.length===0&&t.text.length===0,d=n.length===0&&t.text.length>0&&t.placeholderText.length>0&&t.placeholderText.toLowerCase().startsWith(t.text.toLowerCase());(a||d)&&t.placeholderText&&(n=`${t.placeholderText} `);let r=Te(n,e.text);r>0&&(n=n.slice(0,n.length-r));let l=n.length>0&&n[n.length-1]!==" ",p=`${n}${l?" ":""}${e.text} `,c=(a||d)&&p.length>0?p[0].toUpperCase()+p.slice(1):p,m=c.toLowerCase().lastIndexOf(e.text.toLowerCase()),h=m>=0?c.slice(m,m+e.text.length):e.text,g={id:crypto.randomUUID(),placeholder:"",type:i.type,text:h,kind:e.kind,suggestionType:i.type,suggestionPlaceholder:i.text,options:i.options??[],metadata:e.metadata},S=t.actionableSuggestions.length-1;this.store.set(x=>({text:c,filterBase:c.length,completedParams:[...x.completedParams,g],newParamId:g.id,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:S>0})),this.suggestionRemovalTimer=window.setTimeout(()=>{this.store.set(x=>({suggestions:x.suggestions.filter(I=>I!==i)}))},400)}recomputeDerived(e,t){if(this.derivedInProgress)return;this.derivedInProgress=!0;let i=Oe(e.text,e.completedParams),s=e.suggestions.filter(x=>x.type!=="placeholder"),n=s[0],a=n?this.opts.optionOverrides?.[n.type]:void 0,d=Math.min(e.filterBase,e.text.length),l=e.lastRawQuery!==""||d>0?q(e.text,d,e.filterInProgress):"",p=n?a?a(l.trim()):n.options??[]:[],c=X(p,l),m=e.suggestions.filter(x=>x.type==="placeholder").map(x=>x.text).join(" "),h=this.opts.dropdownTrigger??"auto",g=!1;h==="auto"?g=!e.isLoading&&c.length>0&&e.isFocused:h==="manual"&&(g=!e.isLoading&&c.length>0&&e.pillTapped),this.store.set({segments:i,actionableSuggestions:s,filteredOptions:c,placeholderText:m,isDropdownOpen:g}),this.derivedInProgress=!1;let S=this.store.get();for(let x of this.externalListeners)x(S)}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 z(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},selectOption:i=>this.selectOption(i),setActivePill:i=>this.pillsController.setActivePill(i),handleKeyDown:i=>this.keyboardController.handleKeyDown(i),handleChange:i=>this.handleChange(i)};this.domRefs=Ke(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&we(this.domRefs,this.store.get(),t)}),we(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=Be(this.container,e),this.subscribeBatchedRender(()=>{this.dropdownRefs&&ye(this.dropdownRefs,this.store.get(),e)}),ye(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:s}=De(e,t.completedParams);s.length>0&&this.store.set(n=>({completedParams:i,suggestions:[...s.map(a=>({type:a.suggestionType,text:a.suggestionPlaceholder,required:!0,options:a.options})),...n.suggestions]}))}};function Ie({onSubmit:o,onError:e,optionOverrides:t,maskCompletedText:i,apiConfig:s,columns:n=2,dropdownTrigger:a,value:d,completedParams:r,onChange:l,onParamsChange:p}){let c=E(null),[m,h]=ht(null),g=E(o);g.current=o;let S=E(e);S.current=e;let x=E(l);x.current=l;let I=E(p);I.current=p,re(()=>{if(typeof document>"u")return;let b=new ne(document.createElement("div"),{renderMode:"headless",apiConfig:s,optionOverrides:t,maskCompletedText:i,columns:n,dropdownTrigger:a,value:d,completedParams:r,onSubmit:(...w)=>g.current?.(...w),onError:(...w)=>S.current?.(...w),onChange:(...w)=>x.current?.(...w),onParamsChange:(...w)=>I.current?.(...w)});c.current=b,h(b.getState());let f=b.subscribe(w=>h(w));return()=>{f(),b.destroy(),c.current===b&&(c.current=null)}},[]);let u=c.current,v=C(()=>{},[]);re(()=>{d!==void 0&&u?.setValue(d)},[d,u]),re(()=>{r!==void 0&&u?.setCompletedParams(r)},[r,u]);let L=JSON.stringify(s??null),P=E(t),R=E(0);if(t!==P.current){let b=P.current,f=t,w=Object.keys(b??{}),K=Object.keys(f??{});(w.length!==K.length||K.some(F=>!b?.[F]||f[F]!==b[F]))&&R.current++,P.current=t}re(()=>{u?.update({apiConfig:s,optionOverrides:t,dropdownTrigger:a})},[L,R.current,a,u]);let ae=C(b=>{if(!u)return;let f=b.target.value,K=f.length>0&&!b.nativeEvent?.isComposing&&f[0]!==f[0].toUpperCase()?f[0].toUpperCase()+f.slice(1):f;u.handleTextChange(K)},[u]),le=C(b=>{u?.handleKeyDown(b.nativeEvent)},[u]),V=C(()=>u?.setFocused(!0),[u]),D=C(()=>u?.setFocused(!1),[u]),N=C(b=>u?.setActivePill(b),[u]),k=C(()=>u?.removeLastParam(),[u]),de=C(()=>u?.clearNewParamId(),[u]),M=C(()=>u?.reset(),[u]),U=C(b=>u?.selectOption(b),[u]),pe=C(b=>u?.setActiveDropdownIndex(b),[u]);if(!u)return{completedParams:r??[],suggestionPills:[],setActivePill:v,removeLastParam:v,segments:[],newParamId:null,clearNewParamId:v,suggestions:[],activeIndex:-1,isReady:!1,isLoading:!0,error:null,inputProps:{value:d??"",placeholder:void 0,onChange:v,onKeyDown:v,onFocus:v,onBlur:v,role:"combobox","aria-expanded":!1,"aria-activedescendant":void 0,"aria-autocomplete":"list","aria-controls":""},reset:v,dropdownProps:{suggestions:[],activeIndex:-1,onSelect:v,onHighlight:v,isOpen:!1,id:"",pills:[],onPillClick:v}};let y=m??u.getState(),Q=d!==void 0?d:y.text,ce=r!==void 0?r:y.completedParams,H=y.actionableSuggestions,W=H[0],ue=y.filteredOptions,me=y.activeDropdownIndex>=0?`${u.listboxId}-option-${y.activeDropdownIndex}`:void 0;return{completedParams:ce,suggestionPills:H,setActivePill:N,removeLastParam:k,segments:y.segments,newParamId:y.newParamId,clearNewParamId:de,suggestions:y.suggestions,activeIndex:y.activeDropdownIndex,isReady:y.isReady,isLoading:y.isLoading,error:y.error,inputProps:{value:Q,placeholder:y.placeholderText||void 0,onChange:ae,onKeyDown:le,onFocus:V,onBlur:D,role:"combobox","aria-expanded":y.isDropdownOpen,"aria-activedescendant":me,"aria-autocomplete":"list","aria-controls":u.listboxId},reset:M,dropdownProps:{suggestions:W?[{...W,options:ue}]:[],activeIndex:y.activeDropdownIndex,onSelect:U,onHighlight:pe,isOpen:y.isDropdownOpen,id:u.listboxId,pills:H,onPillClick:N}}}import{jsx as O,jsxs as B}from"react/jsx-runtime";function yt(o){return o!=="auto"?o:typeof window>"u"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}var wt=xt(function({onSubmit:e,onError:t,optionOverrides:i,maskCompletedText:s,className:n,apiConfig:a,columns:d,pillPlacement:r="inline",mode:l="auto",optionsPosition:p="below",animations:c=!0,dropdownTrigger:m,value:h,completedParams:g,onChange:S,onParamsChange:x},I){let u=se(null),v=se(null),L=se(()=>{}),P=se(null);_e(()=>{let f=u.current;if(f)return P.current?P.current.setMode(l):P.current=new z(f,l),()=>{P.current?.destroy(),P.current=null}},[l]);let{completedParams:R,suggestionPills:ae,setActivePill:le,segments:V,newParamId:D,clearNewParamId:N,inputProps:k,dropdownProps:de,reset:M}=Ie({onSubmit:f=>L.current(f),onError:t,optionOverrides:i,maskCompletedText:s,apiConfig:a,columns:d,dropdownTrigger:m,value:h,completedParams:g,onChange:S,onParamsChange:x}),U=k.onFocus;_e(()=>{let f=v.current;f&&(document.activeElement===f?U():f.focus())},[U]),_e(()=>{if(!D)return;let f=window.setTimeout(()=>N(),650);return()=>window.clearTimeout(f)},[D,N]),vt(I,()=>({focus:()=>v.current?.focus(),reset:M,setMode:f=>P.current?.setMode(f)}),[M]);let pe=()=>{v.current?.focus()},y=!!k.value||R.length>0,Q=bt(()=>{if(!y)return;let{rawQuery:f,completedParams:w}=T(k.value,R);e({query:k.value.trim(),raw_query:f,completed_params:w}),M()},[y,k.value,R,e,M]);L.current=Q;let{onChange:ce,placeholder:H,...W}=k,ue=!k.value,me=r==="inline",b=r==="dropdown";return B("div",{ref:u,className:`magicx-aia ${_.container} ${n??""}`,"data-pill-placement":r,"data-options-position":p,"data-animations":c?"on":"off","data-mode":yt(l),children:[O(be,{...de,showPills:b}),B("div",{className:_.inputWrapper,onClick:pe,children:[B("div",{className:_.editorArea,"data-aia-editor":"",children:[B("div",{className:_.sizerContent,"aria-hidden":"true",children:[ue&&H?B("span",{className:_.placeholderText,children:[H," "]}):B("span",{className:`${_.sizerText} ${D?_.sizerTextVisible:""}`,children:[V.map((f,w)=>{if(f.type==="completed"&&f.param.id===D){let F=`${_.shimmerRevealed} ${_.shimmerSweep}`;return O("span",{className:F,children:f.value},`${w}-${f.type}`)}return O("span",{children:f.value},`${w}-${f.type}`)}),V.length===0&&"\xA0"]})," ",me&&O(G,{pills:ae,activePillIndex:0,onSelectPill:le})]}),O("textarea",{ref:v,"data-aia-textarea":"",className:`${_.textarea} ${D?_.textareaHidden:""}`,rows:1,onChange:ce,...W})]}),O("button",{type:"button","data-aia-submit":"",className:_.submitButton,disabled:!y,onClick:f=>{f.stopPropagation(),Q()},"aria-label":"Submit",children:O("svg",{width:"18",height:"18",viewBox:"0 0 18 18",fill:"none",role:"img","aria-label":"Submit",children:O("path",{d:"M9 14V4M9 4L4 9M9 4L14 9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})});export{wt as AIAutocomplete,be as AIAutocompleteDropdown,Ie as useAIAutocomplete};
686
+ `,document.head.appendChild(o)}import{useCallback as P,useEffect as pe,useRef as O,useState as wt}from"react";function U(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 F=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.27",ze=!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 Be=new WeakMap;function lt(o){let e=Be.get(o.getAccessToken);return e||(e=new oe(o),Be.set(o.getAccessToken,e)),e}function dt(o,e,t){let i=e.find(n=>n.type==="contact"&&n.metadata?.contact_account_count)?.metadata?.contact_account_count,r=typeof i=="number"?i:void 0;return{data:{raw_query:o,completed_params:e.map(n=>st(n,t)),...r!=null&&{contact_account_count:r}},meta:{request_id:rt(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:nt}}}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),a=pt(i),p=i?.endpoint??"/ac/suggest",s=JSON.stringify(n);if(Ne(i)){let m=lt(i),h=await m.getToken(),g=await Fe(p,a,h,s,t?.signal);if(g.status===401){let y=await m.getToken(!0);g=await Fe(p,a,y,s,t?.signal)}if(!g.ok)throw new Error(`API error: ${g.status} ${g.statusText}`);return g.json()}let l=at(i),d=l?.apiKey??"";if(!d&&!ze&&(ze=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),d){let m=l?.authScheme??"Bearer";a.Authorization=m==="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 E(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){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=r;this.getOnError=n;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,{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],m=this.store.get().text,h,g;if(c?.state==="in_progress"){g=!0;let I=m.toLowerCase().lastIndexOf(c.text.toLowerCase());h=I!==-1?I:a}else g=!1,h=a;let x=l.filter(I=>I.type!=="placeholder")[0],b=null;if(x){let I=U(m,h,g),T=_e(x.options,I);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(H=>H!==x))}this.store.set(I=>({suggestions:l,isLoading:!1,isReady:s.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:h,filterInProgress:g,...b?{completedParams:[...I.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=U(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:m,completedParams:h}=E(r.text,r.completedParams),g=m.length<r.lastRawQuery.length,y=Math.abs(m.length-r.lastRawQuery.length);return g||y>=i?(this.doFetch(m,h),!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}=E(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(m=>m!==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 h=o.querySelector(".magicx-aia-pill-bar");d?(h||(h=document.createElement("div"),h.className="magicx-aia-pill-bar",h.setAttribute("data-aia-pillbar",""),o.insertBefore(h,o.firstChild)),se(h,n,0,l,!0)):h&&h.remove();let g=o.querySelector(".magicx-aia-grid");t.length>0?(g||(g=document.createElement("div"),g.className="magicx-aia-grid",o.appendChild(g)),ft(g,t,i,p,s,e.listboxId)):g&&(g.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],m=ht(c,d,t,i,r,n);l.appendChild(m)}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],m=d===t;c.setAttribute("aria-selected",String(m)),m?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=document.createElement("button");return l.type="button",l.className="magicx-aia-submit",l.setAttribute("aria-label","Submit"),l.setAttribute("data-aia-submit",""),l.innerHTML=xt,r.appendChild(l),r.addEventListener("click",()=>s.focus()),s.addEventListener("input",()=>{let d=s.value,m=d.length>0&&d[0]!==d[0].toUpperCase()?d[0].toUpperCase()+d.slice(1):d;e.handleChange(m)}),s.addEventListener("keydown",d=>e.handleKeyDown(d)),s.addEventListener("focus",()=>e.store.set({isFocused:!0})),s.addEventListener("blur",()=>e.store.set({isFocused:!1})),l.addEventListener("click",d=>{d.stopPropagation();let c=e.store.get();if(!(!!c.text||c.completedParams.length>0)||!e.onSubmit)return;let{rawQuery:h,completedParams:g}=E(c.text,c.completedParams);e.onSubmit({query:c.text.trim(),raw_query:h,completed_params:g})}),e.autoFocus!==!1&&s.focus(),{textarea:s,dropdown:i,sizer:a,submitButton:l,inlinePillContainer:p}}function Pe(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 m=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";m?i.setAttribute("aria-activedescendant",m):i.removeAttribute("aria-activedescendant"),e.newParamId?i.classList.add("magicx-aia-textarea--hidden"):i.classList.remove("magicx-aia-textarea--hidden");let h=!!e.text||e.completedParams.length>0;a.disabled=!h,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:g=>c.set({activeDropdownIndex:g}),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 Ae=!1;function We(){if(Ae||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){Ae=!0;return}Ae=!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 je(){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(je());this._listboxId=yt();this.modeController=null;this.unsubscribers=[];this.derivedInProgress=!1;this.domRefs=null;this.dropdownRefs=null;this.externalListeners=new Set;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.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"&&(We(),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({...je()}),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,m=c.toLowerCase().lastIndexOf(e.text.toLowerCase()),h=m>=0?c.slice(m,m+e.text.length):e.text,g={id:crypto.randomUUID(),placeholder:"",type:i.type,text:h,kind:e.kind,suggestionType:i.type,suggestionPlaceholder:i.text,options:i.options??[],metadata:e.metadata},y=t.actionableSuggestions.length-1;this.store.set(x=>({text:c,filterBase:c.length,completedParams:[...x.completedParams,g],newParamId:g.id,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:y>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?U(e.text,p,e.filterInProgress):"",d=n?a?a(l.trim()):n.options??[]:[],c=te(d,l),m=e.suggestions.filter(b=>b.type==="placeholder").map(b=>b.text).join(" "),h=this.opts.dropdownTrigger??"auto",g=this.opts.closeDropdownOnBlur??!0,y=!1;if(h==="auto"){let b=g?e.isFocused:!0;y=!e.isLoading&&c.length>0&&b}else h==="manual"&&(y=!e.isLoading&&c.length>0&&e.pillTapped);this.store.set({segments:i,actionableSuggestions:r,filteredOptions:c,placeholderText:m,isDropdownOpen:y}),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 F(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},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&&Pe(this.domRefs,this.store.get(),t)}),Pe(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:m,onParamsChange:h}){let g=O(null),[y,x]=wt(null),b=O(o);b.current=o;let I=O(e);I.current=e;let T=O(m);T.current=m;let H=O(h);H.current=h;let Q=O(s);Q.current=s;let K=O(l);K.current=l,pe(()=>{if(typeof document>"u")return;let u=new de(document.createElement("div"),{renderMode:"headless",apiConfig:r,optionOverrides:t,maskCompletedText:i,columns:n,dropdownTrigger:a,closeDropdownOnBlur:p,value:d,completedParams:c,onSubmit:(..._)=>b.current?.(..._),onError:(..._)=>I.current?.(..._),onChange:(..._)=>T.current?.(..._),onParamsChange:(..._)=>H.current?.(..._),onFocus:()=>Q.current?.(),onBlur:()=>K.current?.()});g.current=u,x(u.getState());let w=u.subscribe(_=>x(_));return()=>{w(),u.destroy(),g.current===u&&(g.current=null)}},[]);let f=g.current,S=P(()=>{},[]);pe(()=>{d!==void 0&&f?.setValue(d)},[d,f]),pe(()=>{c!==void 0&&f?.setCompletedParams(c)},[c,f]);let D=JSON.stringify(r??null),R=O(t),W=O(0);if(t!==R.current){let u=R.current,w=t,_=Object.keys(u??{}),B=Object.keys(w??{});(_.length!==B.length||B.some(be=>!u?.[be]||w[be]!==u[be]))&&W.current++,R.current=t}pe(()=>{f?.update({apiConfig:r,optionOverrides:t,dropdownTrigger:a,closeDropdownOnBlur:p})},[D,W.current,a,p,f]);let ue=P(u=>{if(!f)return;let w=u.target.value,B=w.length>0&&!u.nativeEvent?.isComposing&&w[0]!==w[0].toUpperCase()?w[0].toUpperCase()+w.slice(1):w;f.handleTextChange(B)},[f]),j=P(u=>{f?.handleKeyDown(u.nativeEvent)},[f]),M=P(()=>f?.setFocused(!0),[f]),G=P(()=>f?.setFocused(!1),[f]),A=P(u=>f?.setActivePill(u),[f]),me=P(()=>f?.removeLastParam(),[f]),z=P(()=>f?.clearNewParamId(),[f]),X=P(()=>f?.reset(),[f]),ge=P(u=>f?.selectOption(u),[f]),$=P(u=>f?.setActiveDropdownIndex(u),[f]);if(!f)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=y??f.getState(),fe=d!==void 0?d:v.text,J=c!==void 0?c:v.completedParams,q=v.actionableSuggestions,Y=q[0],he=v.filteredOptions,xe=v.activeDropdownIndex>=0?`${f.listboxId}-option-${v.activeDropdownIndex}`:void 0;return{completedParams:J,suggestionPills:q,setActivePill:A,removeLastParam:me,segments:v.segments,newParamId:v.newParamId,clearNewParamId:z,suggestions:v.suggestions,activeIndex:v.activeDropdownIndex,isReady:v.isReady,isLoading:v.isLoading,error:v.error,inputProps:{value:fe,placeholder:v.placeholderText||void 0,onChange:ue,onKeyDown:j,onFocus:M,onBlur:G,role:"combobox","aria-expanded":v.isDropdownOpen,"aria-activedescendant":xe,"aria-autocomplete":"list","aria-controls":f.listboxId},reset:X,dropdownProps:{suggestions:Y?[{...Y,options:he}]:[],activeIndex:v.activeDropdownIndex,onSelect:ge,onHighlight:$,isOpen:v.isDropdownOpen,id:f.listboxId,pills:q,onPillClick:A}}}import{jsx as L,jsxs as N}from"react/jsx-runtime";function Ct(o){return o!=="auto"?o:typeof window>"u"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}var Pt=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:m,closeDropdownOnBlur:h,autoFocus:g=!0,onFocus:y,onBlur:x,value:b,completedParams:I,onChange:T,onParamsChange:H},Q){let K=ce(null),f=ce(null),S=ce(()=>{}),D=ce(null);Te(()=>{let u=K.current;if(u)return D.current?D.current.setMode(l):D.current=new F(u,l),()=>{D.current?.destroy(),D.current=null}},[l]);let{completedParams:R,suggestionPills:W,setActivePill:ue,segments:j,newParamId:M,clearNewParamId:G,inputProps:A,dropdownProps:me,reset:z}=ke({onSubmit:u=>S.current(u),onError:t,optionOverrides:i,maskCompletedText:r,apiConfig:a,columns:p,dropdownTrigger:m,closeDropdownOnBlur:h,onFocus:y,onBlur:x,value:b,completedParams:I,onChange:T,onParamsChange:H}),X=A.onFocus;Te(()=>{if(!g)return;let u=f.current;u&&(document.activeElement===u?X():u.focus())},[X,g]),Te(()=>{if(!M)return;let u=window.setTimeout(()=>G(),650);return()=>window.clearTimeout(u)},[M,G]),_t(Q,()=>({focus:()=>f.current?.focus(),blur:()=>f.current?.blur(),reset:z,setMode:u=>D.current?.setMode(u)}),[z]);let ge=()=>{f.current?.focus()},$=!!A.value||R.length>0,v=It(()=>{if(!$)return;let{rawQuery:u,completedParams:w}=E(A.value,R);e({query:A.value.trim(),raw_query:u,completed_params:w}),z()},[$,A.value,R,e,z]);S.current=v;let{onChange:fe,placeholder:J,...q}=A,Y=!A.value,he=s==="inline",xe=s==="dropdown";return N("div",{ref:K,className:`magicx-aia ${C.container} ${n??""}`,"data-pill-placement":s,"data-options-position":d,"data-animations":c?"on":"off","data-mode":Ct(l),children:[L(Ie,{...me,showPills:xe}),N("div",{className:C.inputWrapper,onClick:ge,children:[N("div",{className:C.editorArea,"data-aia-editor":"",children:[N("div",{className:C.sizerContent,"aria-hidden":"true",children:[Y&&J?N("span",{className:C.placeholderText,children:[J," "]}):N("span",{className:`${C.sizerText} ${M?C.sizerTextVisible:""}`,children:[j.map((u,w)=>{if(u.type==="completed"&&u.param.id===M){let B=`${C.shimmerRevealed} ${C.shimmerSweep}`;return L("span",{className:B,children:u.value},`${w}-${u.type}`)}return L("span",{children:u.value},`${w}-${u.type}`)}),j.length===0&&"\xA0"]})," ",he&&L(ee,{pills:W,activePillIndex:0,onSelectPill:ue})]}),L("textarea",{ref:f,"data-aia-textarea":"",className:`${C.textarea} ${M?C.textareaHidden:""}`,rows:1,onChange:fe,...q})]}),L("button",{type:"button","data-aia-submit":"",className:C.submitButton,disabled:!$,onClick:u=>{u.stopPropagation(),v()},"aria-label":"Submit",children:L("svg",{width:"18",height:"18",viewBox:"0 0 18 18",fill:"none",role:"img","aria-label":"Submit",children:L("path",{d:"M9 14V4M9 4L4 9M9 4L14 9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})});export{Pt as AIAutocomplete,Ie as AIAutocompleteDropdown,ke as useAIAutocomplete};
687
687
  //# sourceMappingURL=index.mjs.map