@magicx-eng/ai-autocomplete-react 0.1.37 → 0.1.38
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +5 -5
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +5 -5
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{forwardRef as Tt,useCallback as Ot,useEffect as
|
|
1
|
+
import{forwardRef as Tt,useCallback as Ot,useEffect as Me,useImperativeHandle as Et,useRef as xe}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;
|
|
@@ -247,7 +247,7 @@ import{forwardRef as Tt,useCallback as Ot,useEffect as Re,useImperativeHandle as
|
|
|
247
247
|
opacity: 0;
|
|
248
248
|
}
|
|
249
249
|
}
|
|
250
|
-
`,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
|
|
250
|
+
`,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 He}from"react/jsx-runtime";function tt(o){return o===0?.4:o===1?.3:.15}function oe({pills:o,activePillIndex:e,onSelectPill:t,rounded:i}){return He("span",{className:V.list,children:o.map((r,n)=>He("button",{type:"button","data-aia-pill":"",className:`${V.pill} ${i?V.rounded:""} ${n===e?V.active:""}`,style:{opacity:tt(n)},onClick:()=>t(n),children:r.text},`${r.type}-${r.text}`))})}import{useEffect as nt,useLayoutEffect as st,useRef as at,useState as lt}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 {
|
|
251
251
|
position: relative;
|
|
252
252
|
}
|
|
253
253
|
|
|
@@ -299,7 +299,7 @@ import{forwardRef as Tt,useCallback as Ot,useEffect as Re,useImperativeHandle as
|
|
|
299
299
|
background: var(--aia-scrollbar-thumb, rgba(0, 0, 0, 0.3));
|
|
300
300
|
border-radius: 3px;
|
|
301
301
|
}
|
|
302
|
-
`,document.head.appendChild(o)}var
|
|
302
|
+
`,document.head.appendChild(o)}var Ce={scrollWrapper:"SuggestionGrid-module_scrollWrapper_MOqfw",grid:"SuggestionGrid-module_grid_jvaPb"};import{useEffect as ot,useRef as it,useState as rt}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 {
|
|
303
303
|
position: relative;
|
|
304
304
|
overflow: visible;
|
|
305
305
|
display: flex;
|
|
@@ -610,7 +610,7 @@ import{forwardRef as Tt,useCallback as Ot,useEffect as Re,useImperativeHandle as
|
|
|
610
610
|
box-shadow: 0 0 24px 10px rgba(var(--aia-streak-rgb, 255, 255, 255), 0.02);
|
|
611
611
|
}
|
|
612
612
|
}
|
|
613
|
-
`,document.head.appendChild(o)}var O={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
|
|
613
|
+
`,document.head.appendChild(o)}var O={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 Ae,jsxs as Be}from"react/jsx-runtime";function ze({option:o,isHighlighted:e,onSelect:t,onHighlight:i,id:r}){let[n,s]=rt(!1),d=it(void 0);ot(()=>()=>clearTimeout(d.current),[]);let a=()=>{!o.is_tappable||n||(s(!0),t(o),clearTimeout(d.current),d.current=setTimeout(()=>s(!1),400))},l=[O.item,e?O.highlighted:"",o.is_tappable?O.tappable:O.nonTappable,n?O.pressed:""].filter(Boolean).join(" ");return Be("div",{id:r,role:"option","data-aia-option":"","aria-selected":e,className:l,tabIndex:o.is_tappable?0:-1,onClick:a,onKeyDown:p=>{o.is_tappable&&(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),a())},onMouseEnter:o.is_tappable?i:void 0,children:[Ae("div",{className:O.streaks}),Ae("div",{className:O.streaksVert}),Be("span",{className:O.content,children:[o.icon?`${o.icon} ${o.text}`:o.text,o.tag&&Ae("span",{className:O.tag,children:o.tag})]})]})}import{jsx as Pe}from"react/jsx-runtime";function Fe({options:o,activeIndex:e,onSelect:t,onHighlight:i,listboxId:r}){let n=at(null),[s,d]=lt(!1);return nt(()=>{let a=n.current;if(!a)return;let l=()=>{d(a.scrollHeight-a.scrollTop-a.clientHeight>1)};a.addEventListener("scroll",l,{passive:!0});let p=new ResizeObserver(l);return p.observe(a),()=>{a.removeEventListener("scroll",l),p.disconnect()}},[]),st(()=>{let a=n.current;a&&d(a.scrollHeight-a.scrollTop-a.clientHeight>1)},[o]),Pe("div",{className:Ce.scrollWrapper,"data-fade":s?"":void 0,children:Pe("div",{ref:n,className:Ce.grid,children:o.map((a,l)=>Pe(ze,{option:a,isHighlighted:l===e,onSelect:t,onHighlight:()=>i(l),id:`${r}-option-${l}`},a.text))})})}import{jsx as ke,jsxs as dt}from"react/jsx-runtime";function Te({suggestions:o,activeIndex:e,onSelect:t,onHighlight:i,isOpen:r,id:n,className:s,pills:d,onPillClick:a,showPills:l=!0}){let c=o[0]?.options??[],m=l&&d&&d.length>0&&a,x=r&&c.length>0||r&&m;return dt("div",{id:n,role:"listbox","data-aia-dropdown":"",className:`${te.dropdown} ${x?te.visible:""} ${s??""}`,onMouseDown:y=>y.preventDefault(),children:[m&&ke("div",{className:te.pillBar,"data-aia-pillbar":"",children:ke(oe,{pills:d,activePillIndex:0,onSelectPill:a,rounded:!0})}),c.length>0&&ke(Fe,{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=`/*
|
|
614
614
|
* Built-in appearance defaults \u2014 zero specificity via :where().
|
|
615
615
|
* Consumer CSS always wins without !important.
|
|
616
616
|
*
|
|
@@ -689,5 +689,5 @@ import{forwardRef as Tt,useCallback as Ot,useEffect as Re,useImperativeHandle as
|
|
|
689
689
|
animation-duration: 0s !important;
|
|
690
690
|
transition-duration: 0s !important;
|
|
691
691
|
}
|
|
692
|
-
`,document.head.appendChild(o)}import{useCallback as P,useEffect as fe,useRef as E,useState as kt}from"react";function A(o,e){let t=o,i={},r=[];for(let n of e){let s=(i[n.type]??0)+1;i[n.type]=s;let a=`{{${n.type.toUpperCase().replace(/\s+/g,"_")}_${s}}}`,l=t.indexOf(n.text);l!==-1&&(t=t.slice(0,l)+a+t.slice(l+n.text.length)),r.push({...n,placeholder:a})}return{rawQuery:t,completedParams:r}}function Q(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 Fe(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 s=i.slice(n).join(" ");if(r.startsWith(s.toLowerCase())){let d=t.length-s.length;return o.length-d}}return 0}function ie(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 Te(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 K=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 Ne(o,e){let t=[],i=0;for(let n of e){let s=o.indexOf(n.text,i);s!==-1&&(s>i&&t.push({type:"text",value:o.slice(i,s)}),t.push({type:"completed",value:n.text,param:n}),i=s+n.text.length)}let r=o.slice(i);return r&&t.push({type:"text",value:r}),t}function Ke(o,e){let t=[],i=[],r=0;for(let n of e){let s=o.indexOf(n.text,r);s===-1?i.push(n):(t.push(n),r=s+n.text.length)}return{valid:t,invalid:i}}var re=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 $e=new WeakMap;function G(o){return o?.type==="accessToken"}function pt(o){if(!(!o||G(o)))return o}function ne(o){let e=$e.get(o.getAccessToken);return e||(e=new re(o),$e.set(o.getAccessToken,e)),e}function se(o){return{"Content-Type":"application/json",...o?.appIdentifier&&{"X-App-Identifier":o.appIdentifier},...o?.headers}}function ae(o){let e=pt(o),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}var ct="https://api.ai-autocomplete.com/api/suggest",qe="/api/telemetry/events";function ut(o){let e=o??ct;try{return`${new URL(e).origin}${qe}`}catch{return`https://api.ai-autocomplete.com${qe}`}}async function mt(o){return G(o)?`Bearer ${await ne(o).getToken()}`:ae(o)}async function Ue(o){try{let e=ut(o.apiConfig?.endpoint),t=se(o.apiConfig),i=await mt(o.apiConfig);i&&(t.Authorization=i);let r=JSON.stringify({source:o.source,session_id:o.sessionId,type:o.type,at:new Date().toISOString(),query_data:o.queryData});await fetch(e,{method:"POST",headers:t,body:r})}catch{}}var gt="0.1.37",Ve=!1;function ft(){return crypto.randomUUID()}function ht(o,e){return{placeholder:o.placeholder,type:o.type,...e&&{text:o.text},kind:o.kind}}function xt(o,e,t,i){let r=e.find(s=>s.type==="contact"&&s.metadata?.contact_account_count)?.metadata?.contact_account_count,n=typeof r=="number"?r:void 0;return{data:{raw_query:o,completed_params:e.map(s=>ht(s,t)),...n!=null&&{contact_account_count:n}},meta:{request_id:ft(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:gt,session_id:i}}}async function Qe(o,e,t,i,r){return fetch(o,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:r})}async function Ge(o,e,t){let i=t.apiConfig,r=!t.maskCompletedText,n=xt(o,e,r,t.sessionId),s=se(i),d=i?.endpoint??"https://api.ai-autocomplete.com/api/suggest",a=JSON.stringify(n);if(G(i)){let c=ne(i),m=await c.getToken(),g=await Qe(d,s,m,a,t.signal);if(g.status===401){let x=await c.getToken(!0);g=await Qe(d,s,x,a,t.signal)}if(!g.ok)throw new Error(`API error: ${g.status} ${g.statusText}`);return g.json()}let l=ae(i);!l&&!Ve&&(Ve=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),l&&(s.Authorization=l);let p=await fetch(d,{method:"POST",headers:s,body:a,signal:t.signal});if(!p.ok)throw new Error(`API error: ${p.status} ${p.statusText}`);return p.json()}function We(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(d=>d.text)),s=(t.options??[]).filter(d=>!n.has(d.text));return{...t,options:[...r,...s]}}):o}var bt=100,vt=300,yt=2,le=class{constructor(e,t,i,r,n,s,d={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=r;this.getOnError=n;this.getSessionId=s;this.callbacks=d;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(),s=n.text.length;n.suggestions.some(a=>a.type!=="placeholder")||this.store.set({isLoading:!0}),this.store.set({error:null});try{let a=await Ge(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig()});if(r!==this.fetchVersion)return;let l=We(a.data.suggestions??[],this.getOptionOverrides()),p=a.data.input??[],c=p[p.length-1],m=this.store.get().text,g,x;if(c?.state==="in_progress"){x=!0;let S=m.toLowerCase().lastIndexOf(c.text.toLowerCase());g=S!==-1?S:s}else x=!1,g=s;let b=l.filter(S=>S.type!=="placeholder")[0],h=null;if(b){let S=Q(m,g,x),k=Te(b.options,S);k&&(h={id:crypto.randomUUID(),placeholder:"",type:b.type,text:k.text,kind:k.kind,suggestionType:b.type,suggestionPlaceholder:b.text,options:b.options??[],metadata:k.metadata},l=l.filter(H=>H!==b),this.callbacks.onAutoMatch?.({active:b,matched:k,rawQuery:e}))}this.store.set(S=>({suggestions:l,isLoading:!1,isReady:a.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:g,filterInProgress:x,...h?{completedParams:[...S.completedParams,h]}:{}}))}catch(a){if(r===this.fetchVersion){let l=a instanceof Error?a:new Error(String(a));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=Q(r.text,r.filterBase,r.filterInProgress),d=r.suggestions.filter(b=>b.type!=="placeholder")[0],l=(d?ie(d.options,n):[]).filter(b=>b.is_tappable),p=d?Te(d.options,n)!==null:!1,c=n.trim().length>0;if(l.length>0&&!p&&c)return!1;if(r.completedParams.length===0&&r.text.length>0){let b=r.suggestions.filter(h=>h.type==="placeholder").map(h=>h.text).join(" ");if(b.length>0&&b.toLowerCase().startsWith(r.text.toLowerCase()))return!1}let{rawQuery:m,completedParams:g}=A(r.text,r.completedParams),x=m.length<r.lastRawQuery.length,y=Math.abs(m.length-r.lastRawQuery.length);return x||y>=i?(this.doFetch(m,g),!0):!1};this.debounceTimer=setTimeout(()=>{t(yt)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},bt),this.slowDebounceTimer=setTimeout(()=>t(1),vt)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var de=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(),s=r(),d=this.getTappableIndices(n);switch(e.key){case"ArrowDown":{let a=e.target;if(!(a.selectionStart!=null&&a.selectionStart===a.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 a=d.indexOf(t.activeDropdownIndex),l=a>0?a-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 a=t.activeDropdownIndex-1;a>=0&&t.filteredOptions[a]?.is_tappable&&(e.preventDefault(),this.store.set({activeDropdownIndex:a}))}break}case"Enter":{if(e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable)this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i);else if(s){let{rawQuery:a,completedParams:l}=A(t.text,t.completedParams);s({query:t.text.trim(),raw_query:a,completed_params:l}),this.ctx.afterSubmit?.()}break}case"Tab":{let a=!t.text&&!!t.placeholderText,l=t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable;if(a&&!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,s)=>n.is_tappable?s:-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(d=>d.type!=="placeholder");if(e<0||e>=i.length)return;let r=i[e],n=i.filter((d,a)=>a!==e),s=t.suggestions.filter(d=>d.type==="placeholder");this.store.set({suggestions:[...s,r,...n],pillTapped:!0,activeDropdownIndex:-1})}};var pe=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),i=t.suggestions.filter(d=>d.type!=="placeholder");if(e<0||e>=i.length)return;let r=i[e],n=i.filter((d,a)=>a!==e),s=t.suggestions.filter(d=>d.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:d}=A(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:d,selectedPill:r.text,otherPills:n.map(a=>a.text)})}this.store.set({suggestions:[...s,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 wt(o){return o===0?.4:o===1?.3:.15}function ce(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 s=new Map;for(let a of n.querySelectorAll(".magicx-aia-pill"))s.set(a.dataset.pillKey??"",a);let d=new Set;for(let a=0;a<e.length;a++){let l=e[a],p=`${l.type}-${l.text}`;d.add(p);let c=s.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${r?" magicx-aia-pill--rounded":""}${a===t?" magicx-aia-pill--active":""}`,c.style.opacity=String(wt(a)),c.onclick=()=>i(a),n.children[a]!==c&&n.insertBefore(c,n.children[a]??null)}for(let[a,l]of s)d.has(a)||l.remove()}function ue(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 me(o,e){let{filteredOptions:t,activeIndex:i,isOpen:r,pills:n,showPills:s,onSelect:d,onHighlight:a,onPillClick:l}=e,p=s&&n.length>0;r&&t.length>0||r&&p?o.classList.add("magicx-aia-dropdown--visible"):o.classList.remove("magicx-aia-dropdown--visible");let g=o.querySelector(".magicx-aia-pill-bar");p?(g||(g=document.createElement("div"),g.className="magicx-aia-pill-bar",g.setAttribute("data-aia-pillbar",""),o.insertBefore(g,o.firstChild)),ce(g,n,0,l,!0)):g&&g.remove();let x=o.querySelector(".magicx-aia-grid");t.length>0?(x||(x=document.createElement("div"),x.className="magicx-aia-grid",o.appendChild(x)),St(x,t,i,d,a,e.listboxId)):x&&(x.innerHTML="")}function St(o,e,t,i,r,n){let s=e.map(l=>l.text).join("\0"),d=o.dataset.optionsKey??"",a=s!==d;if(o.dataset.optionsKey=s,a){let l=document.createDocumentFragment();for(let p=0;p<e.length;p++){let c=e[p],m=It(c,p,t,i,r,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 It(o,e,t,i,r,n){let s=document.createElement("div");s.id=`${n}-option-${e}`,s.setAttribute("role","option"),s.setAttribute("data-aia-option",""),s.setAttribute("aria-selected",String(e===t)),s.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"),s.className=d.join(" ");let a=document.createElement("div");a.className="magicx-aia-streaks",s.appendChild(a);let l=document.createElement("div");l.className="magicx-aia-streaks-vert",s.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 s.appendChild(p),o.is_tappable&&(s.addEventListener("click",()=>{s.classList.add("magicx-aia-option--pressed"),i(o),setTimeout(()=>s.classList.remove("magicx-aia-option--pressed"),400)}),s.addEventListener("mouseenter",()=>r(e))),s}function je(o,e){let t=ue(e.listboxId);return o.appendChild(t),{dropdown:t}}function Oe(o,e,t){me(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 Xe(o,e,t,i,r){let n=o.querySelector(".magicx-aia-sizer-text"),s=o.querySelector(".magicx-aia-placeholder");if(i&&r){n&&(n.style.display="none"),s||(s=document.createElement("span"),s.className="magicx-aia-placeholder",o.insertBefore(s,o.firstChild)),s.style.display="",s.textContent=`${r} `,o.dataset.segmentKey="";return}s&&(s.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"),a=o.dataset.segmentKey??"",l=o.dataset.newParamId??"";if(!(d===a&&(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 _t='<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 Je(o,e){let{listboxId:t}=e,i=ue(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 s=document.createElement("div");s.className="magicx-aia-sizer",s.setAttribute("aria-hidden","true"),n.appendChild(s);let d=document.createElement("span");s.appendChild(document.createTextNode(" ")),s.appendChild(d);let a=document.createElement("textarea");a.className="magicx-aia-textarea",a.rows=1,a.setAttribute("role","combobox"),a.setAttribute("aria-autocomplete","list"),a.setAttribute("aria-controls",t),a.setAttribute("data-aia-textarea",""),n.appendChild(a);let l=null,p=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=_t,r.appendChild(l),p=l):e.submitButton!==null&&(p=e.submitButton,p.hasAttribute("data-aia-submit")||p.setAttribute("data-aia-submit",""),r.appendChild(p)),r.addEventListener("click",()=>a.focus()),a.addEventListener("input",()=>{let c=a.value,g=c.length>0&&c[0]!==c[0].toUpperCase()?c[0].toUpperCase()+c.slice(1):c;e.handleChange(g)}),a.addEventListener("keydown",c=>e.handleKeyDown(c)),a.addEventListener("focus",()=>e.store.set({isFocused:!0})),a.addEventListener("blur",()=>e.store.set({isFocused:!1})),p&&p.addEventListener("click",c=>{let m=e.store.get();if(!(!!m.text||m.completedParams.length>0)||!e.onSubmit)return;c.stopPropagation();let{rawQuery:x,completedParams:y}=A(m.text,m.completedParams);e.onSubmit({query:m.text.trim(),raw_query:x,completed_params:y}),e.afterSubmit?.()}),e.autoFocus!==!1&&a.focus(),{textarea:a,dropdown:i,sizer:s,submitButton:l,inlinePillContainer:d}}function Ee(o,e,t){let{textarea:i,dropdown:r,sizer:n,submitButton:s,inlinePillContainer:d}=o,{pillPlacement:a,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}`:"";if(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"),s){let g=!!e.text||e.completedParams.length>0;s.disabled=!g}Xe(n,e.segments,e.newParamId,!e.text,e.placeholderText),a==="inline"?ce(d,e.actionableSuggestions,0,l):d.innerHTML="",me(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:a==="dropdown",onSelect:p,onHighlight:g=>c.set({activeDropdownIndex:g}),onPillClick:l})}function Ye(o){let e=o,t=new Set;return{get:()=>e,set:i=>{let r=typeof i=="function"?i(e):i,n={...e,...r},s=e;e=n;for(let d of t)d(n,s)},subscribe:i=>(t.add(i),()=>{t.delete(i)})}}var De=!1;function Ze(){if(De||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){De=!0;return}De=!0;let o=document.createElement("style");o.setAttribute("data-magicx-aia",""),o.textContent=Ct,document.head.appendChild(o)}var Ct="";var At=0;function Pt(){return`:ac-${++At}:`}function et(){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 ge=class{constructor(e,t={}){this.store=Ye(et());this._listboxId=Pt();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 pe(this.store,{onPillSelected:({rawQuery:i,selectedPill:r,otherPills:n})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:r,other_pills:n})}}),this.fetchController=new le(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.opts.onError,()=>this.sessionId,{onAutoMatch:({active:i,matched:r,rawQuery:n})=>{this.fireTelemetry("option",{raw_query:n,selected_option:r.text,other_options:(i.options??[]).filter(s=>s.text!==r.text).map(s=>s.text)})}}),this.keyboardController=new de(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"&&(Ze(),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({...et(),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{rawQuery:r}=A(t.text,t.completedParams);this.fireTelemetry("option",{raw_query:r,selected_option:e.text,other_options:t.filteredOptions.filter(h=>h.text!==e.text).map(h=>h.text)});let n=t.filterBase,s=t.text.slice(0,n),d=s.length===0&&t.text.length===0,a=s.length===0&&t.text.length>0&&t.placeholderText.length>0&&t.placeholderText.toLowerCase().startsWith(t.text.toLowerCase());(d||a)&&t.placeholderText&&(s=`${t.placeholderText} `);let l=Fe(s,e.text);l>0&&(s=s.slice(0,s.length-l));let p=s.length>0&&s[s.length-1]!==" ",c=`${s}${p?" ":""}${e.text} `,m=(d||a)&&c.length>0?c[0].toUpperCase()+c.slice(1):c,g=m.toLowerCase().lastIndexOf(e.text.toLowerCase()),x=g>=0?m.slice(g,g+e.text.length):e.text,y={id:crypto.randomUUID(),placeholder:"",type:i.type,text:x,kind:e.kind,suggestionType:i.type,suggestionPlaceholder:i.text,options:i.options??[],metadata:e.metadata},b=t.actionableSuggestions.length-1;this.store.set(h=>({text:m,filterBase:m.length,completedParams:[...h.completedParams,y],newParamId:y.id,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:b>0})),this.suggestionRemovalTimer=window.setTimeout(()=>{this.store.set(h=>({suggestions:h.suggestions.filter(S=>S!==i)}))},400)}fireTelemetry(e,t){let i=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");Ue({source:i,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}recomputeDerived(e,t){if(this.derivedInProgress)return;this.derivedInProgress=!0;let i=Ne(e.text,e.completedParams),r=e.suggestions.filter(h=>h.type!=="placeholder"),n=r[0],s=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?s?s(l.trim()):n.options??[]:[],c=ie(p,l),m=e.suggestions.filter(h=>h.type==="placeholder").map(h=>h.text).join(" "),g=this.opts.dropdownTrigger??"auto",x=this.opts.closeDropdownOnBlur??!0,y=!1;if(g==="auto"){let h=x?e.isFocused:!0;y=!e.isLoading&&c.length>0&&h}else g==="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 b=this.store.get();for(let h of this.externalListeners)h(b)}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 K(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=Je(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&Ee(this.domRefs,this.store.get(),t)}),Ee(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=je(this.container,e),this.subscribeBatchedRender(()=>{this.dropdownRefs&&Oe(this.dropdownRefs,this.store.get(),e)}),Oe(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}=Ke(e,t.completedParams);r.length>0&&this.store.set(n=>({completedParams:i,suggestions:[...r.map(s=>({type:s.suggestionType,text:s.suggestionPlaceholder,required:!0,options:s.options})),...n.suggestions]}))}};function Le({onSubmit:o,onError:e,optionOverrides:t,maskCompletedText:i,apiConfig:r,columns:n=2,dropdownTrigger:s,closeDropdownOnBlur:d,onFocus:a,onBlur:l,value:p,completedParams:c,onChange:m,onParamsChange:g,source:x}){let y=E(null),[b,h]=kt(null),S=E(o);S.current=o;let k=E(e);k.current=e;let H=E(m);H.current=m;let B=E(g);B.current=g;let W=E(a);W.current=a;let q=E(l);q.current=l,fe(()=>{if(typeof document>"u")return;let u=new ge(document.createElement("div"),{renderMode:"headless",apiConfig:r,optionOverrides:t,maskCompletedText:i,columns:n,dropdownTrigger:s,closeDropdownOnBlur:d,source:x,value:p,completedParams:c,onSubmit:(...C)=>S.current?.(...C),onError:(...C)=>k.current?.(...C),onChange:(...C)=>H.current?.(...C),onParamsChange:(...C)=>B.current?.(...C),onFocus:()=>W.current?.(),onBlur:()=>q.current?.()});y.current=u,h(u.getState());let w=u.subscribe(C=>h(C));return()=>{w(),u.destroy(),y.current===u&&(y.current=null)}},[]);let f=y.current,I=P(()=>{},[]);fe(()=>{p!==void 0&&f?.setValue(p)},[p,f]),fe(()=>{c!==void 0&&f?.setCompletedParams(c)},[c,f]);let L=JSON.stringify(r??null),R=E(t),j=E(0);if(t!==R.current){let u=R.current,w=t,C=Object.keys(u??{}),N=Object.keys(w??{});(C.length!==N.length||N.some(Ie=>!u?.[Ie]||w[Ie]!==u[Ie]))&&j.current++,R.current=t}fe(()=>{f?.update({apiConfig:r,optionOverrides:t,dropdownTrigger:s,closeDropdownOnBlur:d})},[L,j.current,s,d,f]);let xe=P(u=>{if(!f)return;let w=u.target.value,N=w.length>0&&!u.nativeEvent?.isComposing&&w[0]!==w[0].toUpperCase()?w[0].toUpperCase()+w.slice(1):w;f.handleTextChange(N)},[f]),X=P(u=>{f?.handleKeyDown(u.nativeEvent)},[f]),M=P(()=>f?.setFocused(!0),[f]),J=P(()=>f?.setFocused(!1),[f]),T=P(u=>f?.setActivePill(u),[f]),be=P(()=>f?.removeLastParam(),[f]),z=P(()=>f?.clearNewParamId(),[f]),Y=P(()=>f?.reset(),[f]),ve=P(u=>f?.selectOption(u),[f]),F=P(u=>f?.setActiveDropdownIndex(u),[f]);if(!f)return{completedParams:c??[],suggestionPills:[],setActivePill:I,removeLastParam:I,segments:[],newParamId:null,clearNewParamId:I,suggestions:[],activeIndex:-1,isReady:!1,isLoading:!0,error:null,inputProps:{value:p??"",placeholder:void 0,onChange:I,onKeyDown:I,onFocus:I,onBlur:I,role:"combobox","aria-expanded":!1,"aria-activedescendant":void 0,"aria-autocomplete":"list","aria-controls":""},reset:I,dropdownProps:{suggestions:[],activeIndex:-1,onSelect:I,onHighlight:I,isOpen:!1,id:"",pills:[],onPillClick:I}};let v=b??f.getState(),ye=p!==void 0?p:v.text,Z=c!==void 0?c:v.completedParams,U=v.actionableSuggestions,ee=U[0],we=v.filteredOptions,Se=v.activeDropdownIndex>=0?`${f.listboxId}-option-${v.activeDropdownIndex}`:void 0;return{completedParams:Z,suggestionPills:U,setActivePill:T,removeLastParam:be,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:ye,placeholder:v.placeholderText||void 0,onChange:xe,onKeyDown:X,onFocus:M,onBlur:J,role:"combobox","aria-expanded":v.isDropdownOpen,"aria-activedescendant":Se,"aria-autocomplete":"list","aria-controls":f.listboxId},reset:Y,dropdownProps:{suggestions:ee?[{...ee,options:we}]:[],activeIndex:v.activeDropdownIndex,onSelect:ve,onHighlight:F,isOpen:v.isDropdownOpen,id:f.listboxId,pills:U,onPillClick:T}}}import{jsx as D,jsxs as $}from"react/jsx-runtime";function Dt(o){return o!=="auto"?o:typeof window>"u"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}var Lt=Tt(function({onSubmit:e,onError:t,optionOverrides:i,maskCompletedText:r,className:n,apiConfig:s,columns:d,pillPlacement:a="inline",mode:l="auto",optionsPosition:p="below",animations:c=!0,dropdownTrigger:m,closeDropdownOnBlur:g,autoFocus:x=!0,onFocus:y,onBlur:b,value:h,completedParams:S,onChange:k,onParamsChange:H,submitButton:B},W){let q=he(null),f=he(null),I=he(()=>{}),L=he(null);Re(()=>{let u=q.current;if(u)return L.current?L.current.setMode(l):L.current=new K(u,l),()=>{L.current?.destroy(),L.current=null}},[l]);let{completedParams:R,suggestionPills:j,setActivePill:xe,segments:X,newParamId:M,clearNewParamId:J,inputProps:T,dropdownProps:be,reset:z}=Le({onSubmit:u=>I.current(u),onError:t,optionOverrides:i,maskCompletedText:r,apiConfig:s,columns:d,dropdownTrigger:m,closeDropdownOnBlur:g,onFocus:y,onBlur:b,value:h,completedParams:S,onChange:k,onParamsChange:H,source:"full-sdk"}),Y=T.onFocus;Re(()=>{if(!x)return;let u=f.current;u&&(document.activeElement===u?Y():u.focus())},[Y,x]),Re(()=>{if(!M)return;let u=window.setTimeout(()=>J(),650);return()=>window.clearTimeout(u)},[M,J]),Et(W,()=>({focus:()=>f.current?.focus(),blur:()=>f.current?.blur(),reset:z,setMode:u=>L.current?.setMode(u)}),[z]);let ve=()=>{f.current?.focus()},F=!!T.value||R.length>0,v=Ot(()=>{if(!F)return;let{rawQuery:u,completedParams:w}=A(T.value,R);e({query:T.value.trim(),raw_query:u,completed_params:w}),z()},[F,T.value,R,e,z]);I.current=v;let{onChange:ye,placeholder:Z,...U}=T,ee=!T.value,we=a==="inline",Se=a==="dropdown";return $("div",{ref:q,className:`magicx-aia ${_.container} ${n??""}`,"data-pill-placement":a,"data-options-position":p,"data-animations":c?"on":"off","data-mode":Dt(l),children:[D(ke,{...be,showPills:Se}),$("div",{className:_.inputWrapper,onClick:ve,children:[$("div",{className:_.editorArea,"data-aia-editor":"",children:[$("div",{className:_.sizerContent,"aria-hidden":"true",children:[ee&&Z?$("span",{className:_.placeholderText,children:[Z," "]}):$("span",{className:`${_.sizerText} ${M?_.sizerTextVisible:""}`,children:[X.map((u,w)=>{if(u.type==="completed"&&u.param.id===M){let N=`${_.shimmerRevealed} ${_.shimmerSweep}`;return D("span",{className:N,children:u.value},`${w}-${u.type}`)}return D("span",{children:u.value},`${w}-${u.type}`)}),X.length===0&&"\xA0"]})," ",we&&D(oe,{pills:j,activePillIndex:0,onSelectPill:xe})]}),D("textarea",{ref:f,"data-aia-textarea":"",className:`${_.textarea} ${M?_.textareaHidden:""}`,rows:1,onChange:ye,...U})]}),B===null?null:B===void 0?D("button",{type:"button","data-aia-submit":"",className:_.submitButton,disabled:!F,onClick:u=>{u.stopPropagation(),v()},"aria-label":"Submit",children:D("svg",{width:"18",height:"18",viewBox:"0 0 18 18",fill:"none",role:"img","aria-label":"Submit",children:D("path",{d:"M9 14V4M9 4L4 9M9 4L14 9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}):D("span",{"data-aia-submit":"",className:_.submitSlot,onClick:u=>{F&&(u.stopPropagation(),v())},children:B})]})]})});export{Lt as AIAutocomplete,ke as AIAutocompleteDropdown,Le as useAIAutocomplete};
|
|
692
|
+
`,document.head.appendChild(o)}import{useCallback as P,useEffect as he,useRef as E,useState as kt}from"react";function A(o,e){let t=o,i={},r=[];for(let n of e){let s=(i[n.type]??0)+1;i[n.type]=s;let a=`{{${n.type.toUpperCase().replace(/\s+/g,"_")}_${s}}}`,l=t.indexOf(n.text);l!==-1&&(t=t.slice(0,l)+a+t.slice(l+n.text.length)),r.push({...n,placeholder:a})}return{rawQuery:t,completedParams:r}}function Q(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 Ne(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 s=i.slice(n).join(" ");if(r.startsWith(s.toLowerCase())){let d=t.length-s.length;return o.length-d}}return 0}function ie(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 Oe(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 K=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 Ke(o,e){let t=[],i=0;for(let n of e){let s=o.indexOf(n.text,i);s!==-1&&(s>i&&t.push({type:"text",value:o.slice(i,s)}),t.push({type:"completed",value:n.text,param:n}),i=s+n.text.length)}let r=o.slice(i);return r&&t.push({type:"text",value:r}),t}function $e(o,e){let t=[],i=[],r=0;for(let n of e){let s=o.indexOf(n.text,r);s===-1?i.push(n):(t.push(n),r=s+n.text.length)}return{valid:t,invalid:i}}var re=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 pt="https://api.ai-autocomplete.com",ne=`${pt}/api/suggest`,qe=new WeakMap;function G(o){return o?.type==="accessToken"}function ct(o){if(!(!o||G(o)))return o}function se(o){let e=qe.get(o.getAccessToken);return e||(e=new re(o),qe.set(o.getAccessToken,e)),e}function ae(o){return{"Content-Type":"application/json",...o?.appIdentifier&&{"X-App-Identifier":o.appIdentifier},...o?.headers}}function le(o){let e=ct(o),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}function ut(o){return(o??ne).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function mt(o){return G(o)?`Bearer ${await se(o).getToken()}`:le(o)}async function Ue(o){try{let e=ut(o.apiConfig?.endpoint),t=ae(o.apiConfig),i=await mt(o.apiConfig);i&&(t.Authorization=i);let r=JSON.stringify({source:o.source,session_id:o.sessionId,type:o.type,at:new Date().toISOString(),query_data:o.queryData});await fetch(e,{method:"POST",headers:t,body:r})}catch{}}var gt="0.1.38",Ve=!1;function ft(){return crypto.randomUUID()}function ht(o,e){return{placeholder:o.placeholder,type:o.type,...e&&{text:o.text},kind:o.kind}}function xt(o,e,t,i){let r=e.find(s=>s.type==="contact"&&s.metadata?.contact_account_count)?.metadata?.contact_account_count,n=typeof r=="number"?r:void 0;return{data:{raw_query:o,completed_params:e.map(s=>ht(s,t)),...n!=null&&{contact_account_count:n}},meta:{request_id:ft(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:gt,session_id:i}}}async function Qe(o,e,t,i,r){return fetch(o,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:r})}async function Ge(o,e,t){let i=t.apiConfig,r=!t.maskCompletedText,n=xt(o,e,r,t.sessionId),s=ae(i),d=i?.endpoint??ne,a=JSON.stringify(n);if(G(i)){let c=se(i),m=await c.getToken(),g=await Qe(d,s,m,a,t.signal);if(g.status===401){let x=await c.getToken(!0);g=await Qe(d,s,x,a,t.signal)}if(!g.ok)throw new Error(`API error: ${g.status} ${g.statusText}`);return g.json()}let l=le(i);!l&&!Ve&&(Ve=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),l&&(s.Authorization=l);let p=await fetch(d,{method:"POST",headers:s,body:a,signal:t.signal});if(!p.ok)throw new Error(`API error: ${p.status} ${p.statusText}`);return p.json()}function We(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(d=>d.text)),s=(t.options??[]).filter(d=>!n.has(d.text));return{...t,options:[...r,...s]}}):o}var bt=100,vt=300,yt=2,de=class{constructor(e,t,i,r,n,s,d={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=r;this.getOnError=n;this.getSessionId=s;this.callbacks=d;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(),s=n.text.length;n.suggestions.some(a=>a.type!=="placeholder")||this.store.set({isLoading:!0}),this.store.set({error:null});try{let a=await Ge(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig()});if(r!==this.fetchVersion)return;let l=We(a.data.suggestions??[],this.getOptionOverrides()),p=a.data.input??[],c=p[p.length-1],m=this.store.get().text,g,x;if(c?.state==="in_progress"){x=!0;let S=m.toLowerCase().lastIndexOf(c.text.toLowerCase());g=S!==-1?S:s}else x=!1,g=s;let b=l.filter(S=>S.type!=="placeholder")[0],h=null;if(b){let S=Q(m,g,x),k=Oe(b.options,S);k&&(h={id:crypto.randomUUID(),placeholder:"",type:b.type,text:k.text,kind:k.kind,suggestionType:b.type,suggestionPlaceholder:b.text,options:b.options??[],metadata:k.metadata},l=l.filter(H=>H!==b),this.callbacks.onAutoMatch?.({active:b,matched:k,rawQuery:e}))}this.store.set(S=>({suggestions:l,isLoading:!1,isReady:a.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:g,filterInProgress:x,...h?{completedParams:[...S.completedParams,h]}:{}}))}catch(a){if(r===this.fetchVersion){let l=a instanceof Error?a:new Error(String(a));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=Q(r.text,r.filterBase,r.filterInProgress),d=r.suggestions.filter(b=>b.type!=="placeholder")[0],l=(d?ie(d.options,n):[]).filter(b=>b.is_tappable),p=d?Oe(d.options,n)!==null:!1,c=n.trim().length>0;if(l.length>0&&!p&&c)return!1;if(r.completedParams.length===0&&r.text.length>0){let b=r.suggestions.filter(h=>h.type==="placeholder").map(h=>h.text).join(" ");if(b.length>0&&b.toLowerCase().startsWith(r.text.toLowerCase()))return!1}let{rawQuery:m,completedParams:g}=A(r.text,r.completedParams),x=m.length<r.lastRawQuery.length,y=Math.abs(m.length-r.lastRawQuery.length);return x||y>=i?(this.doFetch(m,g),!0):!1};this.debounceTimer=setTimeout(()=>{t(yt)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},bt),this.slowDebounceTimer=setTimeout(()=>t(1),vt)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var pe=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(),s=r(),d=this.getTappableIndices(n);switch(e.key){case"ArrowDown":{let a=e.target;if(!(a.selectionStart!=null&&a.selectionStart===a.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 a=d.indexOf(t.activeDropdownIndex),l=a>0?a-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 a=t.activeDropdownIndex-1;a>=0&&t.filteredOptions[a]?.is_tappable&&(e.preventDefault(),this.store.set({activeDropdownIndex:a}))}break}case"Enter":{if(e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable)this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i);else if(s){let{rawQuery:a,completedParams:l}=A(t.text,t.completedParams);s({query:t.text.trim(),raw_query:a,completed_params:l}),this.ctx.afterSubmit?.()}break}case"Tab":{let a=!t.text&&!!t.placeholderText,l=t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable;if(a&&!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,s)=>n.is_tappable?s:-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(d=>d.type!=="placeholder");if(e<0||e>=i.length)return;let r=i[e],n=i.filter((d,a)=>a!==e),s=t.suggestions.filter(d=>d.type==="placeholder");this.store.set({suggestions:[...s,r,...n],pillTapped:!0,activeDropdownIndex:-1})}};var ce=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),i=t.suggestions.filter(d=>d.type!=="placeholder");if(e<0||e>=i.length)return;let r=i[e],n=i.filter((d,a)=>a!==e),s=t.suggestions.filter(d=>d.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:d}=A(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:d,selectedPill:r.text,otherPills:n.map(a=>a.text)})}this.store.set({suggestions:[...s,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 wt(o){return o===0?.4:o===1?.3:.15}function ue(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 s=new Map;for(let a of n.querySelectorAll(".magicx-aia-pill"))s.set(a.dataset.pillKey??"",a);let d=new Set;for(let a=0;a<e.length;a++){let l=e[a],p=`${l.type}-${l.text}`;d.add(p);let c=s.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${r?" magicx-aia-pill--rounded":""}${a===t?" magicx-aia-pill--active":""}`,c.style.opacity=String(wt(a)),c.onclick=()=>i(a),n.children[a]!==c&&n.insertBefore(c,n.children[a]??null)}for(let[a,l]of s)d.has(a)||l.remove()}function me(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 ge(o,e){let{filteredOptions:t,activeIndex:i,isOpen:r,pills:n,showPills:s,onSelect:d,onHighlight:a,onPillClick:l}=e,p=s&&n.length>0;r&&t.length>0||r&&p?o.classList.add("magicx-aia-dropdown--visible"):o.classList.remove("magicx-aia-dropdown--visible");let g=o.querySelector(".magicx-aia-pill-bar");p?(g||(g=document.createElement("div"),g.className="magicx-aia-pill-bar",g.setAttribute("data-aia-pillbar",""),o.insertBefore(g,o.firstChild)),ue(g,n,0,l,!0)):g&&g.remove();let x=o.querySelector(".magicx-aia-grid");t.length>0?(x||(x=document.createElement("div"),x.className="magicx-aia-grid",o.appendChild(x)),St(x,t,i,d,a,e.listboxId)):x&&(x.innerHTML="")}function St(o,e,t,i,r,n){let s=e.map(l=>l.text).join("\0"),d=o.dataset.optionsKey??"",a=s!==d;if(o.dataset.optionsKey=s,a){let l=document.createDocumentFragment();for(let p=0;p<e.length;p++){let c=e[p],m=It(c,p,t,i,r,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 It(o,e,t,i,r,n){let s=document.createElement("div");s.id=`${n}-option-${e}`,s.setAttribute("role","option"),s.setAttribute("data-aia-option",""),s.setAttribute("aria-selected",String(e===t)),s.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"),s.className=d.join(" ");let a=document.createElement("div");a.className="magicx-aia-streaks",s.appendChild(a);let l=document.createElement("div");l.className="magicx-aia-streaks-vert",s.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 s.appendChild(p),o.is_tappable&&(s.addEventListener("click",()=>{s.classList.add("magicx-aia-option--pressed"),i(o),setTimeout(()=>s.classList.remove("magicx-aia-option--pressed"),400)}),s.addEventListener("mouseenter",()=>r(e))),s}function je(o,e){let t=me(e.listboxId);return o.appendChild(t),{dropdown:t}}function Ee(o,e,t){ge(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 Xe(o,e,t,i,r){let n=o.querySelector(".magicx-aia-sizer-text"),s=o.querySelector(".magicx-aia-placeholder");if(i&&r){n&&(n.style.display="none"),s||(s=document.createElement("span"),s.className="magicx-aia-placeholder",o.insertBefore(s,o.firstChild)),s.style.display="",s.textContent=`${r} `,o.dataset.segmentKey="";return}s&&(s.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"),a=o.dataset.segmentKey??"",l=o.dataset.newParamId??"";if(!(d===a&&(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 _t='<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 Je(o,e){let{listboxId:t}=e,i=me(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 s=document.createElement("div");s.className="magicx-aia-sizer",s.setAttribute("aria-hidden","true"),n.appendChild(s);let d=document.createElement("span");s.appendChild(document.createTextNode(" ")),s.appendChild(d);let a=document.createElement("textarea");a.className="magicx-aia-textarea",a.rows=1,a.setAttribute("role","combobox"),a.setAttribute("aria-autocomplete","list"),a.setAttribute("aria-controls",t),a.setAttribute("data-aia-textarea",""),n.appendChild(a);let l=null,p=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=_t,r.appendChild(l),p=l):e.submitButton!==null&&(p=e.submitButton,p.hasAttribute("data-aia-submit")||p.setAttribute("data-aia-submit",""),r.appendChild(p)),r.addEventListener("click",()=>a.focus()),a.addEventListener("input",()=>{let c=a.value,g=c.length>0&&c[0]!==c[0].toUpperCase()?c[0].toUpperCase()+c.slice(1):c;e.handleChange(g)}),a.addEventListener("keydown",c=>e.handleKeyDown(c)),a.addEventListener("focus",()=>e.store.set({isFocused:!0})),a.addEventListener("blur",()=>e.store.set({isFocused:!1})),p&&p.addEventListener("click",c=>{let m=e.store.get();if(!(!!m.text||m.completedParams.length>0)||!e.onSubmit)return;c.stopPropagation();let{rawQuery:x,completedParams:y}=A(m.text,m.completedParams);e.onSubmit({query:m.text.trim(),raw_query:x,completed_params:y}),e.afterSubmit?.()}),e.autoFocus!==!1&&a.focus(),{textarea:a,dropdown:i,sizer:s,submitButton:l,inlinePillContainer:d}}function De(o,e,t){let{textarea:i,dropdown:r,sizer:n,submitButton:s,inlinePillContainer:d}=o,{pillPlacement:a,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}`:"";if(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"),s){let g=!!e.text||e.completedParams.length>0;s.disabled=!g}Xe(n,e.segments,e.newParamId,!e.text,e.placeholderText),a==="inline"?ue(d,e.actionableSuggestions,0,l):d.innerHTML="",ge(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:a==="dropdown",onSelect:p,onHighlight:g=>c.set({activeDropdownIndex:g}),onPillClick:l})}function Ye(o){let e=o,t=new Set;return{get:()=>e,set:i=>{let r=typeof i=="function"?i(e):i,n={...e,...r},s=e;e=n;for(let d of t)d(n,s)},subscribe:i=>(t.add(i),()=>{t.delete(i)})}}var Le=!1;function Ze(){if(Le||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){Le=!0;return}Le=!0;let o=document.createElement("style");o.setAttribute("data-magicx-aia",""),o.textContent=Ct,document.head.appendChild(o)}var Ct="";var At=0;function Pt(){return`:ac-${++At}:`}function et(){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 fe=class{constructor(e,t={}){this.store=Ye(et());this._listboxId=Pt();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 ce(this.store,{onPillSelected:({rawQuery:i,selectedPill:r,otherPills:n})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:r,other_pills:n})}}),this.fetchController=new de(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.opts.onError,()=>this.sessionId,{onAutoMatch:({active:i,matched:r,rawQuery:n})=>{this.fireTelemetry("option",{raw_query:n,selected_option:r.text,other_options:(i.options??[]).filter(s=>s.text!==r.text).map(s=>s.text)})}}),this.keyboardController=new pe(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"&&(Ze(),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({...et(),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{rawQuery:r}=A(t.text,t.completedParams);this.fireTelemetry("option",{raw_query:r,selected_option:e.text,other_options:t.filteredOptions.filter(h=>h.text!==e.text).map(h=>h.text)});let n=t.filterBase,s=t.text.slice(0,n),d=s.length===0&&t.text.length===0,a=s.length===0&&t.text.length>0&&t.placeholderText.length>0&&t.placeholderText.toLowerCase().startsWith(t.text.toLowerCase());(d||a)&&t.placeholderText&&(s=`${t.placeholderText} `);let l=Ne(s,e.text);l>0&&(s=s.slice(0,s.length-l));let p=s.length>0&&s[s.length-1]!==" ",c=`${s}${p?" ":""}${e.text} `,m=(d||a)&&c.length>0?c[0].toUpperCase()+c.slice(1):c,g=m.toLowerCase().lastIndexOf(e.text.toLowerCase()),x=g>=0?m.slice(g,g+e.text.length):e.text,y={id:crypto.randomUUID(),placeholder:"",type:i.type,text:x,kind:e.kind,suggestionType:i.type,suggestionPlaceholder:i.text,options:i.options??[],metadata:e.metadata},b=t.actionableSuggestions.length-1;this.store.set(h=>({text:m,filterBase:m.length,completedParams:[...h.completedParams,y],newParamId:y.id,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:b>0})),this.suggestionRemovalTimer=window.setTimeout(()=>{this.store.set(h=>({suggestions:h.suggestions.filter(S=>S!==i)}))},400)}fireTelemetry(e,t){let i=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");Ue({source:i,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}recomputeDerived(e,t){if(this.derivedInProgress)return;this.derivedInProgress=!0;let i=Ke(e.text,e.completedParams),r=e.suggestions.filter(h=>h.type!=="placeholder"),n=r[0],s=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?s?s(l.trim()):n.options??[]:[],c=ie(p,l),m=e.suggestions.filter(h=>h.type==="placeholder").map(h=>h.text).join(" "),g=this.opts.dropdownTrigger??"auto",x=this.opts.closeDropdownOnBlur??!0,y=!1;if(g==="auto"){let h=x?e.isFocused:!0;y=!e.isLoading&&c.length>0&&h}else g==="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 b=this.store.get();for(let h of this.externalListeners)h(b)}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 K(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=Je(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&De(this.domRefs,this.store.get(),t)}),De(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=je(this.container,e),this.subscribeBatchedRender(()=>{this.dropdownRefs&&Ee(this.dropdownRefs,this.store.get(),e)}),Ee(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}=$e(e,t.completedParams);r.length>0&&this.store.set(n=>({completedParams:i,suggestions:[...r.map(s=>({type:s.suggestionType,text:s.suggestionPlaceholder,required:!0,options:s.options})),...n.suggestions]}))}};function Re({onSubmit:o,onError:e,optionOverrides:t,maskCompletedText:i,apiConfig:r,columns:n=2,dropdownTrigger:s,closeDropdownOnBlur:d,onFocus:a,onBlur:l,value:p,completedParams:c,onChange:m,onParamsChange:g,source:x}){let y=E(null),[b,h]=kt(null),S=E(o);S.current=o;let k=E(e);k.current=e;let H=E(m);H.current=m;let B=E(g);B.current=g;let W=E(a);W.current=a;let q=E(l);q.current=l,he(()=>{if(typeof document>"u")return;let u=new fe(document.createElement("div"),{renderMode:"headless",apiConfig:r,optionOverrides:t,maskCompletedText:i,columns:n,dropdownTrigger:s,closeDropdownOnBlur:d,source:x,value:p,completedParams:c,onSubmit:(...C)=>S.current?.(...C),onError:(...C)=>k.current?.(...C),onChange:(...C)=>H.current?.(...C),onParamsChange:(...C)=>B.current?.(...C),onFocus:()=>W.current?.(),onBlur:()=>q.current?.()});y.current=u,h(u.getState());let w=u.subscribe(C=>h(C));return()=>{w(),u.destroy(),y.current===u&&(y.current=null)}},[]);let f=y.current,I=P(()=>{},[]);he(()=>{p!==void 0&&f?.setValue(p)},[p,f]),he(()=>{c!==void 0&&f?.setCompletedParams(c)},[c,f]);let L=JSON.stringify(r??null),R=E(t),j=E(0);if(t!==R.current){let u=R.current,w=t,C=Object.keys(u??{}),N=Object.keys(w??{});(C.length!==N.length||N.some(_e=>!u?.[_e]||w[_e]!==u[_e]))&&j.current++,R.current=t}he(()=>{f?.update({apiConfig:r,optionOverrides:t,dropdownTrigger:s,closeDropdownOnBlur:d})},[L,j.current,s,d,f]);let be=P(u=>{if(!f)return;let w=u.target.value,N=w.length>0&&!u.nativeEvent?.isComposing&&w[0]!==w[0].toUpperCase()?w[0].toUpperCase()+w.slice(1):w;f.handleTextChange(N)},[f]),X=P(u=>{f?.handleKeyDown(u.nativeEvent)},[f]),M=P(()=>f?.setFocused(!0),[f]),J=P(()=>f?.setFocused(!1),[f]),T=P(u=>f?.setActivePill(u),[f]),ve=P(()=>f?.removeLastParam(),[f]),z=P(()=>f?.clearNewParamId(),[f]),Y=P(()=>f?.reset(),[f]),ye=P(u=>f?.selectOption(u),[f]),F=P(u=>f?.setActiveDropdownIndex(u),[f]);if(!f)return{completedParams:c??[],suggestionPills:[],setActivePill:I,removeLastParam:I,segments:[],newParamId:null,clearNewParamId:I,suggestions:[],activeIndex:-1,isReady:!1,isLoading:!0,error:null,inputProps:{value:p??"",placeholder:void 0,onChange:I,onKeyDown:I,onFocus:I,onBlur:I,role:"combobox","aria-expanded":!1,"aria-activedescendant":void 0,"aria-autocomplete":"list","aria-controls":""},reset:I,dropdownProps:{suggestions:[],activeIndex:-1,onSelect:I,onHighlight:I,isOpen:!1,id:"",pills:[],onPillClick:I}};let v=b??f.getState(),we=p!==void 0?p:v.text,Z=c!==void 0?c:v.completedParams,U=v.actionableSuggestions,ee=U[0],Se=v.filteredOptions,Ie=v.activeDropdownIndex>=0?`${f.listboxId}-option-${v.activeDropdownIndex}`:void 0;return{completedParams:Z,suggestionPills:U,setActivePill:T,removeLastParam:ve,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:we,placeholder:v.placeholderText||void 0,onChange:be,onKeyDown:X,onFocus:M,onBlur:J,role:"combobox","aria-expanded":v.isDropdownOpen,"aria-activedescendant":Ie,"aria-autocomplete":"list","aria-controls":f.listboxId},reset:Y,dropdownProps:{suggestions:ee?[{...ee,options:Se}]:[],activeIndex:v.activeDropdownIndex,onSelect:ye,onHighlight:F,isOpen:v.isDropdownOpen,id:f.listboxId,pills:U,onPillClick:T}}}import{jsx as D,jsxs as $}from"react/jsx-runtime";function Dt(o){return o!=="auto"?o:typeof window>"u"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}var Lt=Tt(function({onSubmit:e,onError:t,optionOverrides:i,maskCompletedText:r,className:n,apiConfig:s,columns:d,pillPlacement:a="inline",mode:l="auto",optionsPosition:p="below",animations:c=!0,dropdownTrigger:m,closeDropdownOnBlur:g,autoFocus:x=!0,onFocus:y,onBlur:b,value:h,completedParams:S,onChange:k,onParamsChange:H,submitButton:B},W){let q=xe(null),f=xe(null),I=xe(()=>{}),L=xe(null);Me(()=>{let u=q.current;if(u)return L.current?L.current.setMode(l):L.current=new K(u,l),()=>{L.current?.destroy(),L.current=null}},[l]);let{completedParams:R,suggestionPills:j,setActivePill:be,segments:X,newParamId:M,clearNewParamId:J,inputProps:T,dropdownProps:ve,reset:z}=Re({onSubmit:u=>I.current(u),onError:t,optionOverrides:i,maskCompletedText:r,apiConfig:s,columns:d,dropdownTrigger:m,closeDropdownOnBlur:g,onFocus:y,onBlur:b,value:h,completedParams:S,onChange:k,onParamsChange:H,source:"full-sdk"}),Y=T.onFocus;Me(()=>{if(!x)return;let u=f.current;u&&(document.activeElement===u?Y():u.focus())},[Y,x]),Me(()=>{if(!M)return;let u=window.setTimeout(()=>J(),650);return()=>window.clearTimeout(u)},[M,J]),Et(W,()=>({focus:()=>f.current?.focus(),blur:()=>f.current?.blur(),reset:z,setMode:u=>L.current?.setMode(u)}),[z]);let ye=()=>{f.current?.focus()},F=!!T.value||R.length>0,v=Ot(()=>{if(!F)return;let{rawQuery:u,completedParams:w}=A(T.value,R);e({query:T.value.trim(),raw_query:u,completed_params:w}),z()},[F,T.value,R,e,z]);I.current=v;let{onChange:we,placeholder:Z,...U}=T,ee=!T.value,Se=a==="inline",Ie=a==="dropdown";return $("div",{ref:q,className:`magicx-aia ${_.container} ${n??""}`,"data-pill-placement":a,"data-options-position":p,"data-animations":c?"on":"off","data-mode":Dt(l),children:[D(Te,{...ve,showPills:Ie}),$("div",{className:_.inputWrapper,onClick:ye,children:[$("div",{className:_.editorArea,"data-aia-editor":"",children:[$("div",{className:_.sizerContent,"aria-hidden":"true",children:[ee&&Z?$("span",{className:_.placeholderText,children:[Z," "]}):$("span",{className:`${_.sizerText} ${M?_.sizerTextVisible:""}`,children:[X.map((u,w)=>{if(u.type==="completed"&&u.param.id===M){let N=`${_.shimmerRevealed} ${_.shimmerSweep}`;return D("span",{className:N,children:u.value},`${w}-${u.type}`)}return D("span",{children:u.value},`${w}-${u.type}`)}),X.length===0&&"\xA0"]})," ",Se&&D(oe,{pills:j,activePillIndex:0,onSelectPill:be})]}),D("textarea",{ref:f,"data-aia-textarea":"",className:`${_.textarea} ${M?_.textareaHidden:""}`,rows:1,onChange:we,...U})]}),B===null?null:B===void 0?D("button",{type:"button","data-aia-submit":"",className:_.submitButton,disabled:!F,onClick:u=>{u.stopPropagation(),v()},"aria-label":"Submit",children:D("svg",{width:"18",height:"18",viewBox:"0 0 18 18",fill:"none",role:"img","aria-label":"Submit",children:D("path",{d:"M9 14V4M9 4L4 9M9 4L14 9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}):D("span",{"data-aia-submit":"",className:_.submitSlot,onClick:u=>{F&&(u.stopPropagation(),v())},children:B})]})]})});export{Lt as AIAutocomplete,Te as AIAutocompleteDropdown,Re as useAIAutocomplete};
|
|
693
693
|
//# sourceMappingURL=index.mjs.map
|