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

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.d.mts CHANGED
@@ -117,6 +117,13 @@ interface UseAIAutocompleteOptions {
117
117
  maskCompletedText?: boolean;
118
118
  apiConfig?: APIConfig;
119
119
  columns?: number;
120
+ /**
121
+ * SDK surface identifier for telemetry. Set automatically by the Tier 1
122
+ * `<AIAutocomplete />` component. Consumers using the hook directly should
123
+ * leave this unset (defaults to "headless-sdk").
124
+ * @internal
125
+ */
126
+ source?: "full-sdk" | "headless-sdk";
120
127
  /** When the dropdown appears. Default: "auto". */
121
128
  dropdownTrigger?: "auto" | "manual" | "hidden";
122
129
  /** When true (default), the dropdown closes when the input loses focus. Set to false to keep it open whenever options are available. */
@@ -179,6 +186,6 @@ declare const AIAutocomplete: react.ForwardRefExoticComponent<AIAutocompleteProp
179
186
 
180
187
  declare function AIAutocompleteDropdown({ suggestions, activeIndex, onSelect, onHighlight, isOpen, id, className, pills, onPillClick, showPills, }: AIAutocompleteDropdownProps): react_jsx_runtime.JSX.Element;
181
188
 
182
- declare function useAIAutocomplete({ onSubmit, onError, optionOverrides, maskCompletedText, apiConfig, columns, dropdownTrigger, closeDropdownOnBlur, onFocus, onBlur, value: controlledValue, completedParams: controlledParams, onChange: onChangeProp, onParamsChange, }: UseAIAutocompleteOptions): UseAIAutocompleteReturn;
189
+ declare function useAIAutocomplete({ onSubmit, onError, optionOverrides, maskCompletedText, apiConfig, columns, dropdownTrigger, closeDropdownOnBlur, onFocus, onBlur, value: controlledValue, completedParams: controlledParams, onChange: onChangeProp, onParamsChange, source, }: UseAIAutocompleteOptions): UseAIAutocompleteReturn;
183
190
 
184
191
  export { AIAutocomplete, AIAutocompleteDropdown, type AIAutocompleteDropdownProps, type AIAutocompleteHandle, type AIAutocompleteProps, type APIConfig, type APIKeyConfig, type AccessTokenConfig, type AccessTokenResult, type AppearanceMode, type AutocompleteResult, type CompletedParam, type CompletedParamState, type OptionOverrides, type Segment, type Suggestion, type SuggestionOption, type TaskKind, type UseAIAutocompleteOptions, type UseAIAutocompleteReturn, useAIAutocomplete };
package/dist/index.d.ts CHANGED
@@ -117,6 +117,13 @@ interface UseAIAutocompleteOptions {
117
117
  maskCompletedText?: boolean;
118
118
  apiConfig?: APIConfig;
119
119
  columns?: number;
120
+ /**
121
+ * SDK surface identifier for telemetry. Set automatically by the Tier 1
122
+ * `<AIAutocomplete />` component. Consumers using the hook directly should
123
+ * leave this unset (defaults to "headless-sdk").
124
+ * @internal
125
+ */
126
+ source?: "full-sdk" | "headless-sdk";
120
127
  /** When the dropdown appears. Default: "auto". */
121
128
  dropdownTrigger?: "auto" | "manual" | "hidden";
122
129
  /** When true (default), the dropdown closes when the input loses focus. Set to false to keep it open whenever options are available. */
@@ -179,6 +186,6 @@ declare const AIAutocomplete: react.ForwardRefExoticComponent<AIAutocompleteProp
179
186
 
180
187
  declare function AIAutocompleteDropdown({ suggestions, activeIndex, onSelect, onHighlight, isOpen, id, className, pills, onPillClick, showPills, }: AIAutocompleteDropdownProps): react_jsx_runtime.JSX.Element;
181
188
 
182
- declare function useAIAutocomplete({ onSubmit, onError, optionOverrides, maskCompletedText, apiConfig, columns, dropdownTrigger, closeDropdownOnBlur, onFocus, onBlur, value: controlledValue, completedParams: controlledParams, onChange: onChangeProp, onParamsChange, }: UseAIAutocompleteOptions): UseAIAutocompleteReturn;
189
+ declare function useAIAutocomplete({ onSubmit, onError, optionOverrides, maskCompletedText, apiConfig, columns, dropdownTrigger, closeDropdownOnBlur, onFocus, onBlur, value: controlledValue, completedParams: controlledParams, onChange: onChangeProp, onParamsChange, source, }: UseAIAutocompleteOptions): UseAIAutocompleteReturn;
183
190
 
184
191
  export { AIAutocomplete, AIAutocompleteDropdown, type AIAutocompleteDropdownProps, type AIAutocompleteHandle, type AIAutocompleteProps, type APIConfig, type APIKeyConfig, type AccessTokenConfig, type AccessTokenResult, type AppearanceMode, type AutocompleteResult, type CompletedParam, type CompletedParamState, type OptionOverrides, type Segment, type Suggestion, type SuggestionOption, type TaskKind, type UseAIAutocompleteOptions, type UseAIAutocompleteReturn, useAIAutocomplete };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Ie=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var je=Object.getOwnPropertyNames;var Xe=Object.prototype.hasOwnProperty;var Je=(o,e)=>{for(var t in e)Ie(o,t,{get:e[t],enumerable:!0})},Ye=(o,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of je(e))!Xe.call(o,r)&&r!==t&&Ie(o,r,{get:()=>e[r],enumerable:!(i=We(e,r))||i.enumerable});return o};var Ze=o=>Ye(Ie({},"__esModule",{value:!0}),o);var vt={};Je(vt,{AIAutocomplete:()=>Ge,AIAutocompleteDropdown:()=>re,useAIAutocomplete:()=>fe});module.exports=Ze(vt);var A=require("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
+ "use strict";var Ce=Object.defineProperty;var Ze=Object.getOwnPropertyDescriptor;var et=Object.getOwnPropertyNames;var tt=Object.prototype.hasOwnProperty;var ot=(o,e)=>{for(var t in e)Ce(o,t,{get:e[t],enumerable:!0})},it=(o,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of et(e))!tt.call(o,n)&&n!==t&&Ce(o,n,{get:()=>e[n],enumerable:!(i=Ze(e,n))||i.enumerable});return o};var nt=o=>it(Ce({},"__esModule",{value:!0}),o);var Tt={};ot(Tt,{AIAutocomplete:()=>Ye,AIAutocompleteDropdown:()=>ae,useAIAutocomplete:()=>he});module.exports=nt(Tt);var _=require("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;
@@ -184,7 +184,7 @@
184
184
  .AIAutocompleteDropdown-module_pillBar_pwTXe {
185
185
  padding: 27px 27px 0px 27px;
186
186
  }
187
- `,document.head.appendChild(o)}var oe={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 {
187
+ `,document.head.appendChild(o)}var ne={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 {
188
188
  position: relative;
189
189
  z-index: 1;
190
190
  pointer-events: auto;
@@ -247,7 +247,7 @@
247
247
  opacity: 0;
248
248
  }
249
249
  }
250
- `,document.head.appendChild(o)}var j={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--"};var _e=require("react/jsx-runtime");function et(o){return o===0?.4:o===1?.3:.15}function ie({pills:o,activePillIndex:e,onSelectPill:t,rounded:i}){return(0,_e.jsx)("span",{className:j.list,children:o.map((r,n)=>(0,_e.jsx)("button",{type:"button","data-aia-pill":"",className:`${j.pill} ${i?j.rounded:""} ${n===e?j.active:""}`,style:{opacity:et(n)},onClick:()=>t(n),children:r.text},`${r.type}-${r.text}`))})}var L=require("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 {
250
+ `,document.head.appendChild(o)}var j={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--"};var _e=require("react/jsx-runtime");function rt(o){return o===0?.4:o===1?.3:.15}function re({pills:o,activePillIndex:e,onSelectPill:t,rounded:i}){return(0,_e.jsx)("span",{className:j.list,children:o.map((n,r)=>(0,_e.jsx)("button",{type:"button","data-aia-pill":"",className:`${j.pill} ${i?j.rounded:""} ${r===e?j.active:""}`,style:{opacity:rt(r)},onClick:()=>t(r),children:n.text},`${n.type}-${n.text}`))})}var R=require("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 @@
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 Ce={scrollWrapper:"SuggestionGrid-module_scrollWrapper_MOqfw",grid:"SuggestionGrid-module_grid_jvaPb"};var $=require("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 {
302
+ `,document.head.appendChild(o)}var Ae={scrollWrapper:"SuggestionGrid-module_scrollWrapper_MOqfw",grid:"SuggestionGrid-module_grid_jvaPb"};var q=require("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 @@
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"};var H=require("react/jsx-runtime");function Oe({option:o,isHighlighted:e,onSelect:t,onHighlight:i,id:r}){let[n,a]=(0,$.useState)(!1),p=(0,$.useRef)(void 0);(0,$.useEffect)(()=>()=>clearTimeout(p.current),[]);let s=()=>{!o.is_tappable||n||(a(!0),t(o),clearTimeout(p.current),p.current=setTimeout(()=>a(!1),400))},l=[O.item,e?O.highlighted:"",o.is_tappable?O.tappable:O.nonTappable,n?O.pressed:""].filter(Boolean).join(" ");return(0,H.jsxs)("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:[(0,H.jsx)("div",{className:O.streaks}),(0,H.jsx)("div",{className:O.streaksVert}),(0,H.jsxs)("span",{className:O.content,children:[o.icon?`${o.icon} ${o.text}`:o.text,o.tag&&(0,H.jsx)("span",{className:O.tag,children:o.tag})]})]})}var ne=require("react/jsx-runtime");function De({options:o,activeIndex:e,onSelect:t,onHighlight:i,listboxId:r}){let n=(0,L.useRef)(null),[a,p]=(0,L.useState)(!1);return(0,L.useEffect)(()=>{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()}},[]),(0,L.useLayoutEffect)(()=>{let s=n.current;s&&p(s.scrollHeight-s.scrollTop-s.clientHeight>1)},[o]),(0,ne.jsx)("div",{className:Ce.scrollWrapper,"data-fade":a?"":void 0,children:(0,ne.jsx)("div",{ref:n,className:Ce.grid,children:o.map((s,l)=>(0,ne.jsx)(Oe,{option:s,isHighlighted:l===e,onSelect:t,onHighlight:()=>i(l),id:`${r}-option-${l}`},s.text))})})}var q=require("react/jsx-runtime");function re({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??[],u=l&&p&&p.length>0&&s,m=r&&c.length>0||r&&u;return(0,q.jsxs)("div",{id:n,role:"listbox","data-aia-dropdown":"",className:`${oe.dropdown} ${m?oe.visible:""} ${a??""}`,onMouseDown:S=>S.preventDefault(),children:[u&&(0,q.jsx)("div",{className:oe.pillBar,"data-aia-pillbar":"",children:(0,q.jsx)(ie,{pills:p,activePillIndex:0,onSelectPill:s,rounded:!0})}),c.length>0&&(0,q.jsx)(De,{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=`/*
613
+ `,document.head.appendChild(o)}var D={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"};var B=require("react/jsx-runtime");function Ee({option:o,isHighlighted:e,onSelect:t,onHighlight:i,id:n}){let[r,s]=(0,q.useState)(!1),d=(0,q.useRef)(void 0);(0,q.useEffect)(()=>()=>clearTimeout(d.current),[]);let a=()=>{!o.is_tappable||r||(s(!0),t(o),clearTimeout(d.current),d.current=setTimeout(()=>s(!1),400))},l=[D.item,e?D.highlighted:"",o.is_tappable?D.tappable:D.nonTappable,r?D.pressed:""].filter(Boolean).join(" ");return(0,B.jsxs)("div",{id:n,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:[(0,B.jsx)("div",{className:D.streaks}),(0,B.jsx)("div",{className:D.streaksVert}),(0,B.jsxs)("span",{className:D.content,children:[o.icon?`${o.icon} ${o.text}`:o.text,o.tag&&(0,B.jsx)("span",{className:D.tag,children:o.tag})]})]})}var se=require("react/jsx-runtime");function De({options:o,activeIndex:e,onSelect:t,onHighlight:i,listboxId:n}){let r=(0,R.useRef)(null),[s,d]=(0,R.useState)(!1);return(0,R.useEffect)(()=>{let a=r.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()}},[]),(0,R.useLayoutEffect)(()=>{let a=r.current;a&&d(a.scrollHeight-a.scrollTop-a.clientHeight>1)},[o]),(0,se.jsx)("div",{className:Ae.scrollWrapper,"data-fade":s?"":void 0,children:(0,se.jsx)("div",{ref:r,className:Ae.grid,children:o.map((a,l)=>(0,se.jsx)(Ee,{option:a,isHighlighted:l===e,onSelect:t,onHighlight:()=>i(l),id:`${n}-option-${l}`},a.text))})})}var U=require("react/jsx-runtime");function ae({suggestions:o,activeIndex:e,onSelect:t,onHighlight:i,isOpen:n,id:r,className:s,pills:d,onPillClick:a,showPills:l=!0}){let c=o[0]?.options??[],m=l&&d&&d.length>0&&a,h=n&&c.length>0||n&&m;return(0,U.jsxs)("div",{id:r,role:"listbox","data-aia-dropdown":"",className:`${ne.dropdown} ${h?ne.visible:""} ${s??""}`,onMouseDown:y=>y.preventDefault(),children:[m&&(0,U.jsx)("div",{className:ne.pillBar,"data-aia-pillbar":"",children:(0,U.jsx)(re,{pills:d,activePillIndex:0,onSelectPill:a,rounded:!0})}),c.length>0&&(0,U.jsx)(De,{options:c,activeIndex:e,onSelect:t,onHighlight:i,listboxId:r})]})}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 @@
689
689
  animation-duration: 0s !important;
690
690
  transition-duration: 0s !important;
691
691
  }
692
- `,document.head.appendChild(o)}var x=require("react");function X(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 Ee(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 se(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 Ae(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 V=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 Le(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 Re(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 ae=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 tt="0.1.35",Me=!1;function ot(){return crypto.randomUUID()}function it(o,e){return{placeholder:o.placeholder,type:o.type,...e&&{text:o.text},kind:o.kind}}function ze(o){return o?.type==="accessToken"}function nt(o){if(!(!o||ze(o)))return o}var He=new WeakMap;function rt(o){let e=He.get(o.getAccessToken);return e||(e=new ae(o),He.set(o.getAccessToken,e)),e}function st(o,e,t,i){let r=e.find(a=>a.type==="contact"&&a.metadata?.contact_account_count)?.metadata?.contact_account_count,n=typeof r=="number"?r:void 0;return{data:{raw_query:o,completed_params:e.map(a=>it(a,t)),...n!=null&&{contact_account_count:n}},meta:{request_id:ot(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:tt,session_id:i}}}function at(o){return{"Content-Type":"application/json",...o?.appIdentifier&&{"X-App-Identifier":o.appIdentifier},...o?.headers}}async function Be(o,e,t,i,r){return fetch(o,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:r})}async function Fe(o,e,t){let i=t.apiConfig,r=!t.maskCompletedText,n=st(o,e,r,t.sessionId),a=at(i),p=i?.endpoint??"https://api.ai-autocomplete.com/api/suggest",s=JSON.stringify(n);if(ze(i)){let u=rt(i),f=await u.getToken(),m=await Be(p,a,f,s,t.signal);if(m.status===401){let S=await u.getToken(!0);m=await Be(p,a,S,s,t.signal)}if(!m.ok)throw new Error(`API error: ${m.status} ${m.statusText}`);return m.json()}let l=nt(i),d=l?.apiKey??"";if(!d&&!Me&&(Me=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),d){let u=l?.authScheme??"Bearer";a.Authorization=u==="Basic"?`Basic ${btoa(d)}`:`Bearer ${d}`}let c=await fetch(p,{method:"POST",headers:a,body:s,signal:t.signal});if(!c.ok)throw new Error(`API error: ${c.status} ${c.statusText}`);return c.json()}function R(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 Ne(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 lt=100,dt=300,pt=2,le=class{constructor(e,t,i,r,n,a){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=r;this.getOnError=n;this.getSessionId=a;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null}start(){this.doFetch("",[]);let e=this.store.get().text,t=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(i=>{(i.text!==e||i.completedParams!==t)&&(e=i.text,t=i.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let i=new AbortController;this.abortController=i;let r=++this.fetchVersion,n=this.store.get(),a=n.text.length;n.suggestions.some(s=>s.type!=="placeholder")||this.store.set({isLoading:!0}),this.store.set({error:null});try{let s=await Fe(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig()});if(r!==this.fetchVersion)return;let l=Ne(s.data.suggestions??[],this.getOptionOverrides()),d=s.data.input??[],c=d[d.length-1],u=this.store.get().text,f,m;if(c?.state==="in_progress"){m=!0;let k=u.toLowerCase().lastIndexOf(c.text.toLowerCase());f=k!==-1?k:a}else m=!1,f=a;let b=l.filter(k=>k.type!=="placeholder")[0],v=null;if(b){let k=X(u,f,m),D=Ae(b.options,k);D&&(v={id:crypto.randomUUID(),placeholder:"",type:b.type,text:D.text,kind:D.kind,suggestionType:b.type,suggestionPlaceholder:b.text,options:b.options??[],metadata:D.metadata},l=l.filter(B=>B!==b))}this.store.set(k=>({suggestions:l,isLoading:!1,isReady:s.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:f,filterInProgress:m,...v?{completedParams:[...k.completedParams,v]}:{}}))}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=X(r.text,r.filterBase,r.filterInProgress),p=r.suggestions.filter(b=>b.type!=="placeholder")[0],l=(p?se(p.options,n):[]).filter(b=>b.is_tappable),d=p?Ae(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 b=r.suggestions.filter(v=>v.type==="placeholder").map(v=>v.text).join(" ");if(b.length>0&&b.toLowerCase().startsWith(r.text.toLowerCase()))return!1}let{rawQuery:u,completedParams:f}=R(r.text,r.completedParams),m=u.length<r.lastRawQuery.length,S=Math.abs(u.length-r.lastRawQuery.length);return m||S>=i?(this.doFetch(u,f),!0):!1};this.debounceTimer=setTimeout(()=>{t(pt)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},lt),this.slowDebounceTimer=setTimeout(()=>t(1),dt)}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(),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}=R(t.text,t.completedParams);a({query:t.text.trim(),raw_query:s,completed_params:l}),this.ctx.afterSubmit?.()}break}case"Tab":{let s=!t.text&&!!t.placeholderText,l=t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable;if(s&&!l){e.preventDefault();let d=t.suggestions.find(c=>c.type==="placeholder");d?this.store.set(c=>({text:t.placeholderText,filterBase:t.placeholderText.length,completedParams:[...c.completedParams,{id:crypto.randomUUID(),placeholder:"",type:d.type,text:t.placeholderText,kind:null,suggestionType:d.type,suggestionPlaceholder:d.text,options:d.options??[]}],suggestions:c.suggestions.filter(u=>u!==d)})):this.store.set({text:t.placeholderText,filterBase:t.placeholderText.length})}else if(l)e.preventDefault(),this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i);else if(t.isDropdownOpen){let d=t.filteredOptions.findIndex(c=>c.is_tappable);d>=0&&(e.preventDefault(),this.clickOrSelect(d,t.filteredOptions,i))}break}case"Escape":this.store.set({activeDropdownIndex:-1});break}}getTappableIndices(e){let i=this.store.get().filteredOptions.map((n,a)=>n.is_tappable?a:-1).filter(n=>n!==-1),r=Array.from({length:e},()=>[]);for(let n of i)r[n%e].push(n);return r.flat()}getEffectiveColumns(){let t=document.getElementById(`${this.ctx.listboxId}-option-0`)?.parentElement;if(!t)return this.ctx.columns;let i=getComputedStyle(t).gridTemplateColumns.split(" ").filter(Boolean).length;return i>0?i:this.ctx.columns}clickOrSelect(e,t,i){let r=document.getElementById(`${i}-option-${e}`);r?r.click():this.ctx.selectOption(t[e])}pillsSetActivePill(e){let t=this.store.get(),i=t.suggestions.filter(p=>p.type!=="placeholder");if(e<0||e>=i.length)return;let r=i[e],n=i.filter((p,s)=>s!==e),a=t.suggestions.filter(p=>p.type==="placeholder");this.store.set({suggestions:[...a,r,...n],pillTapped:!0,activeDropdownIndex:-1})}};var pe=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 ct(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 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(ct(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 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:a,onSelect:p,onHighlight:s,onPillClick:l}=e,d=a&&n.length>0;r&&t.length>0||r&&d?o.classList.add("magicx-aia-dropdown--visible"):o.classList.remove("magicx-aia-dropdown--visible");let f=o.querySelector(".magicx-aia-pill-bar");d?(f||(f=document.createElement("div"),f.className="magicx-aia-pill-bar",f.setAttribute("data-aia-pillbar",""),o.insertBefore(f,o.firstChild)),ce(f,n,0,l,!0)):f&&f.remove();let m=o.querySelector(".magicx-aia-grid");t.length>0?(m||(m=document.createElement("div"),m.className="magicx-aia-grid",o.appendChild(m)),ut(m,t,i,p,s,e.listboxId)):m&&(m.innerHTML="")}function ut(o,e,t,i,r,n){let a=e.map(l=>l.text).join("\0"),p=o.dataset.optionsKey??"",s=a!==p;if(o.dataset.optionsKey=a,s){let l=document.createDocumentFragment();for(let d=0;d<e.length;d++){let c=e[d],u=mt(c,d,t,i,r,n);l.appendChild(u)}o.innerHTML="",o.appendChild(l)}else{let l=o.querySelectorAll(".magicx-aia-option");for(let d=0;d<l.length;d++){let c=l[d],u=d===t;c.setAttribute("aria-selected",String(u)),u?c.classList.add("magicx-aia-option--highlighted"):c.classList.remove("magicx-aia-option--highlighted")}}}function mt(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 Ke(o,e){let t=ue(e.listboxId);return o.appendChild(t),{dropdown:t}}function Pe(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 $e(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 gt='<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 qe(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 a=document.createElement("div");a.className="magicx-aia-sizer",a.setAttribute("aria-hidden","true"),n.appendChild(a);let p=document.createElement("span");a.appendChild(document.createTextNode(" ")),a.appendChild(p);let s=document.createElement("textarea");s.className="magicx-aia-textarea",s.rows=1,s.setAttribute("role","combobox"),s.setAttribute("aria-autocomplete","list"),s.setAttribute("aria-controls",t),s.setAttribute("data-aia-textarea",""),n.appendChild(s);let l=null,d=null;return e.submitButton===void 0?(l=document.createElement("button"),l.type="button",l.className="magicx-aia-submit",l.setAttribute("aria-label","Submit"),l.setAttribute("data-aia-submit",""),l.innerHTML=gt,r.appendChild(l),d=l):e.submitButton!==null&&(d=e.submitButton,d.hasAttribute("data-aia-submit")||d.setAttribute("data-aia-submit",""),r.appendChild(d)),r.addEventListener("click",()=>s.focus()),s.addEventListener("input",()=>{let c=s.value,f=c.length>0&&c[0]!==c[0].toUpperCase()?c[0].toUpperCase()+c.slice(1):c;e.handleChange(f)}),s.addEventListener("keydown",c=>e.handleKeyDown(c)),s.addEventListener("focus",()=>e.store.set({isFocused:!0})),s.addEventListener("blur",()=>e.store.set({isFocused:!1})),d&&d.addEventListener("click",c=>{let u=e.store.get();if(!(!!u.text||u.completedParams.length>0)||!e.onSubmit)return;c.stopPropagation();let{rawQuery:m,completedParams:S}=R(u.text,u.completedParams);e.onSubmit({query:u.text.trim(),raw_query:m,completed_params:S}),e.afterSubmit?.()}),e.autoFocus!==!1&&s.focus(),{textarea:s,dropdown:i,sizer:a,submitButton:l,inlinePillContainer:p}}function ke(o,e,t){let{textarea:i,dropdown:r,sizer:n,submitButton:a,inlinePillContainer:p}=o,{pillPlacement:s,setActivePill:l,selectOption:d,store:c}=t;i.value!==e.text&&(i.value=e.text),e.placeholderText?i.placeholder=e.placeholderText:i.removeAttribute("placeholder"),i.setAttribute("aria-expanded",String(e.isDropdownOpen));let u=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(u?i.setAttribute("aria-activedescendant",u):i.removeAttribute("aria-activedescendant"),e.newParamId?i.classList.add("magicx-aia-textarea--hidden"):i.classList.remove("magicx-aia-textarea--hidden"),a){let f=!!e.text||e.completedParams.length>0;a.disabled=!f}$e(n,e.segments,e.newParamId,!e.text,e.placeholderText),s==="inline"?ce(p,e.actionableSuggestions,0,l):p.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:s==="dropdown",onSelect:d,onHighlight:f=>c.set({activeDropdownIndex:f}),onPillClick:l})}function Ve(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 Te=!1;function Ue(){if(Te||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){Te=!0;return}Te=!0;let o=document.createElement("style");o.setAttribute("data-magicx-aia",""),o.textContent=ft,document.head.appendChild(o)}var ft="";var ht=0;function xt(){return`:ac-${++ht}:`}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 ge=class{constructor(e,t={}){this.store=Ve(Qe());this._listboxId=xt();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),this.fetchController=new le(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.opts.onError,()=>this.sessionId),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"&&(Ue(),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({...Qe(),skipNextFetch:!0}),this.sessionId=crypto.randomUUID(),this.fetchController.doFetch("",[])}destroy(){this.fetchController.dispose(),this.modeController?.destroy(),this.newParamTimer&&clearTimeout(this.newParamTimer),this.suggestionRemovalTimer&&clearTimeout(this.suggestionRemovalTimer),this.externalListeners.clear();for(let e of this.unsubscribers)e();this.unsubscribers=[],this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}setValue(e){this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e)}removeLastParam(){this.pillsController.removeLastParam()}clearNewParamId(){this.store.set({newParamId:null})}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}handleTextChange(e){this.handleChange(e)}handleKeyDown(e){this.keyboardController.handleKeyDown(e)}setFocused(e){this.store.get().isFocused!==e&&this.store.set({isFocused:e})}subscribe(e){return this.externalListeners.add(e),()=>{this.externalListeners.delete(e)}}getState(){return this.store.get()}get listboxId(){return this._listboxId}get isReady(){return this.store.get().isReady}on(e,t){switch(e){case"submit":return this.opts.onSubmit=t,()=>{this.opts.onSubmit=void 0};case"error":return this.opts.onError=t,()=>{this.opts.onError=void 0};case"change":return this.opts.onChange=t,()=>{this.opts.onChange=void 0};case"paramsChange":return this.opts.onParamsChange=t,()=>{this.opts.onParamsChange=void 0};case"stateChange":return this.opts.onStateChange=t,()=>{this.opts.onStateChange=void 0};case"focus":return this.opts.onFocus=t,()=>{this.opts.onFocus=void 0};case"blur":return this.opts.onBlur=t,()=>{this.opts.onBlur=void 0};default:return()=>{}}}update(e){Object.assign(this.opts,e),e.mode!==void 0&&this.modeController?.setMode(e.mode),e.optionsPosition!==void 0&&(this.container.dataset.optionsPosition=e.optionsPosition),e.animations!==void 0&&(this.container.dataset.animations=e.animations?"on":"off"),e.pillPlacement!==void 0&&(this.container.dataset.pillPlacement=e.pillPlacement,this.store.set({})),(e.dropdownTrigger!==void 0||e.closeDropdownOnBlur!==void 0)&&this.store.set({}),e.value!==void 0&&this.store.set({text:e.value}),e.completedParams!==void 0&&this.store.set({completedParams:e.completedParams})}selectOption(e){let t=this.store.get(),i=t.actionableSuggestions[0];if(!i)return;let r=t.filterBase,n=t.text.slice(0,r),a=n.length===0&&t.text.length===0,p=n.length===0&&t.text.length>0&&t.placeholderText.length>0&&t.placeholderText.toLowerCase().startsWith(t.text.toLowerCase());(a||p)&&t.placeholderText&&(n=`${t.placeholderText} `);let s=Ee(n,e.text);s>0&&(n=n.slice(0,n.length-s));let l=n.length>0&&n[n.length-1]!==" ",d=`${n}${l?" ":""}${e.text} `,c=(a||p)&&d.length>0?d[0].toUpperCase()+d.slice(1):d,u=c.toLowerCase().lastIndexOf(e.text.toLowerCase()),f=u>=0?c.slice(u,u+e.text.length):e.text,m={id:crypto.randomUUID(),placeholder:"",type:i.type,text:f,kind:e.kind,suggestionType:i.type,suggestionPlaceholder:i.text,options:i.options??[],metadata:e.metadata},S=t.actionableSuggestions.length-1;this.store.set(b=>({text:c,filterBase:c.length,completedParams:[...b.completedParams,m],newParamId:m.id,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:S>0})),this.suggestionRemovalTimer=window.setTimeout(()=>{this.store.set(b=>({suggestions:b.suggestions.filter(v=>v!==i)}))},400)}recomputeDerived(e,t){if(this.derivedInProgress)return;this.derivedInProgress=!0;let i=Le(e.text,e.completedParams),r=e.suggestions.filter(v=>v.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?X(e.text,p,e.filterInProgress):"",d=n?a?a(l.trim()):n.options??[]:[],c=se(d,l),u=e.suggestions.filter(v=>v.type==="placeholder").map(v=>v.text).join(" "),f=this.opts.dropdownTrigger??"auto",m=this.opts.closeDropdownOnBlur??!0,S=!1;if(f==="auto"){let v=m?e.isFocused:!0;S=!e.isLoading&&c.length>0&&v}else f==="manual"&&(S=!e.isLoading&&c.length>0&&e.pillTapped);this.store.set({segments:i,actionableSuggestions:r,filteredOptions:c,placeholderText:u,isDropdownOpen:S}),this.derivedInProgress=!1;let b=this.store.get();for(let v of this.externalListeners)v(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 V(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=qe(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&ke(this.domRefs,this.store.get(),t)}),ke(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=Ke(this.container,e),this.subscribeBatchedRender(()=>{this.dropdownRefs&&Pe(this.dropdownRefs,this.store.get(),e)}),Pe(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}=Re(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 fe({onSubmit:o,onError:e,optionOverrides:t,maskCompletedText:i,apiConfig:r,columns:n=2,dropdownTrigger:a,closeDropdownOnBlur:p,onFocus:s,onBlur:l,value:d,completedParams:c,onChange:u,onParamsChange:f}){let m=(0,x.useRef)(null),[S,b]=(0,x.useState)(null),v=(0,x.useRef)(o);v.current=o;let k=(0,x.useRef)(e);k.current=e;let D=(0,x.useRef)(u);D.current=u;let B=(0,x.useRef)(f);B.current=f;let z=(0,x.useRef)(s);z.current=s;let J=(0,x.useRef)(l);J.current=l,(0,x.useEffect)(()=>{if(typeof document>"u")return;let w=new ge(document.createElement("div"),{renderMode:"headless",apiConfig:r,optionOverrides:t,maskCompletedText:i,columns:n,dropdownTrigger:a,closeDropdownOnBlur:p,value:d,completedParams:c,onSubmit:(..._)=>v.current?.(..._),onError:(..._)=>k.current?.(..._),onChange:(..._)=>D.current?.(..._),onParamsChange:(..._)=>B.current?.(..._),onFocus:()=>z.current?.(),onBlur:()=>J.current?.()});m.current=w,b(w.getState());let g=w.subscribe(_=>b(_));return()=>{g(),w.destroy(),m.current===w&&(m.current=null)}},[]);let h=m.current,I=(0,x.useCallback)(()=>{},[]);(0,x.useEffect)(()=>{d!==void 0&&h?.setValue(d)},[d,h]),(0,x.useEffect)(()=>{c!==void 0&&h?.setCompletedParams(c)},[c,h]);let Y=JSON.stringify(r??null),T=(0,x.useRef)(t),F=(0,x.useRef)(0);if(t!==T.current){let w=T.current,g=t,_=Object.keys(w??{}),G=Object.keys(g??{});(_.length!==G.length||G.some(W=>!w?.[W]||g[W]!==w[W]))&&F.current++,T.current=t}(0,x.useEffect)(()=>{h?.update({apiConfig:r,optionOverrides:t,dropdownTrigger:a,closeDropdownOnBlur:p})},[Y,F.current,a,p,h]);let he=(0,x.useCallback)(w=>{if(!h)return;let g=w.target.value,G=g.length>0&&!w.nativeEvent?.isComposing&&g[0]!==g[0].toUpperCase()?g[0].toUpperCase()+g.slice(1):g;h.handleTextChange(G)},[h]),xe=(0,x.useCallback)(w=>{h?.handleKeyDown(w.nativeEvent)},[h]),Z=(0,x.useCallback)(()=>h?.setFocused(!0),[h]),M=(0,x.useCallback)(()=>h?.setFocused(!1),[h]),U=(0,x.useCallback)(w=>h?.setActivePill(w),[h]),E=(0,x.useCallback)(()=>h?.removeLastParam(),[h]),be=(0,x.useCallback)(()=>h?.clearNewParamId(),[h]),N=(0,x.useCallback)(()=>h?.reset(),[h]),ee=(0,x.useCallback)(w=>h?.selectOption(w),[h]),ve=(0,x.useCallback)(w=>h?.setActiveDropdownIndex(w),[h]);if(!h)return{completedParams:c??[],suggestionPills:[],setActivePill:I,removeLastParam:I,segments:[],newParamId:null,clearNewParamId:I,suggestions:[],activeIndex:-1,isReady:!1,isLoading:!0,error:null,inputProps:{value:d??"",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 y=S??h.getState(),Q=d!==void 0?d:y.text,ye=c!==void 0?c:y.completedParams,K=y.actionableSuggestions,te=K[0],we=y.filteredOptions,Se=y.activeDropdownIndex>=0?`${h.listboxId}-option-${y.activeDropdownIndex}`:void 0;return{completedParams:ye,suggestionPills:K,setActivePill:U,removeLastParam:E,segments:y.segments,newParamId:y.newParamId,clearNewParamId:be,suggestions:y.suggestions,activeIndex:y.activeDropdownIndex,isReady:y.isReady,isLoading:y.isLoading,error:y.error,inputProps:{value:Q,placeholder:y.placeholderText||void 0,onChange:he,onKeyDown:xe,onFocus:Z,onBlur:M,role:"combobox","aria-expanded":y.isDropdownOpen,"aria-activedescendant":Se,"aria-autocomplete":"list","aria-controls":h.listboxId},reset:N,dropdownProps:{suggestions:te?[{...te,options:we}]:[],activeIndex:y.activeDropdownIndex,onSelect:ee,onHighlight:ve,isOpen:y.isDropdownOpen,id:h.listboxId,pills:K,onPillClick:U}}}var C=require("react/jsx-runtime");function bt(o){return o!=="auto"?o:typeof window>"u"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}var Ge=(0,A.forwardRef)(function({onSubmit:e,onError:t,optionOverrides:i,maskCompletedText:r,className:n,apiConfig:a,columns:p,pillPlacement:s="inline",mode:l="auto",optionsPosition:d="below",animations:c=!0,dropdownTrigger:u,closeDropdownOnBlur:f,autoFocus:m=!0,onFocus:S,onBlur:b,value:v,completedParams:k,onChange:D,onParamsChange:B,submitButton:z},J){let h=(0,A.useRef)(null),I=(0,A.useRef)(null),Y=(0,A.useRef)(()=>{}),T=(0,A.useRef)(null);(0,A.useEffect)(()=>{let g=h.current;if(g)return T.current?T.current.setMode(l):T.current=new V(g,l),()=>{T.current?.destroy(),T.current=null}},[l]);let{completedParams:F,suggestionPills:he,setActivePill:xe,segments:Z,newParamId:M,clearNewParamId:U,inputProps:E,dropdownProps:be,reset:N}=fe({onSubmit:g=>Y.current(g),onError:t,optionOverrides:i,maskCompletedText:r,apiConfig:a,columns:p,dropdownTrigger:u,closeDropdownOnBlur:f,onFocus:S,onBlur:b,value:v,completedParams:k,onChange:D,onParamsChange:B}),ee=E.onFocus;(0,A.useEffect)(()=>{if(!m)return;let g=I.current;g&&(document.activeElement===g?ee():g.focus())},[ee,m]),(0,A.useEffect)(()=>{if(!M)return;let g=window.setTimeout(()=>U(),650);return()=>window.clearTimeout(g)},[M,U]),(0,A.useImperativeHandle)(J,()=>({focus:()=>I.current?.focus(),blur:()=>I.current?.blur(),reset:N,setMode:g=>T.current?.setMode(g)}),[N]);let ve=()=>{I.current?.focus()},y=!!E.value||F.length>0,Q=(0,A.useCallback)(()=>{if(!y)return;let{rawQuery:g,completedParams:_}=R(E.value,F);e({query:E.value.trim(),raw_query:g,completed_params:_}),N()},[y,E.value,F,e,N]);Y.current=Q;let{onChange:ye,placeholder:K,...te}=E,we=!E.value,Se=s==="inline",w=s==="dropdown";return(0,C.jsxs)("div",{ref:h,className:`magicx-aia ${P.container} ${n??""}`,"data-pill-placement":s,"data-options-position":d,"data-animations":c?"on":"off","data-mode":bt(l),children:[(0,C.jsx)(re,{...be,showPills:w}),(0,C.jsxs)("div",{className:P.inputWrapper,onClick:ve,children:[(0,C.jsxs)("div",{className:P.editorArea,"data-aia-editor":"",children:[(0,C.jsxs)("div",{className:P.sizerContent,"aria-hidden":"true",children:[we&&K?(0,C.jsxs)("span",{className:P.placeholderText,children:[K," "]}):(0,C.jsxs)("span",{className:`${P.sizerText} ${M?P.sizerTextVisible:""}`,children:[Z.map((g,_)=>{if(g.type==="completed"&&g.param.id===M){let W=`${P.shimmerRevealed} ${P.shimmerSweep}`;return(0,C.jsx)("span",{className:W,children:g.value},`${_}-${g.type}`)}return(0,C.jsx)("span",{children:g.value},`${_}-${g.type}`)}),Z.length===0&&"\xA0"]})," ",Se&&(0,C.jsx)(ie,{pills:he,activePillIndex:0,onSelectPill:xe})]}),(0,C.jsx)("textarea",{ref:I,"data-aia-textarea":"",className:`${P.textarea} ${M?P.textareaHidden:""}`,rows:1,onChange:ye,...te})]}),z===null?null:z===void 0?(0,C.jsx)("button",{type:"button","data-aia-submit":"",className:P.submitButton,disabled:!y,onClick:g=>{g.stopPropagation(),Q()},"aria-label":"Submit",children:(0,C.jsx)("svg",{width:"18",height:"18",viewBox:"0 0 18 18",fill:"none",role:"img","aria-label":"Submit",children:(0,C.jsx)("path",{d:"M9 14V4M9 4L4 9M9 4L14 9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}):(0,C.jsx)("span",{"data-aia-submit":"",className:P.submitSlot,onClick:g=>{y&&(g.stopPropagation(),Q())},children:z})]})]})});0&&(module.exports={AIAutocomplete,AIAutocompleteDropdown,useAIAutocomplete});
692
+ `,document.head.appendChild(o)}var b=require("react");function T(o,e){let t=o,i={},n=[];for(let r of e){let s=(i[r.type]??0)+1;i[r.type]=s;let a=`{{${r.type.toUpperCase().replace(/\s+/g,"_")}_${s}}}`,l=t.indexOf(r.text);l!==-1&&(t=t.slice(0,l)+a+t.slice(l+r.text.length)),n.push({...r,placeholder:a})}return{rawQuery:t,completedParams:n}}function X(o,e,t){let i=o.slice(e);if(t||e===0||o[e-1]===" ")return i;let n=i.indexOf(" ");return n===-1?"":i.slice(n+1)}function Le(o,e){let t=o.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let i=t.split(" "),n=e.toLowerCase();for(let r=0;r<i.length;r++){let s=i.slice(r).join(" ");if(n.startsWith(s.toLowerCase())){let d=t.length-s.length;return o.length-d}}return 0}function le(o,e){if(!o)return[];let t=e.trimStart();if(!t)return o;let i=t.toLowerCase();return o.filter(n=>!n.is_tappable||n.text.toLowerCase().includes(i))}function Pe(o,e){if(!o)return null;let t=e.trim();if(!t)return null;let i=t.toLowerCase();return o.find(n=>n.is_tappable&&n.text.toLowerCase()===i)??null}var V=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 Re(o,e){let t=[],i=0;for(let r of e){let s=o.indexOf(r.text,i);s!==-1&&(s>i&&t.push({type:"text",value:o.slice(i,s)}),t.push({type:"completed",value:r.text,param:r}),i=s+r.text.length)}let n=o.slice(i);return n&&t.push({type:"text",value:n}),t}function Me(o,e){let t=[],i=[],n=0;for(let r of e){let s=o.indexOf(r.text,n);s===-1?i.push(r):(t.push(r),n=s+r.text.length)}return{valid:t,invalid:i}}var Q=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 st="https://api.ai-autocomplete.com/api/suggest",He="/api/telemetry/events",Be=new WeakMap;function ze(o){return o?.type==="accessToken"}function at(o){if(!(!o||ze(o)))return o}function lt(o){let e=Be.get(o.getAccessToken);return e||(e=new Q(o),Be.set(o.getAccessToken,e)),e}function dt(o){let e=o??st;try{return`${new URL(e).origin}${He}`}catch{return`https://api.ai-autocomplete.com${He}`}}async function pt(o){if(ze(o))return`Bearer ${await lt(o).getToken()}`;let e=at(o),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}async function Fe(o){try{let e=await pt(o.apiConfig);if(!e)return;let t=dt(o.apiConfig?.endpoint),i={"Content-Type":"application/json",Authorization:e,...o.apiConfig?.appIdentifier&&{"X-App-Identifier":o.apiConfig.appIdentifier},...o.apiConfig?.headers},n=JSON.stringify({source:o.source,session_id:o.sessionId,type:o.type,at:new Date().toISOString(),query_data:o.queryData});await fetch(t,{method:"POST",headers:i,body:n})}catch{}}var ct="0.1.36",Ne=!1;function ut(){return crypto.randomUUID()}function mt(o,e){return{placeholder:o.placeholder,type:o.type,...e&&{text:o.text},kind:o.kind}}function qe(o){return o?.type==="accessToken"}function gt(o){if(!(!o||qe(o)))return o}var Ke=new WeakMap;function ft(o){let e=Ke.get(o.getAccessToken);return e||(e=new Q(o),Ke.set(o.getAccessToken,e)),e}function ht(o,e,t,i){let n=e.find(s=>s.type==="contact"&&s.metadata?.contact_account_count)?.metadata?.contact_account_count,r=typeof n=="number"?n:void 0;return{data:{raw_query:o,completed_params:e.map(s=>mt(s,t)),...r!=null&&{contact_account_count:r}},meta:{request_id:ut(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:ct,session_id:i}}}function xt(o){return{"Content-Type":"application/json",...o?.appIdentifier&&{"X-App-Identifier":o.appIdentifier},...o?.headers}}async function $e(o,e,t,i,n){return fetch(o,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:n})}async function Ue(o,e,t){let i=t.apiConfig,n=!t.maskCompletedText,r=ht(o,e,n,t.sessionId),s=xt(i),d=i?.endpoint??"https://api.ai-autocomplete.com/api/suggest",a=JSON.stringify(r);if(qe(i)){let m=ft(i),f=await m.getToken(),h=await $e(d,s,f,a,t.signal);if(h.status===401){let y=await m.getToken(!0);h=await $e(d,s,y,a,t.signal)}if(!h.ok)throw new Error(`API error: ${h.status} ${h.statusText}`);return h.json()}let l=gt(i),p=l?.apiKey??"";if(!p&&!Ne&&(Ne=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),p){let m=l?.authScheme??"Bearer";s.Authorization=m==="Basic"?`Basic ${btoa(p)}`:`Bearer ${p}`}let c=await fetch(d,{method:"POST",headers:s,body:a,signal:t.signal});if(!c.ok)throw new Error(`API error: ${c.status} ${c.statusText}`);return c.json()}function Ve(o,e){return e?o.map(t=>{let i=e[t.type];if(!i)return t;let n=i("");if(n.length===0)return t;let r=new Set(n.map(d=>d.text)),s=(t.options??[]).filter(d=>!r.has(d.text));return{...t,options:[...n,...s]}}):o}var bt=100,vt=300,yt=2,de=class{constructor(e,t,i,n,r,s,d={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=n;this.getOnError=r;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 n=++this.fetchVersion,r=this.store.get(),s=r.text.length;r.suggestions.some(a=>a.type!=="placeholder")||this.store.set({isLoading:!0}),this.store.set({error:null});try{let a=await Ue(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig()});if(n!==this.fetchVersion)return;let l=Ve(a.data.suggestions??[],this.getOptionOverrides()),p=a.data.input??[],c=p[p.length-1],m=this.store.get().text,f,h;if(c?.state==="in_progress"){h=!0;let C=m.toLowerCase().lastIndexOf(c.text.toLowerCase());f=C!==-1?C:s}else h=!1,f=s;let v=l.filter(C=>C.type!=="placeholder")[0],x=null;if(v){let C=X(m,f,h),O=Pe(v.options,C);O&&(x={id:crypto.randomUUID(),placeholder:"",type:v.type,text:O.text,kind:O.kind,suggestionType:v.type,suggestionPlaceholder:v.text,options:v.options??[],metadata:O.metadata},l=l.filter(z=>z!==v),this.callbacks.onAutoMatch?.({active:v,matched:O,rawQuery:e}))}this.store.set(C=>({suggestions:l,isLoading:!1,isReady:a.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:f,filterInProgress:h,...x?{completedParams:[...C.completedParams,x]}:{}}))}catch(a){if(n===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 n=this.store.get();if(!n.text&&n.completedParams.length===0)return this.doFetch("",[]),!0;let r=X(n.text,n.filterBase,n.filterInProgress),d=n.suggestions.filter(v=>v.type!=="placeholder")[0],l=(d?le(d.options,r):[]).filter(v=>v.is_tappable),p=d?Pe(d.options,r)!==null:!1,c=r.trim().length>0;if(l.length>0&&!p&&c)return!1;if(n.completedParams.length===0&&n.text.length>0){let v=n.suggestions.filter(x=>x.type==="placeholder").map(x=>x.text).join(" ");if(v.length>0&&v.toLowerCase().startsWith(n.text.toLowerCase()))return!1}let{rawQuery:m,completedParams:f}=T(n.text,n.completedParams),h=m.length<n.lastRawQuery.length,y=Math.abs(m.length-n.lastRawQuery.length);return h||y>=i?(this.doFetch(m,f),!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:n}=this.ctx,r=this.getEffectiveColumns(),s=n(),d=this.getTappableIndices(r);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<r){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%r<r-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%r>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}=T(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((r,s)=>r.is_tappable?s:-1).filter(r=>r!==-1),n=Array.from({length:e},()=>[]);for(let r of i)n[r%e].push(r);return n.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 n=document.getElementById(`${i}-option-${e}`);n?n.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 n=i[e],r=i.filter((d,a)=>a!==e),s=t.suggestions.filter(d=>d.type==="placeholder");this.store.set({suggestions:[...s,n,...r],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 n=i[e],r=i.filter((d,a)=>a!==e),s=t.suggestions.filter(d=>d.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:d}=T(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:d,selectedPill:n.text,otherPills:r.map(a=>a.text)})}this.store.set({suggestions:[...s,n,...r],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(n=>({completedParams:n.completedParams.slice(0,-1),suggestions:[i,...n.suggestions],activeDropdownIndex:-1}))}};function wt(o){return o===0?.4:o===1?.3:.15}function ue(o,e,t,i,n=!1){let r=o.querySelector(".magicx-aia-pill-list");r||(r=document.createElement("span"),r.className="magicx-aia-pill-list",o.appendChild(r));let s=new Map;for(let a of r.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${n?" magicx-aia-pill--rounded":""}${a===t?" magicx-aia-pill--active":""}`,c.style.opacity=String(wt(a)),c.onclick=()=>i(a),r.children[a]!==c&&r.insertBefore(c,r.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:n,pills:r,showPills:s,onSelect:d,onHighlight:a,onPillClick:l}=e,p=s&&r.length>0;n&&t.length>0||n&&p?o.classList.add("magicx-aia-dropdown--visible"):o.classList.remove("magicx-aia-dropdown--visible");let f=o.querySelector(".magicx-aia-pill-bar");p?(f||(f=document.createElement("div"),f.className="magicx-aia-pill-bar",f.setAttribute("data-aia-pillbar",""),o.insertBefore(f,o.firstChild)),ue(f,r,0,l,!0)):f&&f.remove();let h=o.querySelector(".magicx-aia-grid");t.length>0?(h||(h=document.createElement("div"),h.className="magicx-aia-grid",o.appendChild(h)),St(h,t,i,d,a,e.listboxId)):h&&(h.innerHTML="")}function St(o,e,t,i,n,r){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,n,r);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,n,r){let s=document.createElement("div");s.id=`${r}-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",()=>n(e))),s}function Qe(o,e){let t=me(e.listboxId);return o.appendChild(t),{dropdown:t}}function ke(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 Ge(o,e,t,i,n){let r=o.querySelector(".magicx-aia-sizer-text"),s=o.querySelector(".magicx-aia-placeholder");if(i&&n){r&&(r.style.display="none"),s||(s=document.createElement("span"),s.className="magicx-aia-placeholder",o.insertBefore(s,o.firstChild)),s.style.display="",s.textContent=`${n} `,o.dataset.segmentKey="";return}s&&(s.style.display="none"),r||(r=document.createElement("span"),r.className="magicx-aia-sizer-text",o.insertBefore(r,o.firstChild)),r.style.display="",r.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??"",r.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,r.appendChild(c)}e.length===0&&(r.textContent="\xA0")}}var Ct='<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 We(o,e){let{listboxId:t}=e,i=me(t);o.appendChild(i);let n=document.createElement("div");n.className="magicx-aia-input-wrapper",o.appendChild(n);let r=document.createElement("div");r.className="magicx-aia-editor",r.setAttribute("data-aia-editor",""),n.appendChild(r);let s=document.createElement("div");s.className="magicx-aia-sizer",s.setAttribute("aria-hidden","true"),r.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",""),r.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=Ct,n.appendChild(l),p=l):e.submitButton!==null&&(p=e.submitButton,p.hasAttribute("data-aia-submit")||p.setAttribute("data-aia-submit",""),n.appendChild(p)),n.addEventListener("click",()=>a.focus()),a.addEventListener("input",()=>{let c=a.value,f=c.length>0&&c[0]!==c[0].toUpperCase()?c[0].toUpperCase()+c.slice(1):c;e.handleChange(f)}),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:h,completedParams:y}=T(m.text,m.completedParams);e.onSubmit({query:m.text.trim(),raw_query:h,completed_params:y}),e.afterSubmit?.()}),e.autoFocus!==!1&&a.focus(),{textarea:a,dropdown:i,sizer:s,submitButton:l,inlinePillContainer:d}}function Te(o,e,t){let{textarea:i,dropdown:n,sizer:r,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 f=!!e.text||e.completedParams.length>0;s.disabled=!f}Ge(r,e.segments,e.newParamId,!e.text,e.placeholderText),a==="inline"?ue(d,e.actionableSuggestions,0,l):d.innerHTML="",ge(n,{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:f=>c.set({activeDropdownIndex:f}),onPillClick:l})}function je(o){let e=o,t=new Set;return{get:()=>e,set:i=>{let n=typeof i=="function"?i(e):i,r={...e,...n},s=e;e=r;for(let d of t)d(r,s)},subscribe:i=>(t.add(i),()=>{t.delete(i)})}}var Oe=!1;function Xe(){if(Oe||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){Oe=!0;return}Oe=!0;let o=document.createElement("style");o.setAttribute("data-magicx-aia",""),o.textContent=_t,document.head.appendChild(o)}var _t="";var At=0;function Pt(){return`:ac-${++At}:`}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 fe=class{constructor(e,t={}){this.store=je(Je());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:n,otherPills:r})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:n,other_pills:r})}}),this.fetchController=new de(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.opts.onError,()=>this.sessionId,{onAutoMatch:({active:i,matched:n,rawQuery:r})=>{this.fireTelemetry("option",{raw_query:r,selected_option:n.text,other_options:(i.options??[]).filter(s=>s.text!==n.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,n)=>{this.recomputeDerived(i,n)})),this.unsubscribers.push(this.store.subscribe((i,n)=>{i.text!==n.text&&this.opts.onChange?.(i.text),i.completedParams!==n.completedParams&&this.opts.onParamsChange?.(i.completedParams),i.isFocused!==n.isFocused&&(i.isFocused?this.opts.onFocus?.():this.opts.onBlur?.()),this.opts.onStateChange?.(i)})),this.renderMode!=="headless"&&(Xe(),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(),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:n}=T(t.text,t.completedParams);this.fireTelemetry("option",{raw_query:n,selected_option:e.text,other_options:t.filteredOptions.filter(x=>x.text!==e.text).map(x=>x.text)});let r=t.filterBase,s=t.text.slice(0,r),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=Le(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,f=m.toLowerCase().lastIndexOf(e.text.toLowerCase()),h=f>=0?m.slice(f,f+e.text.length):e.text,y={id:crypto.randomUUID(),placeholder:"",type:i.type,text:h,kind:e.kind,suggestionType:i.type,suggestionPlaceholder:i.text,options:i.options??[],metadata:e.metadata},v=t.actionableSuggestions.length-1;this.store.set(x=>({text:m,filterBase:m.length,completedParams:[...x.completedParams,y],newParamId:y.id,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:v>0})),this.suggestionRemovalTimer=window.setTimeout(()=>{this.store.set(x=>({suggestions:x.suggestions.filter(C=>C!==i)}))},400)}fireTelemetry(e,t){let i=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");Fe({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=Re(e.text,e.completedParams),n=e.suggestions.filter(x=>x.type!=="placeholder"),r=n[0],s=r?this.opts.optionOverrides?.[r.type]:void 0,d=Math.min(e.filterBase,e.text.length),l=e.lastRawQuery!==""||d>0?X(e.text,d,e.filterInProgress):"",p=r?s?s(l.trim()):r.options??[]:[],c=le(p,l),m=e.suggestions.filter(x=>x.type==="placeholder").map(x=>x.text).join(" "),f=this.opts.dropdownTrigger??"auto",h=this.opts.closeDropdownOnBlur??!0,y=!1;if(f==="auto"){let x=h?e.isFocused:!0;y=!e.isLoading&&c.length>0&&x}else f==="manual"&&(y=!e.isLoading&&c.length>0&&e.pillTapped);this.store.set({segments:i,actionableSuggestions:n,filteredOptions:c,placeholderText:m,isDropdownOpen:y}),this.derivedInProgress=!1;let v=this.store.get();for(let x of this.externalListeners)x(v)}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 V(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=We(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&Te(this.domRefs,this.store.get(),t)}),Te(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&&ke(this.dropdownRefs,this.store.get(),e)}),ke(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:n}=Me(e,t.completedParams);n.length>0&&this.store.set(r=>({completedParams:i,suggestions:[...n.map(s=>({type:s.suggestionType,text:s.suggestionPlaceholder,required:!0,options:s.options})),...r.suggestions]}))}};function he({onSubmit:o,onError:e,optionOverrides:t,maskCompletedText:i,apiConfig:n,columns:r=2,dropdownTrigger:s,closeDropdownOnBlur:d,onFocus:a,onBlur:l,value:p,completedParams:c,onChange:m,onParamsChange:f,source:h}){let y=(0,b.useRef)(null),[v,x]=(0,b.useState)(null),C=(0,b.useRef)(o);C.current=o;let O=(0,b.useRef)(e);O.current=e;let z=(0,b.useRef)(m);z.current=m;let F=(0,b.useRef)(f);F.current=f;let J=(0,b.useRef)(a);J.current=a;let G=(0,b.useRef)(l);G.current=l,(0,b.useEffect)(()=>{if(typeof document>"u")return;let u=new fe(document.createElement("div"),{renderMode:"headless",apiConfig:n,optionOverrides:t,maskCompletedText:i,columns:r,dropdownTrigger:s,closeDropdownOnBlur:d,source:h,value:p,completedParams:c,onSubmit:(...k)=>C.current?.(...k),onError:(...k)=>O.current?.(...k),onChange:(...k)=>z.current?.(...k),onParamsChange:(...k)=>F.current?.(...k),onFocus:()=>J.current?.(),onBlur:()=>G.current?.()});y.current=u,x(u.getState());let I=u.subscribe(k=>x(k));return()=>{I(),u.destroy(),y.current===u&&(y.current=null)}},[]);let g=y.current,A=(0,b.useCallback)(()=>{},[]);(0,b.useEffect)(()=>{p!==void 0&&g?.setValue(p)},[p,g]),(0,b.useEffect)(()=>{c!==void 0&&g?.setCompletedParams(c)},[c,g]);let L=JSON.stringify(n??null),M=(0,b.useRef)(t),Y=(0,b.useRef)(0);if(t!==M.current){let u=M.current,I=t,k=Object.keys(u??{}),$=Object.keys(I??{});(k.length!==$.length||$.some(Ie=>!u?.[Ie]||I[Ie]!==u[Ie]))&&Y.current++,M.current=t}(0,b.useEffect)(()=>{g?.update({apiConfig:n,optionOverrides:t,dropdownTrigger:s,closeDropdownOnBlur:d})},[L,Y.current,s,d,g]);let xe=(0,b.useCallback)(u=>{if(!g)return;let I=u.target.value,$=I.length>0&&!u.nativeEvent?.isComposing&&I[0]!==I[0].toUpperCase()?I[0].toUpperCase()+I.slice(1):I;g.handleTextChange($)},[g]),Z=(0,b.useCallback)(u=>{g?.handleKeyDown(u.nativeEvent)},[g]),H=(0,b.useCallback)(()=>g?.setFocused(!0),[g]),ee=(0,b.useCallback)(()=>g?.setFocused(!1),[g]),E=(0,b.useCallback)(u=>g?.setActivePill(u),[g]),be=(0,b.useCallback)(()=>g?.removeLastParam(),[g]),N=(0,b.useCallback)(()=>g?.clearNewParamId(),[g]),te=(0,b.useCallback)(()=>g?.reset(),[g]),ve=(0,b.useCallback)(u=>g?.selectOption(u),[g]),K=(0,b.useCallback)(u=>g?.setActiveDropdownIndex(u),[g]);if(!g)return{completedParams:c??[],suggestionPills:[],setActivePill:A,removeLastParam:A,segments:[],newParamId:null,clearNewParamId:A,suggestions:[],activeIndex:-1,isReady:!1,isLoading:!0,error:null,inputProps:{value:p??"",placeholder:void 0,onChange:A,onKeyDown:A,onFocus:A,onBlur:A,role:"combobox","aria-expanded":!1,"aria-activedescendant":void 0,"aria-autocomplete":"list","aria-controls":""},reset:A,dropdownProps:{suggestions:[],activeIndex:-1,onSelect:A,onHighlight:A,isOpen:!1,id:"",pills:[],onPillClick:A}};let w=v??g.getState(),ye=p!==void 0?p:w.text,oe=c!==void 0?c:w.completedParams,W=w.actionableSuggestions,ie=W[0],we=w.filteredOptions,Se=w.activeDropdownIndex>=0?`${g.listboxId}-option-${w.activeDropdownIndex}`:void 0;return{completedParams:oe,suggestionPills:W,setActivePill:E,removeLastParam:be,segments:w.segments,newParamId:w.newParamId,clearNewParamId:N,suggestions:w.suggestions,activeIndex:w.activeDropdownIndex,isReady:w.isReady,isLoading:w.isLoading,error:w.error,inputProps:{value:ye,placeholder:w.placeholderText||void 0,onChange:xe,onKeyDown:Z,onFocus:H,onBlur:ee,role:"combobox","aria-expanded":w.isDropdownOpen,"aria-activedescendant":Se,"aria-autocomplete":"list","aria-controls":g.listboxId},reset:te,dropdownProps:{suggestions:ie?[{...ie,options:we}]:[],activeIndex:w.activeDropdownIndex,onSelect:ve,onHighlight:K,isOpen:w.isDropdownOpen,id:g.listboxId,pills:W,onPillClick:E}}}var S=require("react/jsx-runtime");function kt(o){return o!=="auto"?o:typeof window>"u"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}var Ye=(0,_.forwardRef)(function({onSubmit:e,onError:t,optionOverrides:i,maskCompletedText:n,className:r,apiConfig:s,columns:d,pillPlacement:a="inline",mode:l="auto",optionsPosition:p="below",animations:c=!0,dropdownTrigger:m,closeDropdownOnBlur:f,autoFocus:h=!0,onFocus:y,onBlur:v,value:x,completedParams:C,onChange:O,onParamsChange:z,submitButton:F},J){let G=(0,_.useRef)(null),g=(0,_.useRef)(null),A=(0,_.useRef)(()=>{}),L=(0,_.useRef)(null);(0,_.useEffect)(()=>{let u=G.current;if(u)return L.current?L.current.setMode(l):L.current=new V(u,l),()=>{L.current?.destroy(),L.current=null}},[l]);let{completedParams:M,suggestionPills:Y,setActivePill:xe,segments:Z,newParamId:H,clearNewParamId:ee,inputProps:E,dropdownProps:be,reset:N}=he({onSubmit:u=>A.current(u),onError:t,optionOverrides:i,maskCompletedText:n,apiConfig:s,columns:d,dropdownTrigger:m,closeDropdownOnBlur:f,onFocus:y,onBlur:v,value:x,completedParams:C,onChange:O,onParamsChange:z,source:"full-sdk"}),te=E.onFocus;(0,_.useEffect)(()=>{if(!h)return;let u=g.current;u&&(document.activeElement===u?te():u.focus())},[te,h]),(0,_.useEffect)(()=>{if(!H)return;let u=window.setTimeout(()=>ee(),650);return()=>window.clearTimeout(u)},[H,ee]),(0,_.useImperativeHandle)(J,()=>({focus:()=>g.current?.focus(),blur:()=>g.current?.blur(),reset:N,setMode:u=>L.current?.setMode(u)}),[N]);let ve=()=>{g.current?.focus()},K=!!E.value||M.length>0,w=(0,_.useCallback)(()=>{if(!K)return;let{rawQuery:u,completedParams:I}=T(E.value,M);e({query:E.value.trim(),raw_query:u,completed_params:I}),N()},[K,E.value,M,e,N]);A.current=w;let{onChange:ye,placeholder:oe,...W}=E,ie=!E.value,we=a==="inline",Se=a==="dropdown";return(0,S.jsxs)("div",{ref:G,className:`magicx-aia ${P.container} ${r??""}`,"data-pill-placement":a,"data-options-position":p,"data-animations":c?"on":"off","data-mode":kt(l),children:[(0,S.jsx)(ae,{...be,showPills:Se}),(0,S.jsxs)("div",{className:P.inputWrapper,onClick:ve,children:[(0,S.jsxs)("div",{className:P.editorArea,"data-aia-editor":"",children:[(0,S.jsxs)("div",{className:P.sizerContent,"aria-hidden":"true",children:[ie&&oe?(0,S.jsxs)("span",{className:P.placeholderText,children:[oe," "]}):(0,S.jsxs)("span",{className:`${P.sizerText} ${H?P.sizerTextVisible:""}`,children:[Z.map((u,I)=>{if(u.type==="completed"&&u.param.id===H){let $=`${P.shimmerRevealed} ${P.shimmerSweep}`;return(0,S.jsx)("span",{className:$,children:u.value},`${I}-${u.type}`)}return(0,S.jsx)("span",{children:u.value},`${I}-${u.type}`)}),Z.length===0&&"\xA0"]})," ",we&&(0,S.jsx)(re,{pills:Y,activePillIndex:0,onSelectPill:xe})]}),(0,S.jsx)("textarea",{ref:g,"data-aia-textarea":"",className:`${P.textarea} ${H?P.textareaHidden:""}`,rows:1,onChange:ye,...W})]}),F===null?null:F===void 0?(0,S.jsx)("button",{type:"button","data-aia-submit":"",className:P.submitButton,disabled:!K,onClick:u=>{u.stopPropagation(),w()},"aria-label":"Submit",children:(0,S.jsx)("svg",{width:"18",height:"18",viewBox:"0 0 18 18",fill:"none",role:"img","aria-label":"Submit",children:(0,S.jsx)("path",{d:"M9 14V4M9 4L4 9M9 4L14 9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}):(0,S.jsx)("span",{"data-aia-submit":"",className:P.submitSlot,onClick:u=>{K&&(u.stopPropagation(),w())},children:F})]})]})});0&&(module.exports={AIAutocomplete,AIAutocompleteDropdown,useAIAutocomplete});
693
693
  //# sourceMappingURL=index.js.map