@magicx-eng/ai-autocomplete-react 0.1.39 → 0.1.41

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/README.md CHANGED
@@ -21,6 +21,7 @@ A React/TypeScript SDK that provides a guided AI-powered autocomplete experience
21
21
  - **Ref forwarding** — imperative `focus()`, `blur()`, `reset()`, and `setMode()` via ref
22
22
  - **Accessible** — ARIA combobox 1.2 pattern with `role="listbox"`, `aria-activedescendant`
23
23
  - **Animations** — option selection streak animation, text shimmer on newly added params
24
+ - **Loading skeleton** — while a fetch is in flight, the dropdown and inline pills keep the previous layout (same count and widths) with their text masked and a shimmer pulse. The skeleton is held back until the selection streak animation finishes, so taps don't visually "stutter" into loading.
24
25
  - **Lightweight** — styles auto-injected at runtime
25
26
  - **TypeScript first** — full type definitions shipped with the package
26
27
 
@@ -269,7 +270,7 @@ The headless hook for Tier 2. Accepts the same props as `<AIAutocomplete />` exc
269
270
  | `newParamId` | `string \| null` | ID of the most recently added param (for shimmer animation). |
270
271
  | `suggestions` | `Suggestion[]` | All suggestions from server (including placeholder type). |
271
272
  | `activeIndex` | `number` | Highlighted option index. `-1` = none. |
272
- | `isLoading` | `boolean` | Fetch in progress. |
273
+ | `isLoading` | `boolean` | True when the dropdown should render its loading skeleton — a fetch is in flight, no option-selection animation is playing, and the user is not in re-edit mode (where cached options stay visible). |
273
274
  | `isReady` | `boolean` | Server indicates query is complete. |
274
275
  | `error` | `Error \| null` | Last fetch error. |
275
276
 
@@ -305,6 +306,7 @@ The dropdown component for Tier 2. Spread `dropdownProps` from the hook.
305
306
  | `pills?` | `Suggestion[]` | Pills to render inside the dropdown. |
306
307
  | `onPillClick?` | `(index: number) => void` | Called when a pill is clicked. |
307
308
  | `showPills?` | `boolean` | Whether to render pills. Default: `true`. |
309
+ | `isLoading?` | `boolean` | When `true`, the dropdown renders its pills + options as a skeleton: text masked, layout (count and widths) preserved, shimmer pulse animating. Falls back to a generic 3-bar placeholder when no pills/options are cached. |
308
310
 
309
311
  ### `AutocompleteResult`
310
312
 
@@ -343,6 +345,7 @@ Override on the container (via `className`). All defaults use `:where()` (zero s
343
345
  | `--aia-scrollbar-thumb` | `rgba(0, 0, 0, 0.3)` | `rgba(0, 0, 0, 0.3)` | Color of the option list's scrollbar thumb (Firefox + WebKit). |
344
346
  | `--aia-streak-rgb` | `99, 102, 241` | `255, 255, 255` | Comma-separated RGB triplet used to tint the option-selection streak animation (consumed via `rgba(var(--aia-streak-rgb), …)`). |
345
347
  | `--aia-streak-glass-bg` | `rgba(99, 102, 241, 0.1)` | `rgba(255, 255, 255, 0.1)` | Background fill for the streak's glass-pill effect. |
348
+ | `--aia-skeleton-bg` | `rgba(189, 189, 189, 0.51)` | `#333539` | Fill color for the loading skeleton bars and the masked text in cached pills/options. |
346
349
 
347
350
  Legacy `--aia-color-*` variables are still supported as fallbacks.
348
351
 
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var dt=Object.defineProperty;var Qt=Object.getOwnPropertyDescriptor;var jt=Object.getOwnPropertyNames;var Vt=Object.prototype.hasOwnProperty;var Xt=(n,e)=>{for(var t in e)dt(n,t,{get:e[t],enumerable:!0})},Jt=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of jt(e))!Vt.call(n,r)&&r!==t&&dt(n,r,{get:()=>e[r],enumerable:!(o=Qt(e,r))||o.enumerable});return n};var Yt=n=>Jt(dt({},"__esModule",{value:!0}),n);var Tn={};Xt(Tn,{AIAutocomplete:()=>zt,AIAutocompleteDropdown:()=>Ne,useAIAutocomplete:()=>Ze});module.exports=Yt(Tn);var I=require("react");if(typeof document<"u"&&!document.getElementById("ac-style-cc65f4cc")){let n=document.createElement("style");n.id="ac-style-cc65f4cc",n.textContent=`.AIAutocomplete-module_container_KKjFU {
1
+ "use strict";var dt=Object.defineProperty;var Qt=Object.getOwnPropertyDescriptor;var jt=Object.getOwnPropertyNames;var Vt=Object.prototype.hasOwnProperty;var Xt=(n,e)=>{for(var t in e)dt(n,t,{get:e[t],enumerable:!0})},Jt=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of jt(e))!Vt.call(n,r)&&r!==t&&dt(n,r,{get:()=>e[r],enumerable:!(o=Qt(e,r))||o.enumerable});return n};var Yt=n=>Jt(dt({},"__esModule",{value:!0}),n);var An={};Xt(An,{AIAutocomplete:()=>zt,AIAutocompleteDropdown:()=>Ne,useAIAutocomplete:()=>Ze});module.exports=Yt(An);var I=require("react");if(typeof document<"u"&&!document.getElementById("ac-style-cc65f4cc")){let n=document.createElement("style");n.id="ac-style-cc65f4cc",n.textContent=`.AIAutocomplete-module_container_KKjFU {
2
2
  position: relative;
3
3
  /* Inherits the host page's font by default. Consumers can pin a specific
4
4
  font on the library via \`--aia-font-family: 'Custom Font'\` without
@@ -150,7 +150,7 @@
150
150
  background-position: -50% 0;
151
151
  }
152
152
  }
153
- `,document.head.appendChild(n)}var J={container:"AIAutocomplete-module_container_KKjFU",inputWrapper:"AIAutocomplete-module_inputWrapper_FLq1b",editorArea:"AIAutocomplete-module_editorArea_7rBWq",input:"AIAutocomplete-module_input_IW-P-",pillListContainer:"AIAutocomplete-module_pillListContainer_h92IA",submitButton:"AIAutocomplete-module_submitButton_sl1Mi",submitSlot:"AIAutocomplete-module_submitSlot_GhuCM",shimmerRevealed:"AIAutocomplete-module_shimmerRevealed_RR8dp",shimmerSweep:"AIAutocomplete-module_shimmerSweep_ARCon",textShimmer:"AIAutocomplete-module_textShimmer_eCLdq"};if(typeof document<"u"&&!document.getElementById("ac-style-2eef895d")){let n=document.createElement("style");n.id="ac-style-2eef895d",n.textContent=`.AIAutocompleteDropdown-module_dropdown_yz2KC {
153
+ `,document.head.appendChild(n)}var X={container:"AIAutocomplete-module_container_KKjFU",inputWrapper:"AIAutocomplete-module_inputWrapper_FLq1b",editorArea:"AIAutocomplete-module_editorArea_7rBWq",input:"AIAutocomplete-module_input_IW-P-",pillListContainer:"AIAutocomplete-module_pillListContainer_h92IA",submitButton:"AIAutocomplete-module_submitButton_sl1Mi",submitSlot:"AIAutocomplete-module_submitSlot_GhuCM",shimmerRevealed:"AIAutocomplete-module_shimmerRevealed_RR8dp",shimmerSweep:"AIAutocomplete-module_shimmerSweep_ARCon",textShimmer:"AIAutocomplete-module_textShimmer_eCLdq"};if(typeof document<"u"&&!document.getElementById("ac-style-2eef895d")){let n=document.createElement("style");n.id="ac-style-2eef895d",n.textContent=`.AIAutocompleteDropdown-module_dropdown_yz2KC {
154
154
  position: absolute;
155
155
  left: 0;
156
156
  right: 0;
@@ -189,37 +189,12 @@
189
189
  padding: 27px 27px 0px 27px;
190
190
  }
191
191
 
192
- /* --- Loading skeleton --- */
193
- .AIAutocompleteDropdown-module_skeleton_XiH2s {
194
- display: flex;
195
- flex-direction: column;
196
- gap: 20px;
197
- padding: 25px;
198
- }
199
-
200
- .AIAutocompleteDropdown-module_skeletonPills_KFzRs {
201
- display: flex;
202
- gap: 5px;
203
- align-items: center;
204
- }
205
-
206
- .AIAutocompleteDropdown-module_skeletonPill_JdDM3 {
207
- display: inline-block;
208
- height: 30px;
209
- border-radius: 999px;
210
- background: var(--aia-skeleton-bg, var(--aia-pill-bg, rgba(189, 189, 189, 0.51)));
211
- opacity: 0.5;
212
- animation: AIAutocompleteDropdown-module_aiaSkeletonPulse_G8W7q 1.4s ease-in-out infinite;
213
- }
214
-
215
- .AIAutocompleteDropdown-module_skeletonPills_KFzRs .AIAutocompleteDropdown-module_skeletonPill_JdDM3:nth-child(2) {
216
- opacity: 0.3;
217
- }
218
-
192
+ /* --- Fallback loading skeleton (only when no pills/options are cached) --- */
219
193
  .AIAutocompleteDropdown-module_skeletonBars_HVr9C {
220
194
  display: flex;
221
195
  flex-direction: column;
222
196
  gap: 20px;
197
+ padding: 25px;
223
198
  }
224
199
 
225
200
  .AIAutocompleteDropdown-module_skeletonBar_O3xIx {
@@ -248,7 +223,7 @@
248
223
  opacity: 0.25;
249
224
  }
250
225
  }
251
- `,document.head.appendChild(n)}var Q={dropdown:"AIAutocompleteDropdown-module_dropdown_yz2KC",visible:"AIAutocompleteDropdown-module_visible_QCoXj",pillBar:"AIAutocompleteDropdown-module_pillBar_pwTXe",skeleton:"AIAutocompleteDropdown-module_skeleton_XiH2s",skeletonPills:"AIAutocompleteDropdown-module_skeletonPills_KFzRs",skeletonPill:"AIAutocompleteDropdown-module_skeletonPill_JdDM3",aiaSkeletonPulse:"AIAutocompleteDropdown-module_aiaSkeletonPulse_G8W7q",skeletonBars:"AIAutocompleteDropdown-module_skeletonBars_HVr9C",skeletonBar:"AIAutocompleteDropdown-module_skeletonBar_O3xIx"};if(typeof document<"u"&&!document.getElementById("ac-style-b745b4fb")){let n=document.createElement("style");n.id="ac-style-b745b4fb",n.textContent=`.PillList-module_list_qvLqO {
226
+ `,document.head.appendChild(n)}var Z={dropdown:"AIAutocompleteDropdown-module_dropdown_yz2KC",visible:"AIAutocompleteDropdown-module_visible_QCoXj",pillBar:"AIAutocompleteDropdown-module_pillBar_pwTXe",skeletonBars:"AIAutocompleteDropdown-module_skeletonBars_HVr9C",skeletonBar:"AIAutocompleteDropdown-module_skeletonBar_O3xIx",aiaSkeletonPulse:"AIAutocompleteDropdown-module_aiaSkeletonPulse_G8W7q"};if(typeof document<"u"&&!document.getElementById("ac-style-b745b4fb")){let n=document.createElement("style");n.id="ac-style-b745b4fb",n.textContent=`.PillList-module_list_qvLqO {
252
227
  position: relative;
253
228
  z-index: 1;
254
229
  pointer-events: auto;
@@ -298,14 +273,13 @@
298
273
  border-radius: 999px;
299
274
  }
300
275
 
276
+ /* Loading skeleton \u2014 preserves the pill's exact box (same width and height)
277
+ and just hides the text. The pill's native background acts as the visible
278
+ shape; the pulse provides the shimmer. */
301
279
  .PillList-module_skeleton_Lp8x6 {
302
280
  pointer-events: none;
303
281
  cursor: default;
304
- height: 30px;
305
- padding: 0;
306
- background: var(--aia-skeleton-bg, var(--aia-pill-bg, rgba(189, 189, 189, 0.51)));
307
- box-shadow: none;
308
- backdrop-filter: none;
282
+ color: transparent;
309
283
  animation: PillList-module_skeletonPulse_xZ8Yf 1.4s ease-in-out infinite;
310
284
  }
311
285
 
@@ -315,7 +289,7 @@
315
289
  filter: brightness(1);
316
290
  }
317
291
  50% {
318
- filter: brightness(0.7);
292
+ filter: brightness(0.55);
319
293
  }
320
294
  }
321
295
 
@@ -332,7 +306,7 @@
332
306
  opacity: 0;
333
307
  }
334
308
  }
335
- `,document.head.appendChild(n)}var j={list:"PillList-module_list_qvLqO",pill:"PillList-module_pill_osSyz",fadeIn:"PillList-module_fadeIn_Aezob",rounded:"PillList-module_rounded_WvXy4",skeleton:"PillList-module_skeleton_Lp8x6",skeletonPulse:"PillList-module_skeletonPulse_xZ8Yf",active:"PillList-module_active_Oll--"};var he=require("react/jsx-runtime"),Zt=[125,69];function ft(n){return n===0?.4:n===1?.3:.15}function Me({pills:n,activePillIndex:e,onSelectPill:t,rounded:o,loading:r}){return r?(0,he.jsx)("span",{className:j.list,"data-aia-pill-list-loading":"",children:Zt.map((a,i)=>(0,he.jsx)("span",{"data-aia-pill-skeleton":"",className:`${j.pill} ${o?j.rounded:""} ${j.skeleton}`,style:{width:a,opacity:ft(i)}},`skel-${a}`))}):(0,he.jsx)("span",{className:j.list,children:n.map((a,i)=>(0,he.jsx)("button",{type:"button","data-aia-pill":"",tabIndex:-1,contentEditable:!1,suppressContentEditableWarning:!0,className:`${j.pill} ${o?j.rounded:""} ${i===e?j.active:""}`,style:{opacity:ft(i)},onMouseDown:s=>s.preventDefault(),onClick:()=>t(i),children:a.text},`${a.type}-${a.text}`))})}var Y=require("react");if(typeof document<"u"&&!document.getElementById("ac-style-d91f2b06")){let n=document.createElement("style");n.id="ac-style-d91f2b06",n.textContent=`.SuggestionGrid-module_scrollWrapper_MOqfw {
309
+ `,document.head.appendChild(n)}var W={list:"PillList-module_list_qvLqO",pill:"PillList-module_pill_osSyz",fadeIn:"PillList-module_fadeIn_Aezob",rounded:"PillList-module_rounded_WvXy4",skeleton:"PillList-module_skeleton_Lp8x6",skeletonPulse:"PillList-module_skeletonPulse_xZ8Yf",active:"PillList-module_active_Oll--"};var he=require("react/jsx-runtime"),Zt=[125,69];function ft(n){return n===0?.4:n===1?.3:.15}function be({pills:n,activePillIndex:e,onSelectPill:t,rounded:o,loading:r}){return r&&n.length===0?(0,he.jsx)("span",{className:W.list,"data-aia-pill-list-loading":"",children:Zt.map((a,i)=>(0,he.jsx)("span",{"data-aia-pill-skeleton":"",className:`${W.pill} ${o?W.rounded:""} ${W.skeleton}`,style:{width:a,opacity:ft(i)}},`skel-${a}`))}):(0,he.jsx)("span",{className:W.list,"data-aia-pill-list-loading":r?"":void 0,children:n.map((a,i)=>(0,he.jsx)("button",{type:"button","data-aia-pill":"","data-aia-loading":r?"":void 0,tabIndex:-1,contentEditable:!1,suppressContentEditableWarning:!0,className:`${W.pill} ${o?W.rounded:""} ${i===e&&!r?W.active:""} ${r?W.skeleton:""}`,style:{opacity:ft(i)},onMouseDown:s=>s.preventDefault(),onClick:r?void 0:()=>t(i),disabled:r,children:a.text},`${a.type}-${a.text}`))})}var J=require("react");if(typeof document<"u"&&!document.getElementById("ac-style-d91f2b06")){let n=document.createElement("style");n.id="ac-style-d91f2b06",n.textContent=`.SuggestionGrid-module_scrollWrapper_MOqfw {
336
310
  position: relative;
337
311
  }
338
312
 
@@ -700,7 +674,36 @@
700
674
  box-shadow: 0 0 24px 10px rgba(var(--aia-streak-rgb, 255, 255, 255), 0.02);
701
675
  }
702
676
  }
703
- `,document.head.appendChild(n)}var $={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 ee=require("react/jsx-runtime");function ht({option:n,isHighlighted:e,onSelect:t,onHighlight:o,id:r}){let[a,i]=(0,ie.useState)(!1),s=(0,ie.useRef)(void 0);(0,ie.useEffect)(()=>()=>clearTimeout(s.current),[]);let l=()=>{!n.is_tappable||a||(i(!0),t(n),clearTimeout(s.current),s.current=setTimeout(()=>i(!1),400))},d=[$.item,e?$.highlighted:"",n.is_tappable?$.tappable:$.nonTappable,a?$.pressed:""].filter(Boolean).join(" ");return(0,ee.jsxs)("div",{id:r,role:"option","data-aia-option":"","aria-selected":e,className:d,tabIndex:n.is_tappable?0:-1,onClick:l,onKeyDown:c=>{n.is_tappable&&(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),l())},onMouseEnter:n.is_tappable?o:void 0,children:[(0,ee.jsx)("div",{className:$.streaks}),(0,ee.jsx)("div",{className:$.streaksVert}),(0,ee.jsxs)("span",{className:$.content,children:[n.icon?`${n.icon} ${n.text}`:n.text,n.tag&&(0,ee.jsx)("span",{className:$.tag,children:n.tag})]})]})}var Re=require("react/jsx-runtime");function bt({options:n,activeIndex:e,onSelect:t,onHighlight:o,listboxId:r}){let a=(0,Y.useRef)(null),[i,s]=(0,Y.useState)(!1);return(0,Y.useEffect)(()=>{let l=a.current;if(!l)return;let d=()=>{s(l.scrollHeight-l.scrollTop-l.clientHeight>1)};l.addEventListener("scroll",d,{passive:!0});let c=new ResizeObserver(d);return c.observe(l),()=>{l.removeEventListener("scroll",d),c.disconnect()}},[]),(0,Y.useLayoutEffect)(()=>{let l=a.current;l&&s(l.scrollHeight-l.scrollTop-l.clientHeight>1)},[n]),(0,Re.jsx)("div",{className:ct.scrollWrapper,"data-fade":i?"":void 0,children:(0,Re.jsx)("div",{ref:a,className:ct.grid,children:n.map((l,d)=>(0,Re.jsx)(ht,{option:l,isHighlighted:d===e,onSelect:t,onHighlight:()=>o(d),id:`${r}-option-${d}`},l.text))})})}var H=require("react/jsx-runtime"),en=[159,119,164],tn=[115,122];function Ne({suggestions:n,activeIndex:e,onSelect:t,onHighlight:o,isOpen:r,id:a,className:i,pills:s,onPillClick:l,showPills:d=!0,isLoading:c=!1}){let u=n[0]?.options??[],x=d&&s&&s.length>0&&l,h=r&&u.length>0,y=r&&(c||h||x);return(0,H.jsx)("div",{id:a,role:"listbox","data-aia-dropdown":"","data-aia-loading":c?"":void 0,className:`${Q.dropdown} ${y?Q.visible:""} ${i??""}`,onMouseDown:g=>g.preventDefault(),children:c?(0,H.jsxs)("div",{className:Q.skeleton,"data-aia-skeleton":"",children:[d&&(0,H.jsx)("div",{className:Q.skeletonPills,"data-aia-skeleton-pills":"",children:tn.map(g=>(0,H.jsx)("span",{className:Q.skeletonPill,style:{width:g}},`pill-${g}`))}),(0,H.jsx)("div",{className:Q.skeletonBars,children:en.map(g=>(0,H.jsx)("span",{className:Q.skeletonBar,style:{width:g}},`bar-${g}`))})]}):(0,H.jsxs)(H.Fragment,{children:[x&&(0,H.jsx)("div",{className:Q.pillBar,"data-aia-pillbar":"",children:(0,H.jsx)(Me,{pills:s,activePillIndex:0,onSelectPill:l,rounded:!0})}),u.length>0&&(0,H.jsx)(bt,{options:u,activeIndex:e,onSelect:t,onHighlight:o,listboxId:a})]})})}if(typeof document<"u"&&!document.getElementById("ac-style-dc8da745")){let n=document.createElement("style");n.id="ac-style-dc8da745",n.textContent=`/*
677
+
678
+ /* Loading state \u2014 preserve the row's exact dimensions. The content stays an
679
+ inline span so the line box and padding match the non-loading state byte
680
+ for byte. Just hide the text and apply a background as a skeleton bar; the
681
+ pulse provides the shimmer. */
682
+ .SuggestionItem-module_item_d4vpD[data-aia-loading] {
683
+ cursor: default;
684
+ animation: SuggestionItem-module_skeletonPulse_plvdD 1.4s ease-in-out infinite;
685
+ }
686
+
687
+ .SuggestionItem-module_item_d4vpD[data-aia-loading] .SuggestionItem-module_content_T-Qba {
688
+ color: transparent;
689
+ background: var(--aia-skeleton-bg, var(--aia-pill-bg, rgba(189, 189, 189, 0.51)));
690
+ border-radius: 999px;
691
+ }
692
+
693
+ .SuggestionItem-module_item_d4vpD[data-aia-loading] .SuggestionItem-module_tag_e3Fwe {
694
+ display: none;
695
+ }
696
+
697
+ @keyframes SuggestionItem-module_skeletonPulse_plvdD {
698
+ 0%,
699
+ 100% {
700
+ filter: brightness(1);
701
+ }
702
+ 50% {
703
+ filter: brightness(0.55);
704
+ }
705
+ }
706
+ `,document.head.appendChild(n)}var $={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",skeletonPulse:"SuggestionItem-module_skeletonPulse_plvdD"};var ee=require("react/jsx-runtime");function ht({option:n,isHighlighted:e,onSelect:t,onHighlight:o,id:r,loading:a}){let[i,s]=(0,ie.useState)(!1),d=(0,ie.useRef)(void 0);(0,ie.useEffect)(()=>()=>clearTimeout(d.current),[]);let l=()=>{a||!n.is_tappable||i||(s(!0),t(n),clearTimeout(d.current),d.current=setTimeout(()=>s(!1),500))},p=[$.item,e&&!a?$.highlighted:"",n.is_tappable?$.tappable:$.nonTappable,i?$.pressed:""].filter(Boolean).join(" ");return(0,ee.jsxs)("div",{id:r,role:"option","data-aia-option":"","data-aia-loading":a?"":void 0,"aria-selected":e,className:p,tabIndex:a||!n.is_tappable?-1:0,onClick:l,onKeyDown:u=>{!a&&n.is_tappable&&(u.key==="Enter"||u.key===" ")&&(u.preventDefault(),l())},onMouseEnter:!a&&n.is_tappable?o:void 0,children:[(0,ee.jsx)("div",{className:$.streaks}),(0,ee.jsx)("div",{className:$.streaksVert}),(0,ee.jsxs)("span",{className:$.content,children:[n.icon?`${n.icon} ${n.text}`:n.text,n.tag&&(0,ee.jsx)("span",{className:$.tag,children:n.tag})]})]})}var Re=require("react/jsx-runtime");function bt({options:n,activeIndex:e,onSelect:t,onHighlight:o,listboxId:r,loading:a}){let i=(0,J.useRef)(null),[s,d]=(0,J.useState)(!1);return(0,J.useEffect)(()=>{let l=i.current;if(!l)return;let p=()=>{d(l.scrollHeight-l.scrollTop-l.clientHeight>1)};l.addEventListener("scroll",p,{passive:!0});let u=new ResizeObserver(p);return u.observe(l),()=>{l.removeEventListener("scroll",p),u.disconnect()}},[]),(0,J.useLayoutEffect)(()=>{let l=i.current;l&&d(l.scrollHeight-l.scrollTop-l.clientHeight>1)},[n]),(0,Re.jsx)("div",{className:ct.scrollWrapper,"data-fade":s?"":void 0,children:(0,Re.jsx)("div",{ref:i,className:ct.grid,children:n.map((l,p)=>(0,Re.jsx)(ht,{option:l,isHighlighted:p===e,onSelect:t,onHighlight:()=>o(p),id:`${r}-option-${p}`,loading:a},l.text))})})}var q=require("react/jsx-runtime"),en=[159,119,164];function Ne({suggestions:n,activeIndex:e,onSelect:t,onHighlight:o,isOpen:r,id:a,className:i,pills:s,onPillClick:d,showPills:l=!0,isLoading:p=!1}){let c=n[0]?.options??[],h=l&&s&&s.length>0&&d,b=c.length>0,v=p&&!b,f=r&&(b||h||p);return(0,q.jsxs)("div",{id:a,role:"listbox","data-aia-dropdown":"","data-aia-loading":p?"":void 0,className:`${Z.dropdown} ${f?Z.visible:""} ${i??""}`,onMouseDown:m=>m.preventDefault(),children:[l&&s&&s.length>0&&d&&(0,q.jsx)("div",{className:Z.pillBar,"data-aia-pillbar":"",children:(0,q.jsx)(be,{pills:s,activePillIndex:0,onSelectPill:d,rounded:!0,loading:p})}),l&&(!s||s.length===0)&&p&&(0,q.jsx)("div",{className:Z.pillBar,"data-aia-pillbar":"",children:(0,q.jsx)(be,{pills:[],activePillIndex:0,onSelectPill:()=>{},rounded:!0,loading:!0})}),b&&(0,q.jsx)(bt,{options:c,activeIndex:e,onSelect:t,onHighlight:o,listboxId:a,loading:p}),v&&(0,q.jsx)("div",{className:Z.skeletonBars,"data-aia-skeleton-bars":"",children:en.map(m=>(0,q.jsx)("span",{className:Z.skeletonBar,style:{width:m}},`bar-${m}`))})]})}if(typeof document<"u"&&!document.getElementById("ac-style-dc8da745")){let n=document.createElement("style");n.id="ac-style-dc8da745",n.textContent=`/*
704
707
  * Built-in appearance defaults \u2014 zero specificity via :where().
705
708
  * Consumer CSS always wins without !important.
706
709
  *
@@ -710,6 +713,18 @@
710
713
  * 3. These built-in defaults
711
714
  */
712
715
 
716
+ /*
717
+ * Library-scoped box-sizing reset. The SDK's pill / option / wrapper styles
718
+ * mix explicit dimensions with padding (e.g. .magicx-aia-pill has height:36px
719
+ * + padding:13px) and were authored assuming \`border-box\`. In consumer apps
720
+ * without a global \`* { box-sizing: border-box }\` reset the pill rendered
721
+ * ~62px tall instead of 36px. Scoping the reset to \`.magicx-aia\` descendants
722
+ * keeps the library self-contained without leaking onto consumer markup.
723
+ */
724
+ :where(.magicx-aia, .magicx-aia *, .magicx-aia *::before, .magicx-aia *::after) {
725
+ box-sizing: border-box;
726
+ }
727
+
713
728
  /* Light mode defaults (base) */
714
729
  :where(.magicx-aia),
715
730
  :where(.magicx-aia[data-mode="light"]) {
@@ -783,5 +798,5 @@
783
798
  animation-duration: 0s !important;
784
799
  transition-duration: 0s !important;
785
800
  }
786
- `,document.head.appendChild(n)}var vt='[contenteditable="false"]',re;function nn(){if(re!==void 0)return re;let n=globalThis.Intl.Segmenter;if(!n)return re=null,null;try{re=new n(void 0,{granularity:"grapheme"})}catch{re=null}return re??null}function He(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(vt))return!0;t=t.parentNode}return!1}function Be(n){return(n.ownerDocument??document).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return He(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function ae(n){let e=Be(n),t="",o=e.nextNode();for(;o;)t+=o.data,o=e.nextNode();return t}function Fe(n){let e=Be(n),t=0,o=e.nextNode();for(;o;)t+=o.data.length,o=e.nextNode();return t}function K(n){let e=(n.ownerDocument??document).getSelection();if(!e||e.rangeCount===0)return null;let t=e.anchorNode,o=e.anchorOffset;if(!t||!n.contains(t))return null;if(t.nodeType===Node.ELEMENT_NODE){let r=t;if(He(r,n)&&r!==n)return null;let a=0;for(let i=0;i<o&&i<r.childNodes.length;i++)a+=yt(r.childNodes[i],n);return a+xt(r,n)}return t.nodeType!==Node.TEXT_NODE||He(t,n)?null:xt(t,n)+o}function yt(n,e){if(n.nodeType===Node.TEXT_NODE)return He(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(vt))return 0;let o=0;for(let r of Array.from(t.childNodes))o+=yt(r,e);return o}function xt(n,e){let t=Be(e),o=0,r=t.nextNode();for(;r;){if(r===n||n.nodeType===Node.ELEMENT_NODE&&n.contains(r))return o;o+=r.data.length,r=t.nextNode()}return o}function M(n,e){let t=n.ownerDocument??document,o=t.getSelection();if(!o)return;let r=Math.max(0,Math.min(e,Fe(n))),a=Be(n),i=0,s=null,l=0,d=a.nextNode(),c=null;for(;d;){let u=d.data.length;if(r<i+u){s=d,l=r-i;break}if(r===i+u){let x=a.nextNode();x?(s=x,l=0):(s=d,l=u);break}i+=u,c=d,d=a.nextNode()}let p=t.createRange();if(s){let u=s.parentElement?.closest('strong[data-seg="completed"]');u&&u!==n&&n.contains(u)?l===0?p.setStartBefore(u):l===s.data.length?p.setStartAfter(u):p.setStart(s,l):p.setStart(s,l)}else c?p.setStart(c,c.data.length):p.setStart(n,0);p.collapse(!0),o.removeAllRanges(),o.addRange(p)}function wt(n){let e=K(n);return e==null?!1:e>=Fe(n)}function St(n,e){if(e<=0)return 0;let t=nn();if(!t)return e-1;let o=n.slice(0,e),r=0;for(let{index:a}of t.segment(o))a<e&&(r=a);return r}function Ke(n){let{input:e,segments:t,newParamId:o,editingParamId:r,placeholderText:a,isFocused:i}=n,s=t.length===0;e.dataset.aiaEmpty=s?"true":"false",s&&a?e.dataset.placeholder=a:delete e.dataset.placeholder;let l=t.map(g=>`${g.type}:${g.value}`).join("\0"),d=e.dataset.segKey??"",c=e.dataset.newParamId??"",p=e.dataset.editingParamId??"";if(l===d&&(o??"")===c&&(r??"")===p)return;let u=i?K(e):null;e.dataset.segKey=l,e.dataset.newParamId=o??"",e.dataset.editingParamId=r??"";let x=e.ownerDocument??document,h=x.createDocumentFragment(),y=0;for(let g of t)if(y+=g.value.length,g.type==="completed"){let m=x.createElement("strong");m.dataset.seg="completed",m.dataset.paramId=g.param.id;let f=g.param.id===o,P=g.param.id===r,_=["magicx-aia-segment","magicx-aia-segment--completed"];f&&_.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),P&&_.push("magicx-aia-segment--editing"),m.className=_.join(" "),m.textContent=g.value,h.appendChild(m)}else h.appendChild(x.createTextNode(g.value));e.replaceChildren(h),e.dataset.aiaTextLength=String(y),u!=null&&M(e,Math.max(0,Math.min(u,y)))}var S=require("react");function B(n,e){let t=n,o={},r=[];for(let a of e){let i=(o[a.type]??0)+1;o[a.type]=i;let l=`{{${a.type.toUpperCase().replace(/\s+/g,"_")}_${i}}}`,d=t.indexOf(a.text);d!==-1&&(t=t.slice(0,d)+l+t.slice(d+a.text.length)),r.push({...a,placeholder:l})}return{rawQuery:t,completedParams:r}}function be(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function se(n,e,t){let o=n.slice(e);if(t||e===0||n[e-1]===" ")return o;let r=o.indexOf(" ");return r===-1?"":o.slice(r+1)}function Pt(n,e){let t=n.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let o=t.split(" "),r=e.toLowerCase();for(let a=0;a<o.length;a++){let i=o.slice(a).join(" ");if(r.startsWith(i.toLowerCase())){let s=t.length-i.length;return n.length-s}}return 0}function xe(n,e){if(!n)return[];let t=e.trimStart();if(!t)return n;let o=t.toLowerCase();return n.filter(r=>!r.is_tappable||r.text.toLowerCase().includes(o))}function le(n,e){if(!n)return null;let t=e.trim();if(!t)return null;let o=t.toLowerCase();return n.find(r=>r.is_tappable&&r.text.toLowerCase()===o)??null}var de=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 It(n,e){let t=[],o=0;for(let a of e){let i=n.indexOf(a.text,o);i!==-1&&(i>o&&t.push({type:"text",value:n.slice(o,i)}),t.push({type:"completed",value:a.text,param:a}),o=i+a.text.length)}let r=n.slice(o);return r&&t.push({type:"text",value:r}),t}function Ct(n,e){let t=[],o=[],r=0;for(let a of e){let i=n.indexOf(a.text,r);i===-1?o.push(a):(t.push(a),r=i+a.text.length)}return{valid:t,invalid:o}}var ze=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 on="https://api.ai-autocomplete.com",We=`${on}/api/suggest`,At=new WeakMap;function ve(n){return n?.type==="accessToken"}function rn(n){if(!(!n||ve(n)))return n}function $e(n){let e=At.get(n.getAccessToken);return e||(e=new ze(n),At.set(n.getAccessToken,e)),e}function qe(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function Ue(n){let e=rn(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}function an(n){return(n??We).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function sn(n){return ve(n)?`Bearer ${await $e(n).getToken()}`:Ue(n)}async function _t(n){try{let e=an(n.apiConfig?.endpoint),t=qe(n.apiConfig),o=await sn(n.apiConfig);o&&(t.Authorization=o);let r=JSON.stringify({source:n.source,session_id:n.sessionId,type:n.type,at:new Date().toISOString(),query_data:n.queryData});await fetch(e,{method:"POST",headers:t,body:r})}catch{}}var ln="0.1.39",Tt=!1;function dn(){return crypto.randomUUID()}function cn(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.text},kind:n.kind}}function pn(n,e,t,o){let r=e.find(i=>i.type==="contact"&&i.metadata?.contact_account_count)?.metadata?.contact_account_count,a=typeof r=="number"?r:void 0;return{data:{raw_query:n,completed_params:e.map(i=>cn(i,t)),...a!=null&&{contact_account_count:a}},meta:{request_id:dn(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:ln,session_id:o}}}async function Et(n,e,t,o,r){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:o,signal:r})}async function kt(n,e,t){let o=t.apiConfig,r=!t.maskCompletedText,a=pn(n,e,r,t.sessionId),i=qe(o),s=o?.endpoint??We,l=JSON.stringify(a);if(ve(o)){let p=$e(o),u=await p.getToken(),x=await Et(s,i,u,l,t.signal);if(x.status===401){let h=await p.getToken(!0);x=await Et(s,i,h,l,t.signal)}if(!x.ok)throw new Error(`API error: ${x.status} ${x.statusText}`);return x.json()}let d=Ue(o);!d&&!Tt&&(Tt=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),d&&(i.Authorization=d);let c=await fetch(s,{method:"POST",headers:i,body:l,signal:t.signal});if(!c.ok)throw new Error(`API error: ${c.status} ${c.statusText}`);return c.json()}function Ot(n,e){return e?n.map(t=>{let o=e[t.type];if(!o)return t;let r=o("");if(r.length===0)return t;let a=new Set(r.map(s=>s.text)),i=(t.options??[]).filter(s=>!a.has(s.text));return{...t,options:[...r,...i]}}):n}var un=100,mn=300,gn=2,Ge=class{constructor(e,t,o,r,a,i,s={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=o;this.getMaskCompletedText=r;this.getOnError=a;this.getSessionId=i;this.callbacks=s;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(o=>{(o.text!==e||o.completedParams!==t)&&(e=o.text,t=o.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let o=new AbortController;this.abortController=o;let r=++this.fetchVersion,a=this.store.get().text.length;this.store.set({isLoading:!0,error:null});try{let i=await kt(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:o.signal,apiConfig:this.getApiConfig()});if(r!==this.fetchVersion)return;let s=Ot(i.data.suggestions??[],this.getOptionOverrides()),l=i.data.input??[],d=l[l.length-1],c=this.store.get().text,p,u;if(d?.state==="in_progress"){u=!0;let g=c.toLowerCase().lastIndexOf(d.text.toLowerCase());p=g!==-1?g:a}else u=!1,p=a;let h=s.filter(g=>g.type!=="placeholder")[0],y=null;if(h){let g=se(c,p,u),m=le(h.options,g);m&&(y={id:crypto.randomUUID(),placeholder:"",type:h.type,text:m.text,kind:m.kind,suggestionType:h.type,suggestionPlaceholder:h.text,options:h.options??[],metadata:m.metadata},s=s.filter(f=>f!==h),this.callbacks.onAutoMatch?.({active:h,matched:m,rawQuery:e}))}this.store.set(g=>({suggestions:s,isLoading:!1,isReady:i.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:p,filterInProgress:u,...y?{completedParams:[...g.completedParams,y]}:{}}))}catch(i){if(r===this.fetchVersion){let s=i instanceof Error?i:new Error(String(i));this.store.set({error:s,isLoading:!1}),this.getOnError()?.(s)}}}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}let t=o=>{let r=this.store.get();if(!r.text&&r.completedParams.length===0)return this.doFetch("",[]),!0;let a=r.suggestions.filter(f=>f.type==="placeholder").map(f=>f.text).join(" "),i=be(r.text,r.filterBase,a),s=se(r.text,i,r.filterInProgress),d=r.suggestions.filter(f=>f.type!=="placeholder")[0],p=(d?xe(d.options,s):[]).filter(f=>f.is_tappable),u=d?le(d.options,s)!==null:!1,x=s.trim().length>0;if(p.length>0&&!u&&x||r.completedParams.length===0&&r.text.length>0&&a.length>0&&a.toLowerCase().startsWith(r.text.toLowerCase()))return!1;let{rawQuery:h,completedParams:y}=B(r.text,r.completedParams),g=h.length<r.lastRawQuery.length,m=Math.abs(h.length-r.lastRawQuery.length);return g||m>=o?(this.doFetch(h,y),!0):!1};this.debounceTimer=setTimeout(()=>{t(gn)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},un),this.slowDebounceTimer=setTimeout(()=>t(1),mn)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};function Dt(n){return n instanceof HTMLTextAreaElement||n instanceof HTMLInputElement?n.selectionStart!=null&&n.selectionStart===n.value.length:n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?wt(n):!1}function fn(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?K(n):null}var Qe=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:o,getOnSubmit:r}=this.ctx,a=this.getEffectiveColumns(),i=r(),s=this.getTappableIndices(a);switch(e.key){case"ArrowDown":{let l=Dt(e.target),d=!!t.editingParam;if(!l&&!d&&t.activeDropdownIndex<0)break;if(e.preventDefault(),!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:s[0]??0});break}if(s.length===0)return;let c=s.indexOf(t.activeDropdownIndex),p=c<s.length-1?c+1:0;this.store.set({activeDropdownIndex:s[p]});break}case"ArrowUp":{if(s.length===0||t.activeDropdownIndex<0)break;if(e.preventDefault(),t.activeDropdownIndex<a){this.store.set({activeDropdownIndex:-1});break}let l=s.indexOf(t.activeDropdownIndex),d=l>0?l-1:s.length-1;this.store.set({activeDropdownIndex:s[d]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%a<a-1){let c=t.activeDropdownIndex+1;c<t.filteredOptions.length&&t.filteredOptions[c]?.is_tappable&&this.store.set({activeDropdownIndex:c})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let d=e.target.closest("[data-aia-input]")??e.target,c=t.editingTail;this.ctx.exitEditMode?.(),M(d,c);break}Dt(e.target)&&t.actionableSuggestions.length>1&&(e.preventDefault(),this.pillsSetActivePill(1));break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%a>0){let l=t.activeDropdownIndex-1;l>=0&&t.filteredOptions[l]?.is_tappable&&this.store.set({activeDropdownIndex:l})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let l=e.target.closest("[data-aia-input]")??e.target,d=t.editingAnchor;this.ctx.exitEditMode?.(),M(l,d);break}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let l=fn(e.target);if(l==null)break;this.ctx.removeParamAtCaret(l)&&e.preventDefault();break}case"Enter":{if(e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable)this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,o);else if(i){let{rawQuery:l,completedParams:d}=B(t.text,t.completedParams);i({query:t.text.trim(),raw_query:l,completed_params:d}),this.ctx.afterSubmit?.()}break}case"Tab":{let l=!t.text&&!!t.placeholderText,d=t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable;if(l&&!d){e.preventDefault();let c=t.placeholderText;if(this.store.set(p=>({text:c,filterBase:c.length,suggestions:p.suggestions.filter(u=>u.type!=="placeholder")})),e.target instanceof HTMLElement){let p=e.target.closest("[data-aia-input]")??e.target;queueMicrotask(()=>M(p,c.length))}}else if(d)e.preventDefault(),this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,o);else if(t.isDropdownOpen){let c=t.filteredOptions.findIndex(p=>p.is_tappable);c>=0&&(e.preventDefault(),this.clickOrSelect(c,t.filteredOptions,o))}break}case"Escape":{if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){let l=e.target.closest("[data-aia-input]")??e.target,d=t.editingTail;this.ctx.exitEditMode?.(),M(l,d)}this.store.set({activeDropdownIndex:-1});break}}}getTappableIndices(e){let o=this.store.get().filteredOptions.map((a,i)=>a.is_tappable?i:-1).filter(a=>a!==-1),r=Array.from({length:e},()=>[]);for(let a of o)r[a%e].push(a);return r.flat()}getEffectiveColumns(){let t=document.getElementById(`${this.ctx.listboxId}-option-0`)?.parentElement;if(!t)return this.ctx.columns;let o=getComputedStyle(t).gridTemplateColumns.split(" ").filter(Boolean).length;return o>0?o:this.ctx.columns}clickOrSelect(e,t,o){let r=document.getElementById(`${o}-option-${e}`);r?r.click():this.ctx.selectOption(t[e])}pillsSetActivePill(e){let t=this.store.get(),o=t.suggestions.filter(s=>s.type!=="placeholder");if(e<0||e>=o.length)return;let r=o[e],a=o.filter((s,l)=>l!==e),i=t.suggestions.filter(s=>s.type==="placeholder");this.store.set({suggestions:[...i,r,...a],pillTapped:!0,activeDropdownIndex:-1})}};var je=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),o=t.suggestions.filter(s=>s.type!=="placeholder");if(e<0||e>=o.length)return;let r=o[e],a=o.filter((s,l)=>l!==e),i=t.suggestions.filter(s=>s.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:s}=B(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:s,selectedPill:r.text,otherPills:a.map(l=>l.text)})}this.store.set({suggestions:[...i,r,...a],pillTapped:!0,activeDropdownIndex:-1})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};var Lt=[125,69];function Mt(n){return n===0?.4:n===1?.3:.15}function Ve(n,e,t,o,r=!1,a=!1){let i=n.querySelector(".magicx-aia-pill-list");if(i||(i=document.createElement("span"),i.className="magicx-aia-pill-list",n.appendChild(i)),a){i.setAttribute("data-aia-pill-list-loading",""),i.innerHTML="";for(let d=0;d<Lt.length;d++){let c=Lt[d],p=document.createElement("span");p.setAttribute("data-aia-pill-skeleton",""),p.className=`magicx-aia-pill magicx-aia-pill--skeleton${r?" magicx-aia-pill--rounded":""}`,p.style.width=`${c}px`,p.style.opacity=String(Mt(d)),i.appendChild(p)}return}i.removeAttribute("data-aia-pill-list-loading");let s=new Map;for(let d of i.querySelectorAll(".magicx-aia-pill"))s.set(d.dataset.pillKey??"",d);let l=new Set;for(let d=0;d<e.length;d++){let c=e[d],p=`${c.type}-${c.text}`;l.add(p);let u=s.get(p);(!u||u.tagName!=="BUTTON")&&(u?.remove(),u=document.createElement("button"),u.type="button",u.tabIndex=-1,u.dataset.pillKey=p,u.setAttribute("data-aia-pill",""),u.setAttribute("contenteditable","false"),u.textContent=c.text,u.addEventListener("mousedown",x=>x.preventDefault())),u.className=`magicx-aia-pill${r?" magicx-aia-pill--rounded":""}${d===t?" magicx-aia-pill--active":""}`,u.style.width="",u.style.opacity=String(Mt(d)),u.onclick=()=>o(d),i.children[d]!==u&&i.insertBefore(u,i.children[d]??null)}for(let[d,c]of s)l.has(d)||c.remove();for(let d of i.querySelectorAll("[data-aia-pill-skeleton]"))d.remove()}function pt(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var hn=[159,119,164],bn=[115,122];function Xe(n){let e=document.createElement("div");return e.id=n,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",t=>t.preventDefault()),e}function Je(n,e){let{filteredOptions:t,activeIndex:o,isOpen:r,isLoading:a,pills:i,showPills:s,onSelect:l,onHighlight:d,onPillClick:c}=e,p=s&&i.length>0,u=r&&t.length>0;r&&(a||u||p)?n.classList.add("magicx-aia-dropdown--visible"):n.classList.remove("magicx-aia-dropdown--visible"),a?n.setAttribute("data-aia-loading",""):n.removeAttribute("data-aia-loading");let h=n.querySelector(".magicx-aia-skeleton");if(a){if(n.querySelector(".magicx-aia-pill-bar")?.remove(),n.querySelector(".magicx-aia-grid")?.remove(),!h)h=xn(s),n.appendChild(h);else{let m=h.querySelector(".magicx-aia-skeleton-pills");s&&!m?h.insertBefore(Rt(),h.firstChild):!s&&m&&m.remove()}return}h&&h.remove();let y=n.querySelector(".magicx-aia-pill-bar");p?(y||(y=document.createElement("div"),y.className="magicx-aia-pill-bar",y.setAttribute("data-aia-pillbar",""),n.insertBefore(y,n.firstChild)),Ve(y,i,0,c,!0)):y&&y.remove();let g=n.querySelector(".magicx-aia-grid");t.length>0?(g||(g=document.createElement("div"),g.className="magicx-aia-grid",n.appendChild(g)),vn(g,t,o,l,d,e.listboxId)):g&&(g.innerHTML="")}function xn(n){let e=document.createElement("div");e.className="magicx-aia-skeleton",e.setAttribute("data-aia-skeleton",""),n&&e.appendChild(Rt());let t=document.createElement("div");t.className="magicx-aia-skeleton-bars";for(let o of hn){let r=document.createElement("span");r.className="magicx-aia-skeleton-bar",r.style.width=`${o}px`,t.appendChild(r)}return e.appendChild(t),e}function Rt(){let n=document.createElement("div");n.className="magicx-aia-skeleton-pills",n.setAttribute("data-aia-skeleton-pills","");for(let e of bn){let t=document.createElement("span");t.className="magicx-aia-skeleton-pill",t.style.width=`${e}px`,n.appendChild(t)}return n}function vn(n,e,t,o,r,a){let i=e.map(d=>d.text).join("\0"),s=n.dataset.optionsKey??"",l=i!==s;if(n.dataset.optionsKey=i,l){let d=document.createDocumentFragment();for(let c=0;c<e.length;c++){let p=e[c],u=yn(p,c,t,o,r,a);d.appendChild(u)}n.innerHTML="",n.appendChild(d)}else{let d=n.querySelectorAll(".magicx-aia-option");for(let c=0;c<d.length;c++){let p=d[c],u=c===t;p.setAttribute("aria-selected",String(u)),u?p.classList.add("magicx-aia-option--highlighted"):p.classList.remove("magicx-aia-option--highlighted")}}}function yn(n,e,t,o,r,a){let i=document.createElement("div");i.id=`${a}-option-${e}`,i.setAttribute("role","option"),i.setAttribute("data-aia-option",""),i.setAttribute("aria-selected",String(e===t)),i.tabIndex=n.is_tappable?0:-1;let s=["magicx-aia-option"];e===t&&s.push("magicx-aia-option--highlighted"),n.is_tappable?s.push("magicx-aia-option--tappable"):s.push("magicx-aia-option--non-tappable"),i.className=s.join(" ");let l=document.createElement("div");l.className="magicx-aia-streaks",i.appendChild(l);let d=document.createElement("div");d.className="magicx-aia-streaks-vert",i.appendChild(d);let c=document.createElement("span");if(c.className="magicx-aia-option-content",c.textContent=n.icon?`${n.icon} ${n.text}`:n.text,n.tag){let p=document.createElement("span");p.className="magicx-aia-option-tag",p.textContent=n.tag,c.appendChild(p)}return i.appendChild(c),n.is_tappable&&(i.addEventListener("click",()=>{i.classList.add("magicx-aia-option--pressed"),o(n),setTimeout(()=>i.classList.remove("magicx-aia-option--pressed"),400)}),i.addEventListener("mouseenter",()=>r(e))),i}function Nt(n,e){let t=Xe(e.listboxId);return n.appendChild(t),{dropdown:t}}function ut(n,e,t){Je(n.dropdown,{suggestions:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,onSelect:t.selectOption,onHighlight:o=>t.store.set({activeDropdownIndex:o}),onPillClick:t.setActivePill})}var wn='<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 Sn(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function Ht(n,e){let{listboxId:t}=e,o=Xe(t);n.appendChild(o);let r=document.createElement("div");r.className="magicx-aia-input-wrapper",n.appendChild(r);let a=document.createElement("div");a.className="magicx-aia-editor",a.setAttribute("data-aia-editor",""),r.appendChild(a);let i=document.createElement("div");i.className="magicx-aia-input",i.setAttribute("data-aia-input",""),i.setAttribute("contenteditable",Sn()?"plaintext-only":"true"),i.setAttribute("role","combobox"),i.setAttribute("aria-autocomplete","list"),i.setAttribute("aria-haspopup","listbox"),i.setAttribute("aria-controls",t),i.setAttribute("aria-expanded","false"),i.setAttribute("spellcheck","true"),i.setAttribute("enterkeyhint","send"),a.appendChild(i);let s=document.createElement("span");s.className="magicx-aia-pill-list-container",s.setAttribute("data-aia-pill-list-container",""),a.appendChild(s);let l=null,d=null;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=wn,r.appendChild(l),d=l):e.submitButton!==null&&(d=e.submitButton,d.hasAttribute("data-aia-submit")||d.setAttribute("data-aia-submit",""),r.appendChild(d));let c=new AbortController,{signal:p}=c,u=!1,x=0,h=()=>{let m=ae(i),P=m.length>0&&m[0]!==m[0].toUpperCase()?m[0].toUpperCase()+m.slice(1):m;e.handleChange(P)},y=()=>{let m=(i.ownerDocument??document).getSelection();if(!m||m.rangeCount===0)return null;let f=m.anchorNode;return!f||!i.contains(f)?null:(f.nodeType===Node.ELEMENT_NODE?f:f.parentElement)?.closest('strong[data-seg="completed"][data-param-id]')?.dataset.paramId??null};r.addEventListener("click",m=>{m.target?.closest("[data-aia-pill]")||i.focus()},{signal:p}),i.addEventListener("input",()=>{u||(x=performance.now(),h(),e.handleCaretAfterInput(K(i)))},{signal:p});let g=i.ownerDocument??document;return g.addEventListener("selectionchange",()=>{let m=g.getSelection();if(!m||m.rangeCount===0||!i.contains(m.anchorNode))return;let f=y(),P=e.store.get().editingParam?.id??null;if(f&&f!==P){e.startEditingParam(f);return}performance.now()-x<50||e.handleCaretMove(K(i))},{signal:p}),i.addEventListener("compositionstart",()=>{u=!0},{signal:p}),i.addEventListener("compositionend",()=>{u=!1,h()},{signal:p}),i.addEventListener("beforeinput",m=>{let f=m,P=f.inputType;if(P==="insertParagraph"||P==="insertLineBreak"||P==="insertFromDrop"){m.preventDefault();return}if(P.startsWith("insert")||P.startsWith("delete")){let _=P.startsWith("delete")?"":f.data??"";e.replaceEditingRange(_)&&m.preventDefault()}},{signal:p}),i.addEventListener("paste",m=>{m.preventDefault();let f=(m.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!f)return;let P=i.ownerDocument??document,_=P.getSelection();if(!_||_.rangeCount===0)return;let O=_.getRangeAt(0);if(!i.contains(O.startContainer))return;O.deleteContents();let q=P.createTextNode(f);O.insertNode(q),O.setStartAfter(q),O.collapse(!0),_.removeAllRanges(),_.addRange(O),h()},{signal:p}),i.addEventListener("keydown",m=>e.handleKeyDown(m),{signal:p}),i.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:p}),i.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:p}),d&&d.addEventListener("click",m=>{let f=e.store.get();if(!(!!f.text||f.completedParams.length>0)||!e.onSubmit)return;m.stopPropagation();let{rawQuery:_,completedParams:O}=B(f.text,f.completedParams);e.onSubmit({query:f.text.trim(),raw_query:_,completed_params:O}),e.afterSubmit?.()},{signal:p}),e.autoFocus!==!1&&i.focus(),{input:i,inlinePillContainer:s,dropdown:o,submitButton:l,abort:c}}function mt(n,e,t){let{input:o,inlinePillContainer:r,dropdown:a,submitButton:i}=n,{pillPlacement:s,setActivePill:l,selectOption:d,store:c}=t;o.setAttribute("aria-expanded",String(e.isDropdownOpen));let p=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(p?o.setAttribute("aria-activedescendant",p):o.removeAttribute("aria-activedescendant"),i){let g=!!e.text||e.completedParams.length>0;i.disabled=!g}let u=o.dataset.newParamId??"",x=e.newParamId!==null&&e.newParamId!==u;if(Ke({input:o,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused}),s==="inline"){let g=e.isLoading&&!e.editingParam;g||e.actionableSuggestions.length>0?Ve(r,e.actionableSuggestions,0,l,!1,g):pt(r)}else pt(r);x?(o.focus(),M(o,e.caretOffset??e.text.length)):e.isFocused&&ae(o)!==e.text&&M(o,e.text.length);let h=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:null,y=h??e.actionableSuggestions[0];Je(a,{suggestions:y?[{...y,options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam,listboxId:t.listboxId,pills:h?[h]:e.actionableSuggestions,showPills:s==="dropdown",onSelect:d,onHighlight:g=>c.set({activeDropdownIndex:g}),onPillClick:l})}function Bt(n){let e=n,t=new Set;return{get:()=>e,set:o=>{let r=typeof o=="function"?o(e):o,a={...e,...r},i=e;e=a;for(let s of t)s(a,i)},subscribe:o=>(t.add(o),()=>{t.delete(o)})}}var gt=!1;function Ft(){if(gt||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){gt=!0;return}gt=!0;let n=document.createElement("style");n.setAttribute("data-magicx-aia",""),n.textContent=Pn,document.head.appendChild(n)}var Pn="";var In=0;function Cn(){return`:ac-${++In}:`}function Kt(){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,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:null}}var Ye=class{constructor(e,t={}){this.store=Bt(Kt());this._listboxId=Cn();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 je(this.store,{onPillSelected:({rawQuery:o,selectedPill:r,otherPills:a})=>{this.fireTelemetry("pill",{raw_query:o,selected_pill:r,other_pills:a})}}),this.fetchController=new Ge(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.opts.onError,()=>this.sessionId,{onAutoMatch:({active:o,matched:r,rawQuery:a})=>{this.fireTelemetry("option",{raw_query:a,selected_option:r.text,other_options:(o.options??[]).filter(i=>i.text!==r.text).map(i=>i.text)})}}),this.keyboardController=new Qe(this.store,{columns:t.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.opts.onSubmit,afterSubmit:this.renderMode==="full"?()=>this.reset():void 0,selectOption:o=>this.selectOption(o),removeParamAtCaret:o=>this.removeParamAtCaret(o),exitEditMode:()=>this.exitEditMode()}),this.unsubscribers.push(this.store.subscribe((o,r)=>{this.recomputeDerived(o,r)})),this.unsubscribers.push(this.store.subscribe((o,r)=>{o.text!==r.text&&this.opts.onChange?.(o.text),o.completedParams!==r.completedParams&&this.opts.onParamsChange?.(o.completedParams),o.isFocused!==r.isFocused&&(o.isFocused?this.opts.onFocus?.():this.opts.onBlur?.()),this.opts.onStateChange?.(o)})),this.renderMode!=="headless"&&(Ft(),this.setupContainer()),this.renderMode==="full"?this.buildAndRenderFull():this.renderMode==="dropdown"&&this.buildAndRenderDropdown(),this.fetchController.start()}focus(){this.domRefs?.input.focus()}blur(){this.domRefs?.input.blur()}reset(){this.store.set({...Kt(),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?.abort.abort(),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()}removeParamAtCaret(e){let t=this.store.get(),{text:o,completedParams:r}=t,a=0;for(let i=0;i<r.length;i++){let s=r[i],l=o.indexOf(s.text,a);if(l===-1)continue;let d=l,c=l+s.text.length;if(e>d&&e<=c){let p=St(o,e),u=o.slice(0,p)+o.slice(e),x=r.filter((h,y)=>y!==i);return this.store.set(h=>({text:u,filterBase:Math.min(h.filterBase,u.length),completedParams:x,pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(p),!0}a=c}return!1}scheduleSetCursor(e){queueMicrotask(()=>{let t=this.domRefs;t?M(t.input,e):this.opts.setCursor?.(e)})}clearNewParamId(){this.store.set({newParamId:null})}startEditingParam(e){let t=this.store.get();if(t.editingParam?.id===e)return;let o=t.completedParams.find(i=>i.id===e);if(!o)return;let r=0,a=-1;for(let i of t.completedParams){let s=t.text.indexOf(i.text,r);if(s!==-1){if(i.id===e){a=s;break}r=s+i.text.length}}a<0||this.store.set({editingParam:o,editingAnchor:a,editingTail:a+o.text.length,caretOffset:a+o.text.length,activeDropdownIndex:-1})}replaceEditingRange(e){let t=this.store.get(),o=t.editingParam,r=t.editingAnchor,a=t.editingTail;if(!o||r==null||a==null||!t.completedParams.some(l=>l.id===o.id))return!1;let i=t.text.slice(0,r)+e+t.text.slice(a),s=r+e.length;return this.store.set(l=>({text:i,completedParams:l.completedParams.filter(d=>d.id!==o.id),editingTail:s,caretOffset:s,activeDropdownIndex:-1})),this.scheduleSetCursor(s),this.maybePromoteEditExactMatch(),!0}exitEditMode(){this.store.get().editingParam&&this.store.set({editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1})}handleCaretAfterInput(e){let t=this.store.get(),o={caretOffset:e};t.editingParam&&t.editingAnchor!=null&&e!=null&&(e<t.editingAnchor?(o.editingParam=null,o.editingAnchor=null,o.editingTail=null,o.activeDropdownIndex=-1):t.editingTail!=null&&(o.editingTail=Math.max(t.editingTail,e))),this.store.set(o),this.maybePromoteEditExactMatch()}handleCaretMove(e){let t=this.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null&&e!=null&&(e<t.editingAnchor||e>t.editingTail)){this.store.set({caretOffset:e,editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1});return}this.store.set({caretOffset:e})}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();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null){this.selectOptionInEditMode(e);return}let o=t.actionableSuggestions[0];if(!o)return;let{rawQuery:r}=B(t.text,t.completedParams);this.fireTelemetry("option",{raw_query:r,selected_option:e.text,other_options:t.filteredOptions.filter(m=>m.text!==e.text).map(m=>m.text)});let a=t.filterBase,i=t.text.slice(0,a),s=i.length===0&&t.text.length===0,l=i.length===0&&t.text.length>0&&t.placeholderText.length>0&&t.placeholderText.toLowerCase().startsWith(t.text.toLowerCase());(s||l)&&t.placeholderText&&(i=`${t.placeholderText} `);let d=Pt(i,e.text);d>0&&(i=i.slice(0,i.length-d));let c=i.length>0&&i[i.length-1]!==" ",p=`${i}${c?" ":""}${e.text} `,u=(s||l)&&p.length>0?p[0].toUpperCase()+p.slice(1):p,x=u.toLowerCase().lastIndexOf(e.text.toLowerCase()),h=x>=0?u.slice(x,x+e.text.length):e.text,y={id:crypto.randomUUID(),placeholder:"",type:o.type,text:h,kind:e.kind,suggestionType:o.type,suggestionPlaceholder:o.text,options:o.options??[],metadata:e.metadata},g=t.actionableSuggestions.length-1;this.store.set(m=>({text:u,filterBase:u.length,completedParams:[...m.completedParams,y],newParamId:y.id,caretOffset:u.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:g>0})),this.suggestionRemovalTimer=window.setTimeout(()=>{this.store.set(m=>({suggestions:m.suggestions.filter(f=>f!==o)}))},400)}selectOptionInEditMode(e){let t=this.store.get(),o=t.editingParam,r=t.editingAnchor,a=t.editingTail;if(!o||r==null||a==null)return;this.fireTelemetry("option",{raw_query:B(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:o.options.filter(m=>m.text!==e.text).map(m=>m.text)});let i=t.text.slice(0,r),s=t.text.slice(a),l=r===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,d=s.length===0||s[0]!==" ",c=d?`${l} `:l,p=i+c+s,u=r+c.length+(d?0:1),x={id:crypto.randomUUID(),placeholder:"",type:o.suggestionType,text:l,kind:e.kind,suggestionType:o.suggestionType,suggestionPlaceholder:o.suggestionPlaceholder,options:o.options,metadata:e.metadata},h=t.completedParams.findIndex(m=>m.id===o.id),y=t.completedParams.filter(m=>m.id!==o.id),g=h>=0?Math.min(h,y.length):y.length;y.splice(g,0,x),this.store.set({text:p,completedParams:y,newParamId:x.id,filterBase:u,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:u,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0}),this.scheduleSetCursor(u)}fireTelemetry(e,t){let o=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");_t({source:o,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}recomputeDerived(e,t){if(this.derivedInProgress)return;this.derivedInProgress=!0;let o=It(e.text,e.completedParams),r=e.suggestions.filter(f=>f.type!=="placeholder"),a=r[0],i=a?this.opts.optionOverrides?.[a.type]:void 0,s=e.suggestions.filter(f=>f.type==="placeholder").map(f=>f.text).join(" "),l=be(e.text,Math.min(e.filterBase,e.text.length),s),c=e.lastRawQuery!==""||l>0?se(e.text,l,e.filterInProgress):"",p=a?i?i(c.trim()):a.options??[]:[],u=e.editingParam!=null&&e.editingAnchor!=null,x;if(u&&e.editingParam&&e.editingAnchor!=null){let f=e.editingParam.id,P=e.completedParams.some(q=>q.id===f),_=e.caretOffset??e.editingAnchor,O=P?"":e.text.slice(e.editingAnchor,_);x=xe(e.editingParam.options,O)}else x=xe(p,c);let h=this.opts.dropdownTrigger??"auto",y=this.opts.closeDropdownOnBlur??!0,g=!1;if(u){let f=y?e.isFocused:!0;g=x.length>0&&f}else if(h==="auto"){let f=y?e.isFocused:!0,P=e.text.replace(/\s+$/,"").length,_=e.caretOffset==null||e.caretOffset>=P;g=(x.length>0||e.isLoading)&&f&&_}else h==="manual"&&(g=(x.length>0||e.isLoading)&&e.pillTapped);this.store.set({segments:o,actionableSuggestions:r,filteredOptions:x,placeholderText:s,isDropdownOpen:g}),this.derivedInProgress=!1;let m=this.store.get();for(let f of this.externalListeners)f(m)}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 de(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:o=>this.selectOption(o),setActivePill:o=>this.pillsController.setActivePill(o),handleKeyDown:o=>this.keyboardController.handleKeyDown(o),handleChange:o=>this.handleChange(o),startEditingParam:o=>this.startEditingParam(o),handleCaretAfterInput:o=>this.handleCaretAfterInput(o),handleCaretMove:o=>this.handleCaretMove(o),replaceEditingRange:o=>this.replaceEditingRange(o)};this.domRefs=Ht(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&mt(this.domRefs,this.store.get(),t)}),mt(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=Nt(this.container,e),this.subscribeBatchedRender(()=>{this.dropdownRefs&&ut(this.dropdownRefs,this.store.get(),e)}),ut(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:o,invalid:r}=Ct(e,t.completedParams);r.length>0&&this.store.set({completedParams:o}),this.maybePromoteExactMatch(e)}maybePromoteExactMatch(e){let t=this.store.get(),r=t.suggestions.filter(f=>f.type!=="placeholder")[0];if(!r?.options)return;let a=t.suggestions.filter(f=>f.type==="placeholder").map(f=>f.text).join(" "),i=be(e,t.filterBase,a),s=se(e,i,t.filterInProgress),l=le(r.options,s);if(!l)return;let d=l.text.toLowerCase(),c=e.toLowerCase().lastIndexOf(d),p=c>=0?c:Math.max(0,e.length-l.text.length),u=p+l.text.length,x=e.slice(p,u),h=e,g=u<e.length&&e[u]===" "?u+1:u,m={id:crypto.randomUUID(),placeholder:"",type:r.type,text:x,kind:l.kind,suggestionType:r.type,suggestionPlaceholder:r.text,options:r.options??[],metadata:l.metadata};this.store.set(f=>({text:h,completedParams:[...f.completedParams,m],suggestions:f.suggestions.filter(P=>P!==r),filterBase:g,newParamId:m.id,caretOffset:g,activeDropdownIndex:-1}))}maybePromoteEditExactMatch(){let e=this.store.get(),t=e.editingParam,o=e.editingAnchor,r=e.editingTail;if(!t||o==null||r==null||e.completedParams.some(P=>P.id===t.id))return;let a=e.text.slice(o,r),i=le(t.options,a);if(!i)return;let s=i.text.toLowerCase(),l=a.toLowerCase().lastIndexOf(s),d=o+Math.max(0,l),c=d+i.text.length,p=e.text.slice(d,c),u=e.text,h=c<e.text.length&&e.text[c]===" "?c+1:c,y={id:crypto.randomUUID(),placeholder:"",type:t.suggestionType,text:p,kind:i.kind,suggestionType:t.suggestionType,suggestionPlaceholder:t.suggestionPlaceholder,options:t.options,metadata:i.metadata},g=e.completedParams.length,m=0;for(let P=0;P<e.completedParams.length;P++){let _=u.indexOf(e.completedParams[P].text,m);if(_!==-1){if(_>=h){g=P;break}m=_+e.completedParams[P].text.length}}let f=[...e.completedParams];f.splice(g,0,y),this.store.set(()=>({text:u,completedParams:f,newParamId:y.id,filterBase:h,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:h,activeDropdownIndex:-1})),this.scheduleSetCursor(h)}};function Ze({onSubmit:n,onError:e,optionOverrides:t,maskCompletedText:o,apiConfig:r,columns:a=2,dropdownTrigger:i,closeDropdownOnBlur:s,onFocus:l,onBlur:d,value:c,completedParams:p,onChange:u,onParamsChange:x,source:h,setCursor:y}){let g=(0,S.useRef)(null),[m,f]=(0,S.useState)(null),P=(0,S.useRef)(n);P.current=n;let _=(0,S.useRef)(e);_.current=e;let O=(0,S.useRef)(u);O.current=u;let q=(0,S.useRef)(x);q.current=x;let ce=(0,S.useRef)(l);ce.current=l;let k=(0,S.useRef)(d);k.current=d;let pe=(0,S.useRef)(y);pe.current=y,(0,S.useEffect)(()=>{if(typeof document>"u")return;let w=new Ye(document.createElement("div"),{renderMode:"headless",apiConfig:r,optionOverrides:t,maskCompletedText:o,columns:a,dropdownTrigger:i,closeDropdownOnBlur:s,source:h,value:c,completedParams:p,onSubmit:(...D)=>P.current?.(...D),onError:(...D)=>_.current?.(...D),onChange:(...D)=>O.current?.(...D),onParamsChange:(...D)=>q.current?.(...D),onFocus:()=>ce.current?.(),onBlur:()=>k.current?.(),setCursor:D=>pe.current?.(D)});g.current=w,f(w.getState());let R=w.subscribe(D=>f(D));return()=>{R(),w.destroy(),g.current===w&&(g.current=null)}},[]);let b=g.current,T=(0,S.useCallback)(()=>{},[]);(0,S.useEffect)(()=>{c!==void 0&&b?.setValue(c)},[c,b]),(0,S.useEffect)(()=>{p!==void 0&&b?.setCompletedParams(p)},[p,b]);let ye=JSON.stringify(r??null),te=(0,S.useRef)(t),ue=(0,S.useRef)(0);if(t!==te.current){let w=te.current,R=t,D=Object.keys(w??{}),U=Object.keys(R??{});(D.length!==U.length||U.some(Z=>!w?.[Z]||R[Z]!==w[Z]))&&ue.current++,te.current=t}(0,S.useEffect)(()=>{b?.update({apiConfig:r,optionOverrides:t,dropdownTrigger:i,closeDropdownOnBlur:s})},[ye,ue.current,i,s,b]);let we=(0,S.useCallback)(w=>{if(!b)return;let R=w.target.value,U=R.length>0&&!w.nativeEvent?.isComposing&&R[0]!==R[0].toUpperCase()?R[0].toUpperCase()+R.slice(1):R;b.handleTextChange(U)},[b]),tt=(0,S.useCallback)(w=>{b?.handleKeyDown(w.nativeEvent)},[b]),me=(0,S.useCallback)(()=>b?.setFocused(!0),[b]),Se=(0,S.useCallback)(()=>b?.setFocused(!1),[b]),nt=(0,S.useCallback)(w=>b?.handleTextChange(w),[b]),ge=(0,S.useCallback)(w=>{if(!b)return;let R="nativeEvent"in w?w.nativeEvent:w;b.handleKeyDown(R)},[b]),V=(0,S.useCallback)(w=>b?.setFocused(w),[b]),Pe=(0,S.useCallback)(w=>b?.startEditingParam(w),[b]),Ie=(0,S.useCallback)(()=>b?.exitEditMode(),[b]),Ce=(0,S.useCallback)(w=>b?.handleCaretAfterInput(w),[b]),ot=(0,S.useCallback)(w=>b?.handleCaretMove(w),[b]),Ae=(0,S.useCallback)(w=>b?.replaceEditingRange(w)??!1,[b]),fe=(0,S.useCallback)(w=>b?.setActivePill(w),[b]),_e=(0,S.useCallback)(()=>b?.removeLastParam(),[b]),Te=(0,S.useCallback)(()=>b?.clearNewParamId(),[b]),Ee=(0,S.useCallback)(()=>b?.reset(),[b]),ne=(0,S.useCallback)(w=>b?.selectOption(w),[b]),X=(0,S.useCallback)(w=>b?.setActiveDropdownIndex(w),[b]);if(!b)return{completedParams:p??[],suggestionPills:[],setActivePill:T,removeLastParam:T,segments:[],newParamId:null,clearNewParamId:T,suggestions:[],activeIndex:-1,isReady:!1,isLoading:!0,isFocused:!1,isDropdownOpen:!1,placeholderText:"",listboxId:"",error:null,handleTextChange:T,handleKeyDown:T,setFocused:T,editingParam:null,editingAnchor:null,caretOffset:null,startEditingParam:T,exitEditMode:T,handleCaretAfterInput:T,handleCaretMove:T,replaceEditingRange:()=>!1,inputProps:{value:c??"",placeholder:void 0,onChange:T,onKeyDown:T,onFocus:T,onBlur:T,role:"combobox","aria-expanded":!1,"aria-activedescendant":void 0,"aria-autocomplete":"list","aria-controls":""},reset:T,dropdownProps:{suggestions:[],activeIndex:-1,onSelect:T,onHighlight:T,isOpen:!1,id:"",pills:[],onPillClick:T}};let A=m??b.getState(),it=c!==void 0?c:A.text,ke=p!==void 0?p:A.completedParams,oe=A.actionableSuggestions,Oe=oe[0],De=A.filteredOptions,rt=A.activeDropdownIndex>=0?`${b.listboxId}-option-${A.activeDropdownIndex}`:void 0,z=A.editingParam,W=z?{type:z.suggestionType,text:z.suggestionPlaceholder,required:!0,options:z.options}:null,Le=W??Oe,at=W?[W]:oe;return{completedParams:ke,suggestionPills:oe,setActivePill:fe,removeLastParam:_e,segments:A.segments,newParamId:A.newParamId,clearNewParamId:Te,suggestions:A.suggestions,activeIndex:A.activeDropdownIndex,isReady:A.isReady,isLoading:A.isLoading,isFocused:A.isFocused,isDropdownOpen:A.isDropdownOpen,placeholderText:A.placeholderText,listboxId:b.listboxId,error:A.error,handleTextChange:nt,handleKeyDown:ge,setFocused:V,editingParam:z,editingAnchor:A.editingAnchor,caretOffset:A.caretOffset,startEditingParam:Pe,exitEditMode:Ie,handleCaretAfterInput:Ce,handleCaretMove:ot,replaceEditingRange:Ae,inputProps:{value:it,placeholder:A.placeholderText||void 0,onChange:we,onKeyDown:tt,onFocus:me,onBlur:Se,role:"combobox","aria-expanded":A.isDropdownOpen,"aria-activedescendant":rt,"aria-autocomplete":"list","aria-controls":b.listboxId},reset:Ee,dropdownProps:{suggestions:Le?[{...Le,options:De}]:[],activeIndex:A.activeDropdownIndex,onSelect:ne,onHighlight:X,isOpen:A.isDropdownOpen,id:b.listboxId,pills:at,onPillClick:fe,isLoading:A.isLoading&&!A.editingParam}}}var F=require("react/jsx-runtime");function An(n){return n!=="auto"?n:typeof window>"u"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}var et;function _n(){if(et!==void 0)return et;if(typeof document>"u")return!1;let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),et=n.contentEditable==="plaintext-only",et}var zt=(0,I.forwardRef)(function({onSubmit:e,onError:t,optionOverrides:o,maskCompletedText:r,className:a,apiConfig:i,columns:s,pillPlacement:l="inline",mode:d="auto",optionsPosition:c="below",animations:p=!0,dropdownTrigger:u,closeDropdownOnBlur:x,autoFocus:h=!0,onFocus:y,onBlur:g,value:m,completedParams:f,onChange:P,onParamsChange:_,submitButton:O},q){let ce=(0,I.useRef)(null),k=(0,I.useRef)(null),pe=(0,I.useRef)(()=>{}),b=(0,I.useRef)(null),T=(0,I.useRef)(!1),ye=(0,I.useRef)(""),te=(0,I.useRef)(""),ue=(0,I.useRef)(null),we=(0,I.useRef)(0);(0,I.useEffect)(()=>{let v=ce.current;if(v)return b.current?b.current.setMode(d):b.current=new de(v,d),()=>{b.current?.destroy(),b.current=null}},[d]);let tt=(0,I.useCallback)(v=>{let C=k.current;C&&M(C,v)},[]),{completedParams:me,suggestionPills:Se,setActivePill:nt,segments:ge,newParamId:V,clearNewParamId:Pe,placeholderText:Ie,isFocused:Ce,isDropdownOpen:ot,isLoading:Ae,activeIndex:fe,listboxId:_e,handleTextChange:Te,handleKeyDown:Ee,setFocused:ne,editingParam:X,editingAnchor:A,caretOffset:it,startEditingParam:ke,handleCaretAfterInput:oe,handleCaretMove:Oe,replaceEditingRange:De,dropdownProps:rt,reset:z}=Ze({onSubmit:v=>pe.current(v),onError:t,optionOverrides:o,maskCompletedText:r,apiConfig:i,columns:s,dropdownTrigger:u,closeDropdownOnBlur:x,onFocus:y,onBlur:g,value:m,completedParams:f,onChange:P,onParamsChange:_,source:"full-sdk",setCursor:tt});ue.current=it,(0,I.useEffect)(()=>{if(!h)return;let v=k.current;v&&(document.activeElement===v?ne(!0):v.focus())},[h,ne]),(0,I.useEffect)(()=>{if(!V)return;let v=window.setTimeout(()=>Pe(),650);return()=>window.clearTimeout(v)},[V,Pe]),(0,I.useEffect)(()=>{let v=k.current;if(!v)return;let C=v.ownerDocument??document,E=()=>{let N=C.getSelection();if(!N||N.rangeCount===0||!N.anchorNode||!v.contains(N.anchorNode))return;let L=N.anchorNode,lt=(L.nodeType===Node.ELEMENT_NODE?L:L.parentElement)?.closest('strong[data-seg="completed"][data-param-id]')?.dataset.paramId??null;if(lt&&lt!==X?.id){ke(lt);return}performance.now()-we.current<50||Oe(K(v))};return C.addEventListener("selectionchange",E),()=>C.removeEventListener("selectionchange",E)},[X,ke,Oe]),(0,I.useLayoutEffect)(()=>{let v=k.current;v&&Ke({input:v,segments:ge,newParamId:V,editingParamId:X?.id??null,placeholderText:Ie??"",isFocused:Ce})},[ge,V,X,Ie,Ce]),(0,I.useLayoutEffect)(()=>{let v=ye.current,C=V??"";if(ye.current=C,!C||C===v)return;let E=k.current;if(!E)return;E.focus();let N=ue.current??Fe(E);M(E,N)},[V]),(0,I.useLayoutEffect)(()=>{let v=te.current,C=X?.id??"";if(te.current=C,!C||C===v||A==null)return;let E=k.current;E&&M(E,A)},[X,A]),(0,I.useImperativeHandle)(q,()=>({focus:()=>k.current?.focus(),blur:()=>k.current?.blur(),reset:z,setMode:v=>b.current?.setMode(v)}),[z]);let W=(0,I.useCallback)(()=>{if(T.current)return;let v=k.current;if(!v)return;let C=ae(v),N=C.length>0&&C[0]!==C[0].toUpperCase()?C[0].toUpperCase()+C.slice(1):C;Te(N)},[Te]),Le=(0,I.useCallback)(()=>{we.current=performance.now(),W();let v=k.current;v&&oe(K(v))},[W,oe]);(0,I.useEffect)(()=>{let v=k.current;if(!v)return;let C=E=>{let N=E,L=N.inputType;if(L==="insertParagraph"||L==="insertLineBreak"||L==="insertFromDrop"){E.preventDefault();return}if(L.startsWith("insert")||L.startsWith("delete")){let G=L.startsWith("delete")?"":N.data??"";De(G)&&E.preventDefault()}};return v.addEventListener("beforeinput",C),()=>v.removeEventListener("beforeinput",C)},[De]);let at=(0,I.useCallback)(()=>{T.current=!0},[]),w=(0,I.useCallback)(()=>{T.current=!1,W()},[W]),R=(0,I.useCallback)(v=>{v.preventDefault();let C=k.current;if(!C)return;let E=(v.clipboardData.getData("text/plain")??"").replace(/\r?\n/g," ");if(!E)return;let N=C.ownerDocument??document,L=N.getSelection();if(!L||L.rangeCount===0)return;let G=L.getRangeAt(0);if(!C.contains(G.startContainer))return;G.deleteContents();let st=N.createTextNode(E);G.insertNode(st),G.setStartAfter(st),G.collapse(!0),L.removeAllRanges(),L.addRange(G),W()},[W]),D=(0,I.useCallback)(v=>Ee(v),[Ee]),U=!!ge.length||me.length>0,Z=(0,I.useCallback)(()=>{if(!U)return;let v=k.current?ae(k.current):"",{rawQuery:C,completedParams:E}=B(v,me);e({query:v.trim(),raw_query:C,completed_params:E}),z()},[U,me,e,z]);pe.current=Z;let Wt=(0,I.useCallback)(v=>{v.target?.closest("[data-aia-pill]")||k.current?.focus()},[]),$t=l==="inline",qt=l==="dropdown",Ut=fe>=0?`${_e}-option-${fe}`:void 0,Gt=_n()?"plaintext-only":"true";return(0,F.jsxs)("div",{ref:ce,className:`magicx-aia ${J.container} ${a??""}`,"data-pill-placement":l,"data-options-position":c,"data-animations":p?"on":"off","data-mode":An(d),children:[(0,F.jsx)(Ne,{...rt,showPills:qt}),(0,F.jsxs)("div",{className:J.inputWrapper,onClick:Wt,children:[(0,F.jsxs)("div",{className:J.editorArea,"data-aia-editor":"",children:[(0,F.jsx)("div",{ref:k,className:J.input,"data-aia-input":"",contentEditable:Gt,suppressContentEditableWarning:!0,tabIndex:0,role:"combobox","aria-autocomplete":"list","aria-haspopup":"listbox","aria-controls":_e,"aria-expanded":ot,"aria-activedescendant":Ut,spellCheck:!0,enterKeyHint:"send",onInput:Le,onKeyDown:D,onCompositionStart:at,onCompositionEnd:w,onPaste:R,onFocus:()=>ne(!0),onBlur:()=>ne(!1)}),$t&&(Ae||Se.length>0)&&(0,F.jsx)("span",{className:J.pillListContainer,"data-aia-pill-list-container":"",children:(0,F.jsx)(Me,{pills:Se,activePillIndex:0,onSelectPill:nt,loading:Ae})})]}),O===null?null:O===void 0?(0,F.jsx)("button",{type:"button","data-aia-submit":"",className:J.submitButton,disabled:!U,onClick:v=>{v.stopPropagation(),Z()},"aria-label":"Submit",children:(0,F.jsx)("svg",{width:"18",height:"18",viewBox:"0 0 18 18",fill:"none",role:"img","aria-label":"Submit",children:(0,F.jsx)("path",{d:"M9 14V4M9 4L4 9M9 4L14 9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}):(0,F.jsx)("span",{"data-aia-submit":"",className:J.submitSlot,onClick:v=>{U&&(v.stopPropagation(),Z())},children:O})]})]})});0&&(module.exports={AIAutocomplete,AIAutocompleteDropdown,useAIAutocomplete});
801
+ `,document.head.appendChild(n)}var vt='[contenteditable="false"]',re;function tn(){if(re!==void 0)return re;let n=globalThis.Intl.Segmenter;if(!n)return re=null,null;try{re=new n(void 0,{granularity:"grapheme"})}catch{re=null}return re??null}function He(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(vt))return!0;t=t.parentNode}return!1}function Be(n){return(n.ownerDocument??document).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return He(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function ae(n){let e=Be(n),t="",o=e.nextNode();for(;o;)t+=o.data,o=e.nextNode();return t}function Fe(n){let e=Be(n),t=0,o=e.nextNode();for(;o;)t+=o.data.length,o=e.nextNode();return t}function F(n){let e=(n.ownerDocument??document).getSelection();if(!e||e.rangeCount===0)return null;let t=e.anchorNode,o=e.anchorOffset;if(!t||!n.contains(t))return null;if(t.nodeType===Node.ELEMENT_NODE){let r=t;if(He(r,n)&&r!==n)return null;let a=0;for(let i=0;i<o&&i<r.childNodes.length;i++)a+=yt(r.childNodes[i],n);return a+xt(r,n)}return t.nodeType!==Node.TEXT_NODE||He(t,n)?null:xt(t,n)+o}function yt(n,e){if(n.nodeType===Node.TEXT_NODE)return He(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(vt))return 0;let o=0;for(let r of Array.from(t.childNodes))o+=yt(r,e);return o}function xt(n,e){let t=Be(e),o=0,r=t.nextNode();for(;r;){if(r===n||n.nodeType===Node.ELEMENT_NODE&&n.contains(r))return o;o+=r.data.length,r=t.nextNode()}return o}function M(n,e){let t=n.ownerDocument??document,o=t.getSelection();if(!o)return;let r=Math.max(0,Math.min(e,Fe(n))),a=Be(n),i=0,s=null,d=0,l=a.nextNode(),p=null;for(;l;){let c=l.data.length;if(r<i+c){s=l,d=r-i;break}if(r===i+c){let h=a.nextNode();h?(s=h,d=0):(s=l,d=c);break}i+=c,p=l,l=a.nextNode()}let u=t.createRange();if(s){let c=s.parentElement?.closest('strong[data-seg="completed"]');c&&c!==n&&n.contains(c)?d===0?u.setStartBefore(c):d===s.data.length?u.setStartAfter(c):u.setStart(s,d):u.setStart(s,d)}else p?u.setStart(p,p.data.length):u.setStart(n,0);u.collapse(!0),o.removeAllRanges(),o.addRange(u)}function wt(n){let e=F(n);return e==null?!1:e>=Fe(n)}function St(n,e){if(e<=0)return 0;let t=tn();if(!t)return e-1;let o=n.slice(0,e),r=0;for(let{index:a}of t.segment(o))a<e&&(r=a);return r}function Ke(n){let{input:e,segments:t,newParamId:o,editingParamId:r,placeholderText:a,isFocused:i}=n,s=t.length===0;e.dataset.aiaEmpty=s?"true":"false",s&&a?e.dataset.placeholder=a:delete e.dataset.placeholder;let d=t.map(f=>`${f.type}:${f.value}`).join("\0"),l=e.dataset.segKey??"",p=e.dataset.newParamId??"",u=e.dataset.editingParamId??"";if(d===l&&(o??"")===p&&(r??"")===u)return;let c=i?F(e):null;e.dataset.segKey=d,e.dataset.newParamId=o??"",e.dataset.editingParamId=r??"";let h=e.ownerDocument??document,b=h.createDocumentFragment(),v=0;for(let f of t)if(v+=f.value.length,f.type==="completed"){let m=h.createElement("strong");m.dataset.seg="completed",m.dataset.paramId=f.param.id;let g=f.param.id===o,w=f.param.id===r,T=["magicx-aia-segment","magicx-aia-segment--completed"];g&&T.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),w&&T.push("magicx-aia-segment--editing"),m.className=T.join(" "),m.textContent=f.value,b.appendChild(m)}else b.appendChild(h.createTextNode(f.value));e.replaceChildren(b),e.dataset.aiaTextLength=String(v),c!=null&&M(e,Math.max(0,Math.min(c,v)))}var P=require("react");function H(n,e){let t=n,o={},r=[];for(let a of e){let i=(o[a.type]??0)+1;o[a.type]=i;let d=`{{${a.type.toUpperCase().replace(/\s+/g,"_")}_${i}}}`,l=t.indexOf(a.text);l!==-1&&(t=t.slice(0,l)+d+t.slice(l+a.text.length)),r.push({...a,placeholder:d})}return{rawQuery:t,completedParams:r}}function xe(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function se(n,e,t){let o=n.slice(e);if(t||e===0||n[e-1]===" ")return o;let r=o.indexOf(" ");return r===-1?"":o.slice(r+1)}function Pt(n,e){let t=n.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let o=t.split(" "),r=e.toLowerCase();for(let a=0;a<o.length;a++){let i=o.slice(a).join(" ");if(r.startsWith(i.toLowerCase())){let s=t.length-i.length;return n.length-s}}return 0}function ve(n,e){if(!n)return[];let t=e.trimStart();if(!t)return n;let o=t.toLowerCase();return n.filter(r=>!r.is_tappable||r.text.toLowerCase().includes(o))}function le(n,e){if(!n)return null;let t=e.trim();if(!t)return null;let o=t.toLowerCase();return n.find(r=>r.is_tappable&&r.text.toLowerCase()===o)??null}var de=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 It(n,e){let t=[],o=0;for(let a of e){let i=n.indexOf(a.text,o);i!==-1&&(i>o&&t.push({type:"text",value:n.slice(o,i)}),t.push({type:"completed",value:a.text,param:a}),o=i+a.text.length)}let r=n.slice(o);return r&&t.push({type:"text",value:r}),t}function At(n,e){let t=[],o=[],r=0;for(let a of e){let i=n.indexOf(a.text,r);i===-1?o.push(a):(t.push(a),r=i+a.text.length)}return{valid:t,invalid:o}}var ze=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 nn="https://api.ai-autocomplete.com",We=`${nn}/api/suggest`,Ct=new WeakMap;function ye(n){return n?.type==="accessToken"}function on(n){if(!(!n||ye(n)))return n}function $e(n){let e=Ct.get(n.getAccessToken);return e||(e=new ze(n),Ct.set(n.getAccessToken,e)),e}function qe(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function Ue(n){let e=on(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}function rn(n){return(n??We).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function an(n){return ye(n)?`Bearer ${await $e(n).getToken()}`:Ue(n)}async function Tt(n){try{let e=rn(n.apiConfig?.endpoint),t=qe(n.apiConfig),o=await an(n.apiConfig);o&&(t.Authorization=o);let r=JSON.stringify({source:n.source,session_id:n.sessionId,type:n.type,at:new Date().toISOString(),query_data:n.queryData});await fetch(e,{method:"POST",headers:t,body:r})}catch{}}var sn="0.1.41",_t=!1;function ln(){return crypto.randomUUID()}function dn(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.text},kind:n.kind}}function cn(n,e,t,o){let r=e.find(i=>i.type==="contact"&&i.metadata?.contact_account_count)?.metadata?.contact_account_count,a=typeof r=="number"?r:void 0;return{data:{raw_query:n,completed_params:e.map(i=>dn(i,t)),...a!=null&&{contact_account_count:a}},meta:{request_id:ln(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:sn,session_id:o}}}async function Et(n,e,t,o,r){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:o,signal:r})}async function kt(n,e,t){let o=t.apiConfig,r=!t.maskCompletedText,a=cn(n,e,r,t.sessionId),i=qe(o),s=o?.endpoint??We,d=JSON.stringify(a);if(ye(o)){let u=$e(o),c=await u.getToken(),h=await Et(s,i,c,d,t.signal);if(h.status===401){let b=await u.getToken(!0);h=await Et(s,i,b,d,t.signal)}if(!h.ok)throw new Error(`API error: ${h.status} ${h.statusText}`);return h.json()}let l=Ue(o);!l&&!_t&&(_t=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),l&&(i.Authorization=l);let p=await fetch(s,{method:"POST",headers:i,body:d,signal:t.signal});if(!p.ok)throw new Error(`API error: ${p.status} ${p.statusText}`);return p.json()}function Ot(n,e){return e?n.map(t=>{let o=e[t.type];if(!o)return t;let r=o("");if(r.length===0)return t;let a=new Set(r.map(s=>s.text)),i=(t.options??[]).filter(s=>!a.has(s.text));return{...t,options:[...r,...i]}}):n}var pn=100,un=300,mn=2,Ge=class{constructor(e,t,o,r,a,i,s={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=o;this.getMaskCompletedText=r;this.getOnError=a;this.getSessionId=i;this.callbacks=s;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(o=>{(o.text!==e||o.completedParams!==t)&&(e=o.text,t=o.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let o=new AbortController;this.abortController=o;let r=++this.fetchVersion,a=this.store.get().text.length;this.store.set({isLoading:!0,error:null});try{let i=await kt(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:o.signal,apiConfig:this.getApiConfig()});if(r!==this.fetchVersion)return;let s=Ot(i.data.suggestions??[],this.getOptionOverrides()),d=i.data.input??[],l=d[d.length-1],p=this.store.get().text,u,c;if(l?.state==="in_progress"){c=!0;let f=p.toLowerCase().lastIndexOf(l.text.toLowerCase());u=f!==-1?f:a}else c=!1,u=a;let b=s.filter(f=>f.type!=="placeholder")[0],v=null;if(b){let f=se(p,u,c),m=le(b.options,f);m&&(v={id:crypto.randomUUID(),placeholder:"",type:b.type,text:m.text,kind:m.kind,suggestionType:b.type,suggestionPlaceholder:b.text,options:b.options??[],metadata:m.metadata},s=s.filter(g=>g!==b),this.callbacks.onAutoMatch?.({active:b,matched:m,rawQuery:e}))}this.store.set(f=>({suggestions:s,isLoading:!1,isReady:i.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:u,filterInProgress:c,...v?{completedParams:[...f.completedParams,v]}:{}}))}catch(i){if(r===this.fetchVersion){let s=i instanceof Error?i:new Error(String(i));this.store.set({error:s,isLoading:!1}),this.getOnError()?.(s)}}}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}let t=o=>{let r=this.store.get();if(!r.text&&r.completedParams.length===0)return this.doFetch("",[]),!0;let a=r.suggestions.filter(g=>g.type==="placeholder").map(g=>g.text).join(" "),i=xe(r.text,r.filterBase,a),s=se(r.text,i,r.filterInProgress),l=r.suggestions.filter(g=>g.type!=="placeholder")[0],u=(l?ve(l.options,s):[]).filter(g=>g.is_tappable),c=l?le(l.options,s)!==null:!1,h=s.trim().length>0;if(u.length>0&&!c&&h||r.completedParams.length===0&&r.text.length>0&&a.length>0&&a.toLowerCase().startsWith(r.text.toLowerCase()))return!1;let{rawQuery:b,completedParams:v}=H(r.text,r.completedParams),f=b.length<r.lastRawQuery.length,m=Math.abs(b.length-r.lastRawQuery.length);return f||m>=o?(this.doFetch(b,v),!0):!1};this.debounceTimer=setTimeout(()=>{t(mn)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},pn),this.slowDebounceTimer=setTimeout(()=>t(1),un)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};function Dt(n){return n instanceof HTMLTextAreaElement||n instanceof HTMLInputElement?n.selectionStart!=null&&n.selectionStart===n.value.length:n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?wt(n):!1}function gn(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?F(n):null}var Qe=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:o,getOnSubmit:r}=this.ctx,a=this.getEffectiveColumns(),i=r(),s=this.getTappableIndices(a);switch(e.key){case"ArrowDown":{let d=Dt(e.target),l=!!t.editingParam;if(!d&&!l&&t.activeDropdownIndex<0)break;if(e.preventDefault(),!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:s[0]??0});break}if(s.length===0)return;let p=s.indexOf(t.activeDropdownIndex),u=p<s.length-1?p+1:0;this.store.set({activeDropdownIndex:s[u]});break}case"ArrowUp":{if(s.length===0||t.activeDropdownIndex<0)break;if(e.preventDefault(),t.activeDropdownIndex<a){this.store.set({activeDropdownIndex:-1});break}let d=s.indexOf(t.activeDropdownIndex),l=d>0?d-1:s.length-1;this.store.set({activeDropdownIndex:s[l]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%a<a-1){let p=t.activeDropdownIndex+1;p<t.filteredOptions.length&&t.filteredOptions[p]?.is_tappable&&this.store.set({activeDropdownIndex:p})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let l=e.target.closest("[data-aia-input]")??e.target,p=t.editingTail;this.ctx.exitEditMode?.(),M(l,p);break}Dt(e.target)&&t.actionableSuggestions.length>1&&(e.preventDefault(),this.pillsSetActivePill(1));break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%a>0){let d=t.activeDropdownIndex-1;d>=0&&t.filteredOptions[d]?.is_tappable&&this.store.set({activeDropdownIndex:d})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let d=e.target.closest("[data-aia-input]")??e.target,l=t.editingAnchor;this.ctx.exitEditMode?.(),M(d,l);break}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let d=gn(e.target);if(d==null)break;this.ctx.removeParamAtCaret(d)&&e.preventDefault();break}case"Enter":{if(e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable)this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,o);else if(i){let{rawQuery:d,completedParams:l}=H(t.text,t.completedParams);i({query:t.text.trim(),raw_query:d,completed_params:l}),this.ctx.afterSubmit?.()}break}case"Tab":{let d=!t.text&&!!t.placeholderText,l=t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable;if(d&&!l){e.preventDefault();let p=t.placeholderText;if(this.store.set(u=>({text:p,filterBase:p.length,suggestions:u.suggestions.filter(c=>c.type!=="placeholder")})),e.target instanceof HTMLElement){let u=e.target.closest("[data-aia-input]")??e.target;queueMicrotask(()=>M(u,p.length))}}else if(l)e.preventDefault(),this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,o);else if(t.isDropdownOpen){let p=t.filteredOptions.findIndex(u=>u.is_tappable);p>=0&&(e.preventDefault(),this.clickOrSelect(p,t.filteredOptions,o))}break}case"Escape":{if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){let d=e.target.closest("[data-aia-input]")??e.target,l=t.editingTail;this.ctx.exitEditMode?.(),M(d,l)}this.store.set({activeDropdownIndex:-1});break}}}getTappableIndices(e){let o=this.store.get().filteredOptions.map((a,i)=>a.is_tappable?i:-1).filter(a=>a!==-1),r=Array.from({length:e},()=>[]);for(let a of o)r[a%e].push(a);return r.flat()}getEffectiveColumns(){let t=document.getElementById(`${this.ctx.listboxId}-option-0`)?.parentElement;if(!t)return this.ctx.columns;let o=getComputedStyle(t).gridTemplateColumns.split(" ").filter(Boolean).length;return o>0?o:this.ctx.columns}clickOrSelect(e,t,o){let r=document.getElementById(`${o}-option-${e}`);r?r.click():this.ctx.selectOption(t[e])}pillsSetActivePill(e){let t=this.store.get(),o=t.suggestions.filter(s=>s.type!=="placeholder");if(e<0||e>=o.length)return;let r=o[e],a=o.filter((s,d)=>d!==e),i=t.suggestions.filter(s=>s.type==="placeholder");this.store.set({suggestions:[...i,r,...a],pillTapped:!0,activeDropdownIndex:-1})}};var je=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),o=t.suggestions.filter(s=>s.type!=="placeholder");if(e<0||e>=o.length)return;let r=o[e],a=o.filter((s,d)=>d!==e),i=t.suggestions.filter(s=>s.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:s}=H(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:s,selectedPill:r.text,otherPills:a.map(d=>d.text)})}this.store.set({suggestions:[...i,r,...a],pillTapped:!0,activeDropdownIndex:-1})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};var Lt=[125,69];function Mt(n){return n===0?.4:n===1?.3:.15}function Ve(n,e,t,o,r=!1,a=!1){let i=n.querySelector(".magicx-aia-pill-list");if(i||(i=document.createElement("span"),i.className="magicx-aia-pill-list",n.appendChild(i)),a&&e.length===0){i.setAttribute("data-aia-pill-list-loading",""),i.innerHTML="";for(let l=0;l<Lt.length;l++){let p=Lt[l],u=document.createElement("span");u.setAttribute("data-aia-pill-skeleton",""),u.className=`magicx-aia-pill magicx-aia-pill--skeleton${r?" magicx-aia-pill--rounded":""}`,u.style.width=`${p}px`,u.style.opacity=String(Mt(l)),i.appendChild(u)}return}a?i.setAttribute("data-aia-pill-list-loading",""):i.removeAttribute("data-aia-pill-list-loading");for(let l of i.querySelectorAll("[data-aia-pill-skeleton]"))l.remove();let s=new Map;for(let l of i.querySelectorAll(".magicx-aia-pill"))s.set(l.dataset.pillKey??"",l);let d=new Set;for(let l=0;l<e.length;l++){let p=e[l],u=`${p.type}-${p.text}`;d.add(u);let c=s.get(u);(!c||c.tagName!=="BUTTON")&&(c?.remove(),c=document.createElement("button"),c.type="button",c.tabIndex=-1,c.dataset.pillKey=u,c.setAttribute("data-aia-pill",""),c.setAttribute("contenteditable","false"),c.textContent=p.text,c.addEventListener("mousedown",b=>b.preventDefault()));let h=["magicx-aia-pill"];r&&h.push("magicx-aia-pill--rounded"),l===t&&!a&&h.push("magicx-aia-pill--active"),a&&h.push("magicx-aia-pill--skeleton"),c.className=h.join(" "),c.style.width="",c.style.opacity=String(Mt(l)),a?(c.setAttribute("data-aia-loading",""),c.disabled=!0,c.onclick=null):(c.removeAttribute("data-aia-loading"),c.disabled=!1,c.onclick=()=>o(l)),i.children[l]!==c&&i.insertBefore(c,i.children[l]??null)}for(let[l,p]of s)d.has(l)||p.remove()}function pt(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var fn=[159,119,164];function Xe(n){let e=document.createElement("div");return e.id=n,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",t=>t.preventDefault()),e}function Je(n,e){let{filteredOptions:t,activeIndex:o,isOpen:r,isLoading:a,pills:i,showPills:s,onSelect:d,onHighlight:l,onPillClick:p}=e,u=s&&i.length>0,c=t.length>0;r&&(c||u||a)?n.classList.add("magicx-aia-dropdown--visible"):n.classList.remove("magicx-aia-dropdown--visible"),a?n.setAttribute("data-aia-loading",""):n.removeAttribute("data-aia-loading");let b=u||a&&s,v=n.querySelector(".magicx-aia-pill-bar");b?(v||(v=document.createElement("div"),v.className="magicx-aia-pill-bar",v.setAttribute("data-aia-pillbar",""),n.insertBefore(v,n.firstChild)),Ve(v,i,0,p,!0,a)):v&&v.remove();let f=n.querySelector(".magicx-aia-grid");c?(f||(f=document.createElement("div"),f.className="magicx-aia-grid",n.appendChild(f)),hn(f,t,o,d,l,e.listboxId,a)):f&&f.remove();let m=n.querySelector(".magicx-aia-skeleton-bars");if(a&&!c){if(!m){m=document.createElement("div"),m.className="magicx-aia-skeleton-bars",m.setAttribute("data-aia-skeleton-bars","");for(let g of fn){let w=document.createElement("span");w.className="magicx-aia-skeleton-bar",w.style.width=`${g}px`,m.appendChild(w)}n.appendChild(m)}}else m&&m.remove()}function hn(n,e,t,o,r,a,i){let s=e.map(c=>c.text).join("\0"),d=n.dataset.optionsKey??"",l=n.dataset.loading??"",p=i?"1":"0",u=s!==d||l!==p;if(n.dataset.optionsKey=s,n.dataset.loading=p,u){let c=document.createDocumentFragment();for(let h=0;h<e.length;h++){let b=e[h],v=bn(b,h,t,o,r,a,i);c.appendChild(v)}n.innerHTML="",n.appendChild(c)}else{let c=n.querySelectorAll(".magicx-aia-option");for(let h=0;h<c.length;h++){let b=c[h],v=h===t&&!i;b.setAttribute("aria-selected",String(v)),v?b.classList.add("magicx-aia-option--highlighted"):b.classList.remove("magicx-aia-option--highlighted")}}}function bn(n,e,t,o,r,a,i){let s=document.createElement("div");s.id=`${a}-option-${e}`,s.setAttribute("role","option"),s.setAttribute("data-aia-option",""),i&&s.setAttribute("data-aia-loading",""),s.setAttribute("aria-selected",String(e===t&&!i)),s.tabIndex=i||!n.is_tappable?-1:0;let d=["magicx-aia-option"];e===t&&!i&&d.push("magicx-aia-option--highlighted"),n.is_tappable?d.push("magicx-aia-option--tappable"):d.push("magicx-aia-option--non-tappable"),s.className=d.join(" ");let l=document.createElement("div");l.className="magicx-aia-streaks",s.appendChild(l);let p=document.createElement("div");p.className="magicx-aia-streaks-vert",s.appendChild(p);let u=document.createElement("span");if(u.className="magicx-aia-option-content",u.textContent=n.icon?`${n.icon} ${n.text}`:n.text,n.tag){let c=document.createElement("span");c.className="magicx-aia-option-tag",c.textContent=n.tag,u.appendChild(c)}return s.appendChild(u),!i&&n.is_tappable&&(s.addEventListener("click",()=>{s.classList.add("magicx-aia-option--pressed"),o(n),setTimeout(()=>s.classList.remove("magicx-aia-option--pressed"),500)}),s.addEventListener("mouseenter",()=>r(e))),s}function Rt(n,e){let t=Xe(e.listboxId);return n.appendChild(t),{dropdown:t}}function ut(n,e,t){Je(n.dropdown,{suggestions:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,onSelect:t.selectOption,onHighlight:o=>t.store.set({activeDropdownIndex:o}),onPillClick:t.setActivePill})}var xn='<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 vn(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function Nt(n,e){let{listboxId:t}=e,o=Xe(t);n.appendChild(o);let r=document.createElement("div");r.className="magicx-aia-input-wrapper",n.appendChild(r);let a=document.createElement("div");a.className="magicx-aia-editor",a.setAttribute("data-aia-editor",""),r.appendChild(a);let i=document.createElement("div");i.className="magicx-aia-input",i.setAttribute("data-aia-input",""),i.setAttribute("contenteditable",vn()?"plaintext-only":"true"),i.setAttribute("role","combobox"),i.setAttribute("aria-autocomplete","list"),i.setAttribute("aria-haspopup","listbox"),i.setAttribute("aria-controls",t),i.setAttribute("aria-expanded","false"),i.setAttribute("spellcheck","true"),i.setAttribute("enterkeyhint","send"),a.appendChild(i);let s=document.createElement("span");s.className="magicx-aia-pill-list-container",s.setAttribute("data-aia-pill-list-container",""),a.appendChild(s);let d=null,l=null;e.submitButton===void 0?(d=document.createElement("button"),d.type="button",d.className="magicx-aia-submit",d.setAttribute("aria-label","Submit"),d.setAttribute("data-aia-submit",""),d.innerHTML=xn,r.appendChild(d),l=d):e.submitButton!==null&&(l=e.submitButton,l.hasAttribute("data-aia-submit")||l.setAttribute("data-aia-submit",""),r.appendChild(l));let p=new AbortController,{signal:u}=p,c=!1,h=0,b=()=>{let m=ae(i),w=m.length>0&&m[0]!==m[0].toUpperCase()?m[0].toUpperCase()+m.slice(1):m;e.handleChange(w)},v=()=>{let m=(i.ownerDocument??document).getSelection();if(!m||m.rangeCount===0)return null;let g=m.anchorNode;return!g||!i.contains(g)?null:(g.nodeType===Node.ELEMENT_NODE?g:g.parentElement)?.closest('strong[data-seg="completed"][data-param-id]')?.dataset.paramId??null};r.addEventListener("click",m=>{m.target?.closest("[data-aia-pill]")||i.focus()},{signal:u}),i.addEventListener("input",()=>{c||(h=performance.now(),b(),e.handleCaretAfterInput(F(i)))},{signal:u});let f=i.ownerDocument??document;return f.addEventListener("selectionchange",()=>{let m=f.getSelection();if(!m||m.rangeCount===0||!i.contains(m.anchorNode))return;let g=v(),w=e.store.get().editingParam?.id??null;if(g&&g!==w){e.startEditingParam(g);return}performance.now()-h<50||e.handleCaretMove(F(i))},{signal:u}),i.addEventListener("compositionstart",()=>{c=!0},{signal:u}),i.addEventListener("compositionend",()=>{c=!1,b()},{signal:u}),i.addEventListener("beforeinput",m=>{let g=m,w=g.inputType;if(w==="insertParagraph"||w==="insertLineBreak"||w==="insertFromDrop"){m.preventDefault();return}if(w.startsWith("insert")||w.startsWith("delete")){let T=w.startsWith("delete")?"":g.data??"";e.replaceEditingRange(T)&&m.preventDefault()}},{signal:u}),i.addEventListener("paste",m=>{m.preventDefault();let g=(m.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!g)return;let w=i.ownerDocument??document,T=w.getSelection();if(!T||T.rangeCount===0)return;let O=T.getRangeAt(0);if(!i.contains(O.startContainer))return;O.deleteContents();let U=w.createTextNode(g);O.insertNode(U),O.setStartAfter(U),O.collapse(!0),T.removeAllRanges(),T.addRange(O),b()},{signal:u}),i.addEventListener("keydown",m=>e.handleKeyDown(m),{signal:u}),i.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:u}),i.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:u}),l&&l.addEventListener("click",m=>{let g=e.store.get();if(!(!!g.text||g.completedParams.length>0)||!e.onSubmit)return;m.stopPropagation();let{rawQuery:T,completedParams:O}=H(g.text,g.completedParams);e.onSubmit({query:g.text.trim(),raw_query:T,completed_params:O}),e.afterSubmit?.()},{signal:u}),e.autoFocus!==!1&&i.focus(),{input:i,inlinePillContainer:s,dropdown:o,submitButton:d,abort:p}}function mt(n,e,t){let{input:o,inlinePillContainer:r,dropdown:a,submitButton:i}=n,{pillPlacement:s,setActivePill:d,selectOption:l,store:p}=t;o.setAttribute("aria-expanded",String(e.isDropdownOpen));let u=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(u?o.setAttribute("aria-activedescendant",u):o.removeAttribute("aria-activedescendant"),i){let f=!!e.text||e.completedParams.length>0;i.disabled=!f}let c=o.dataset.newParamId??"",h=e.newParamId!==null&&e.newParamId!==c;if(Ke({input:o,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused}),s==="inline"){let f=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;f||e.actionableSuggestions.length>0?Ve(r,e.actionableSuggestions,0,d,!1,f):pt(r)}else pt(r);h?(o.focus(),M(o,e.caretOffset??e.text.length)):e.isFocused&&ae(o)!==e.text&&M(o,e.text.length);let b=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:null,v=b??e.actionableSuggestions[0];Je(a,{suggestions:v?[{...v,options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation,listboxId:t.listboxId,pills:b?[b]:e.actionableSuggestions,showPills:s==="dropdown",onSelect:l,onHighlight:f=>p.set({activeDropdownIndex:f}),onPillClick:d})}function Ht(n){let e=n,t=new Set;return{get:()=>e,set:o=>{let r=typeof o=="function"?o(e):o,a={...e,...r},i=e;e=a;for(let s of t)s(a,i)},subscribe:o=>(t.add(o),()=>{t.delete(o)})}}var gt=!1;function Bt(){if(gt||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){gt=!0;return}gt=!0;let n=document.createElement("style");n.setAttribute("data-magicx-aia",""),n.textContent=yn,document.head.appendChild(n)}var yn="";var wn=0;function Sn(){return`:ac-${++wn}:`}var Ft=500;function Kt(){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,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:null,inSelectionAnimation:!1}}var Ye=class{constructor(e,t={}){this.store=Ht(Kt());this._listboxId=Sn();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 je(this.store,{onPillSelected:({rawQuery:o,selectedPill:r,otherPills:a})=>{this.fireTelemetry("pill",{raw_query:o,selected_pill:r,other_pills:a})}}),this.fetchController=new Ge(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.opts.onError,()=>this.sessionId,{onAutoMatch:({active:o,matched:r,rawQuery:a})=>{this.fireTelemetry("option",{raw_query:a,selected_option:r.text,other_options:(o.options??[]).filter(i=>i.text!==r.text).map(i=>i.text)})}}),this.keyboardController=new Qe(this.store,{columns:t.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.opts.onSubmit,afterSubmit:this.renderMode==="full"?()=>this.reset():void 0,selectOption:o=>this.selectOption(o),removeParamAtCaret:o=>this.removeParamAtCaret(o),exitEditMode:()=>this.exitEditMode()}),this.unsubscribers.push(this.store.subscribe((o,r)=>{this.recomputeDerived(o,r)})),this.unsubscribers.push(this.store.subscribe((o,r)=>{o.text!==r.text&&this.opts.onChange?.(o.text),o.completedParams!==r.completedParams&&this.opts.onParamsChange?.(o.completedParams),o.isFocused!==r.isFocused&&(o.isFocused?this.opts.onFocus?.():this.opts.onBlur?.()),this.opts.onStateChange?.(o)})),this.renderMode!=="headless"&&(Bt(),this.setupContainer()),this.renderMode==="full"?this.buildAndRenderFull():this.renderMode==="dropdown"&&this.buildAndRenderDropdown(),this.fetchController.start()}focus(){this.domRefs?.input.focus()}blur(){this.domRefs?.input.blur()}reset(){this.store.set({...Kt(),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.selectionAnimationTimer&&clearTimeout(this.selectionAnimationTimer),this.externalListeners.clear();for(let e of this.unsubscribers)e();this.unsubscribers=[],this.domRefs?.abort.abort(),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()}removeParamAtCaret(e){let t=this.store.get(),{text:o,completedParams:r}=t,a=0;for(let i=0;i<r.length;i++){let s=r[i],d=o.indexOf(s.text,a);if(d===-1)continue;let l=d,p=d+s.text.length;if(e>l&&e<=p){let u=St(o,e),c=o.slice(0,u)+o.slice(e),h=r.filter((b,v)=>v!==i);return this.store.set(b=>({text:c,filterBase:Math.min(b.filterBase,c.length),completedParams:h,pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(u),!0}a=p}return!1}scheduleSetCursor(e){queueMicrotask(()=>{let t=this.domRefs;t?M(t.input,e):this.opts.setCursor?.(e)})}clearNewParamId(){this.store.set({newParamId:null})}startEditingParam(e){let t=this.store.get();if(t.editingParam?.id===e)return;let o=t.completedParams.find(i=>i.id===e);if(!o)return;let r=0,a=-1;for(let i of t.completedParams){let s=t.text.indexOf(i.text,r);if(s!==-1){if(i.id===e){a=s;break}r=s+i.text.length}}a<0||this.store.set({editingParam:o,editingAnchor:a,editingTail:a+o.text.length,caretOffset:a+o.text.length,activeDropdownIndex:-1})}replaceEditingRange(e){let t=this.store.get(),o=t.editingParam,r=t.editingAnchor,a=t.editingTail;if(!o||r==null||a==null||!t.completedParams.some(d=>d.id===o.id))return!1;let i=t.text.slice(0,r)+e+t.text.slice(a),s=r+e.length;return this.store.set(d=>({text:i,completedParams:d.completedParams.filter(l=>l.id!==o.id),editingTail:s,caretOffset:s,activeDropdownIndex:-1})),this.scheduleSetCursor(s),this.maybePromoteEditExactMatch(),!0}exitEditMode(){this.store.get().editingParam&&this.store.set({editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1})}handleCaretAfterInput(e){let t=this.store.get(),o={caretOffset:e};t.editingParam&&t.editingAnchor!=null&&e!=null&&(e<t.editingAnchor?(o.editingParam=null,o.editingAnchor=null,o.editingTail=null,o.activeDropdownIndex=-1):t.editingTail!=null&&(o.editingTail=Math.max(t.editingTail,e))),this.store.set(o),this.maybePromoteEditExactMatch()}handleCaretMove(e){let t=this.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null&&e!=null&&(e<t.editingAnchor||e>t.editingTail)){this.store.set({caretOffset:e,editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1});return}this.store.set({caretOffset:e})}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();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null){this.selectOptionInEditMode(e);return}let o=t.actionableSuggestions[0];if(!o)return;let{rawQuery:r}=H(t.text,t.completedParams);this.fireTelemetry("option",{raw_query:r,selected_option:e.text,other_options:t.filteredOptions.filter(m=>m.text!==e.text).map(m=>m.text)});let a=t.filterBase,i=t.text.slice(0,a),s=i.length===0&&t.text.length===0,d=i.length===0&&t.text.length>0&&t.placeholderText.length>0&&t.placeholderText.toLowerCase().startsWith(t.text.toLowerCase());(s||d)&&t.placeholderText&&(i=`${t.placeholderText} `);let l=Pt(i,e.text);l>0&&(i=i.slice(0,i.length-l));let p=i.length>0&&i[i.length-1]!==" ",u=`${i}${p?" ":""}${e.text} `,c=(s||d)&&u.length>0?u[0].toUpperCase()+u.slice(1):u,h=c.toLowerCase().lastIndexOf(e.text.toLowerCase()),b=h>=0?c.slice(h,h+e.text.length):e.text,v={id:crypto.randomUUID(),placeholder:"",type:o.type,text:b,kind:e.kind,suggestionType:o.type,suggestionPlaceholder:o.text,options:o.options??[],metadata:e.metadata},f=t.actionableSuggestions.length-1;this.store.set(m=>({text:c,filterBase:c.length,completedParams:[...m.completedParams,v],newParamId:v.id,caretOffset:c.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:f>0,inSelectionAnimation:!0})),this.startSelectionAnimationTimer(),this.suggestionRemovalTimer&&clearTimeout(this.suggestionRemovalTimer),f>0&&(this.suggestionRemovalTimer=window.setTimeout(()=>{this.store.set(m=>({suggestions:m.suggestions.filter(g=>g!==o)}))},Ft))}startSelectionAnimationTimer(){this.selectionAnimationTimer&&clearTimeout(this.selectionAnimationTimer),this.selectionAnimationTimer=window.setTimeout(()=>{this.store.set({inSelectionAnimation:!1})},Ft)}selectOptionInEditMode(e){let t=this.store.get(),o=t.editingParam,r=t.editingAnchor,a=t.editingTail;if(!o||r==null||a==null)return;this.fireTelemetry("option",{raw_query:H(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:o.options.filter(m=>m.text!==e.text).map(m=>m.text)});let i=t.text.slice(0,r),s=t.text.slice(a),d=r===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,l=s.length===0||s[0]!==" ",p=l?`${d} `:d,u=i+p+s,c=r+p.length+(l?0:1),h={id:crypto.randomUUID(),placeholder:"",type:o.suggestionType,text:d,kind:e.kind,suggestionType:o.suggestionType,suggestionPlaceholder:o.suggestionPlaceholder,options:o.options,metadata:e.metadata},b=t.completedParams.findIndex(m=>m.id===o.id),v=t.completedParams.filter(m=>m.id!==o.id),f=b>=0?Math.min(b,v.length):v.length;v.splice(f,0,h),this.store.set({text:u,completedParams:v,newParamId:h.id,filterBase:c,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:c,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.startSelectionAnimationTimer(),this.scheduleSetCursor(c)}fireTelemetry(e,t){let o=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");Tt({source:o,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}recomputeDerived(e,t){if(this.derivedInProgress)return;this.derivedInProgress=!0;let o=It(e.text,e.completedParams),r=e.suggestions.filter(g=>g.type!=="placeholder"),a=r[0],i=a?this.opts.optionOverrides?.[a.type]:void 0,s=e.suggestions.filter(g=>g.type==="placeholder").map(g=>g.text).join(" "),d=xe(e.text,Math.min(e.filterBase,e.text.length),s),p=e.lastRawQuery!==""||d>0?se(e.text,d,e.filterInProgress):"",u=a?i?i(p.trim()):a.options??[]:[],c=e.editingParam!=null&&e.editingAnchor!=null,h;if(c&&e.editingParam&&e.editingAnchor!=null){let g=e.editingParam.id,w=e.completedParams.some(U=>U.id===g),T=e.caretOffset??e.editingAnchor,O=w?"":e.text.slice(e.editingAnchor,T);h=ve(e.editingParam.options,O)}else h=ve(u,p);let b=this.opts.dropdownTrigger??"auto",v=this.opts.closeDropdownOnBlur??!0,f=!1;if(c){let g=v?e.isFocused:!0;f=h.length>0&&g}else if(b==="auto"){let g=v?e.isFocused:!0,w=e.text.replace(/\s+$/,"").length,T=e.caretOffset==null||e.caretOffset>=w;f=(h.length>0||e.isLoading)&&g&&T}else b==="manual"&&(f=(h.length>0||e.isLoading)&&e.pillTapped);this.store.set({segments:o,actionableSuggestions:r,filteredOptions:h,placeholderText:s,isDropdownOpen:f}),this.derivedInProgress=!1;let m=this.store.get();for(let g of this.externalListeners)g(m)}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 de(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:o=>this.selectOption(o),setActivePill:o=>this.pillsController.setActivePill(o),handleKeyDown:o=>this.keyboardController.handleKeyDown(o),handleChange:o=>this.handleChange(o),startEditingParam:o=>this.startEditingParam(o),handleCaretAfterInput:o=>this.handleCaretAfterInput(o),handleCaretMove:o=>this.handleCaretMove(o),replaceEditingRange:o=>this.replaceEditingRange(o)};this.domRefs=Nt(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&mt(this.domRefs,this.store.get(),t)}),mt(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=Rt(this.container,e),this.subscribeBatchedRender(()=>{this.dropdownRefs&&ut(this.dropdownRefs,this.store.get(),e)}),ut(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:o,invalid:r}=At(e,t.completedParams);r.length>0&&this.store.set({completedParams:o}),this.maybePromoteExactMatch(e)}maybePromoteExactMatch(e){let t=this.store.get(),r=t.suggestions.filter(g=>g.type!=="placeholder")[0];if(!r?.options)return;let a=t.suggestions.filter(g=>g.type==="placeholder").map(g=>g.text).join(" "),i=xe(e,t.filterBase,a),s=se(e,i,t.filterInProgress),d=le(r.options,s);if(!d)return;let l=d.text.toLowerCase(),p=e.toLowerCase().lastIndexOf(l),u=p>=0?p:Math.max(0,e.length-d.text.length),c=u+d.text.length,h=e.slice(u,c),b=e,f=c<e.length&&e[c]===" "?c+1:c,m={id:crypto.randomUUID(),placeholder:"",type:r.type,text:h,kind:d.kind,suggestionType:r.type,suggestionPlaceholder:r.text,options:r.options??[],metadata:d.metadata};this.store.set(g=>({text:b,completedParams:[...g.completedParams,m],suggestions:g.suggestions.filter(w=>w!==r),filterBase:f,newParamId:m.id,caretOffset:f,activeDropdownIndex:-1}))}maybePromoteEditExactMatch(){let e=this.store.get(),t=e.editingParam,o=e.editingAnchor,r=e.editingTail;if(!t||o==null||r==null||e.completedParams.some(w=>w.id===t.id))return;let a=e.text.slice(o,r),i=le(t.options,a);if(!i)return;let s=i.text.toLowerCase(),d=a.toLowerCase().lastIndexOf(s),l=o+Math.max(0,d),p=l+i.text.length,u=e.text.slice(l,p),c=e.text,b=p<e.text.length&&e.text[p]===" "?p+1:p,v={id:crypto.randomUUID(),placeholder:"",type:t.suggestionType,text:u,kind:i.kind,suggestionType:t.suggestionType,suggestionPlaceholder:t.suggestionPlaceholder,options:t.options,metadata:i.metadata},f=e.completedParams.length,m=0;for(let w=0;w<e.completedParams.length;w++){let T=c.indexOf(e.completedParams[w].text,m);if(T!==-1){if(T>=b){f=w;break}m=T+e.completedParams[w].text.length}}let g=[...e.completedParams];g.splice(f,0,v),this.store.set(()=>({text:c,completedParams:g,newParamId:v.id,filterBase:b,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:b,activeDropdownIndex:-1})),this.scheduleSetCursor(b)}};function Ze({onSubmit:n,onError:e,optionOverrides:t,maskCompletedText:o,apiConfig:r,columns:a=2,dropdownTrigger:i,closeDropdownOnBlur:s,onFocus:d,onBlur:l,value:p,completedParams:u,onChange:c,onParamsChange:h,source:b,setCursor:v}){let f=(0,P.useRef)(null),[m,g]=(0,P.useState)(null),w=(0,P.useRef)(n);w.current=n;let T=(0,P.useRef)(e);T.current=e;let O=(0,P.useRef)(c);O.current=c;let U=(0,P.useRef)(h);U.current=h;let ce=(0,P.useRef)(d);ce.current=d;let k=(0,P.useRef)(l);k.current=l;let pe=(0,P.useRef)(v);pe.current=v,(0,P.useEffect)(()=>{if(typeof document>"u")return;let S=new Ye(document.createElement("div"),{renderMode:"headless",apiConfig:r,optionOverrides:t,maskCompletedText:o,columns:a,dropdownTrigger:i,closeDropdownOnBlur:s,source:b,value:p,completedParams:u,onSubmit:(...D)=>w.current?.(...D),onError:(...D)=>T.current?.(...D),onChange:(...D)=>O.current?.(...D),onParamsChange:(...D)=>U.current?.(...D),onFocus:()=>ce.current?.(),onBlur:()=>k.current?.(),setCursor:D=>pe.current?.(D)});f.current=S,g(S.getState());let R=S.subscribe(D=>g(D));return()=>{R(),S.destroy(),f.current===S&&(f.current=null)}},[]);let x=f.current,_=(0,P.useCallback)(()=>{},[]);(0,P.useEffect)(()=>{p!==void 0&&x?.setValue(p)},[p,x]),(0,P.useEffect)(()=>{u!==void 0&&x?.setCompletedParams(u)},[u,x]);let we=JSON.stringify(r??null),te=(0,P.useRef)(t),ue=(0,P.useRef)(0);if(t!==te.current){let S=te.current,R=t,D=Object.keys(S??{}),G=Object.keys(R??{});(D.length!==G.length||G.some(Y=>!S?.[Y]||R[Y]!==S[Y]))&&ue.current++,te.current=t}(0,P.useEffect)(()=>{x?.update({apiConfig:r,optionOverrides:t,dropdownTrigger:i,closeDropdownOnBlur:s})},[we,ue.current,i,s,x]);let Se=(0,P.useCallback)(S=>{if(!x)return;let R=S.target.value,G=R.length>0&&!S.nativeEvent?.isComposing&&R[0]!==R[0].toUpperCase()?R[0].toUpperCase()+R.slice(1):R;x.handleTextChange(G)},[x]),tt=(0,P.useCallback)(S=>{x?.handleKeyDown(S.nativeEvent)},[x]),me=(0,P.useCallback)(()=>x?.setFocused(!0),[x]),Pe=(0,P.useCallback)(()=>x?.setFocused(!1),[x]),nt=(0,P.useCallback)(S=>x?.handleTextChange(S),[x]),ge=(0,P.useCallback)(S=>{if(!x)return;let R="nativeEvent"in S?S.nativeEvent:S;x.handleKeyDown(R)},[x]),j=(0,P.useCallback)(S=>x?.setFocused(S),[x]),Ie=(0,P.useCallback)(S=>x?.startEditingParam(S),[x]),Ae=(0,P.useCallback)(()=>x?.exitEditMode(),[x]),Ce=(0,P.useCallback)(S=>x?.handleCaretAfterInput(S),[x]),ot=(0,P.useCallback)(S=>x?.handleCaretMove(S),[x]),Te=(0,P.useCallback)(S=>x?.replaceEditingRange(S)??!1,[x]),fe=(0,P.useCallback)(S=>x?.setActivePill(S),[x]),_e=(0,P.useCallback)(()=>x?.removeLastParam(),[x]),Ee=(0,P.useCallback)(()=>x?.clearNewParamId(),[x]),ke=(0,P.useCallback)(()=>x?.reset(),[x]),ne=(0,P.useCallback)(S=>x?.selectOption(S),[x]),V=(0,P.useCallback)(S=>x?.setActiveDropdownIndex(S),[x]);if(!x)return{completedParams:u??[],suggestionPills:[],setActivePill:_,removeLastParam:_,segments:[],newParamId:null,clearNewParamId:_,suggestions:[],activeIndex:-1,isReady:!1,isLoading:!0,isFocused:!1,isDropdownOpen:!1,placeholderText:"",listboxId:"",error:null,handleTextChange:_,handleKeyDown:_,setFocused:_,editingParam:null,editingAnchor:null,caretOffset:null,startEditingParam:_,exitEditMode:_,handleCaretAfterInput:_,handleCaretMove:_,replaceEditingRange:()=>!1,inputProps:{value:p??"",placeholder:void 0,onChange:_,onKeyDown:_,onFocus:_,onBlur:_,role:"combobox","aria-expanded":!1,"aria-activedescendant":void 0,"aria-autocomplete":"list","aria-controls":""},reset:_,dropdownProps:{suggestions:[],activeIndex:-1,onSelect:_,onHighlight:_,isOpen:!1,id:"",pills:[],onPillClick:_}};let A=m??x.getState(),it=p!==void 0?p:A.text,Oe=u!==void 0?u:A.completedParams,oe=A.actionableSuggestions,De=oe[0],Le=A.filteredOptions,rt=A.activeDropdownIndex>=0?`${x.listboxId}-option-${A.activeDropdownIndex}`:void 0,K=A.editingParam,z=K?{type:K.suggestionType,text:K.suggestionPlaceholder,required:!0,options:K.options}:null,Me=z??De,at=z?[z]:oe;return{completedParams:Oe,suggestionPills:oe,setActivePill:fe,removeLastParam:_e,segments:A.segments,newParamId:A.newParamId,clearNewParamId:Ee,suggestions:A.suggestions,activeIndex:A.activeDropdownIndex,isReady:A.isReady,isLoading:A.isLoading&&!A.editingParam&&!A.inSelectionAnimation,isFocused:A.isFocused,isDropdownOpen:A.isDropdownOpen,placeholderText:A.placeholderText,listboxId:x.listboxId,error:A.error,handleTextChange:nt,handleKeyDown:ge,setFocused:j,editingParam:K,editingAnchor:A.editingAnchor,caretOffset:A.caretOffset,startEditingParam:Ie,exitEditMode:Ae,handleCaretAfterInput:Ce,handleCaretMove:ot,replaceEditingRange:Te,inputProps:{value:it,placeholder:A.placeholderText||void 0,onChange:Se,onKeyDown:tt,onFocus:me,onBlur:Pe,role:"combobox","aria-expanded":A.isDropdownOpen,"aria-activedescendant":rt,"aria-autocomplete":"list","aria-controls":x.listboxId},reset:ke,dropdownProps:{suggestions:Me?[{...Me,options:Le}]:[],activeIndex:A.activeDropdownIndex,onSelect:ne,onHighlight:V,isOpen:A.isDropdownOpen,id:x.listboxId,pills:at,onPillClick:fe,isLoading:A.isLoading&&!A.editingParam&&!A.inSelectionAnimation}}}var B=require("react/jsx-runtime");function Pn(n){return n!=="auto"?n:typeof window>"u"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}var et;function In(){if(et!==void 0)return et;if(typeof document>"u")return!1;let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),et=n.contentEditable==="plaintext-only",et}var zt=(0,I.forwardRef)(function({onSubmit:e,onError:t,optionOverrides:o,maskCompletedText:r,className:a,apiConfig:i,columns:s,pillPlacement:d="inline",mode:l="auto",optionsPosition:p="below",animations:u=!0,dropdownTrigger:c,closeDropdownOnBlur:h,autoFocus:b=!0,onFocus:v,onBlur:f,value:m,completedParams:g,onChange:w,onParamsChange:T,submitButton:O},U){let ce=(0,I.useRef)(null),k=(0,I.useRef)(null),pe=(0,I.useRef)(()=>{}),x=(0,I.useRef)(null),_=(0,I.useRef)(!1),we=(0,I.useRef)(""),te=(0,I.useRef)(""),ue=(0,I.useRef)(null),Se=(0,I.useRef)(0);(0,I.useEffect)(()=>{let y=ce.current;if(y)return x.current?x.current.setMode(l):x.current=new de(y,l),()=>{x.current?.destroy(),x.current=null}},[l]);let tt=(0,I.useCallback)(y=>{let C=k.current;C&&M(C,y)},[]),{completedParams:me,suggestionPills:Pe,setActivePill:nt,segments:ge,newParamId:j,clearNewParamId:Ie,placeholderText:Ae,isFocused:Ce,isDropdownOpen:ot,isLoading:Te,activeIndex:fe,listboxId:_e,handleTextChange:Ee,handleKeyDown:ke,setFocused:ne,editingParam:V,editingAnchor:A,caretOffset:it,startEditingParam:Oe,handleCaretAfterInput:oe,handleCaretMove:De,replaceEditingRange:Le,dropdownProps:rt,reset:K}=Ze({onSubmit:y=>pe.current(y),onError:t,optionOverrides:o,maskCompletedText:r,apiConfig:i,columns:s,dropdownTrigger:c,closeDropdownOnBlur:h,onFocus:v,onBlur:f,value:m,completedParams:g,onChange:w,onParamsChange:T,source:"full-sdk",setCursor:tt});ue.current=it,(0,I.useEffect)(()=>{if(!b)return;let y=k.current;y&&(document.activeElement===y?ne(!0):y.focus())},[b,ne]),(0,I.useEffect)(()=>{if(!j)return;let y=window.setTimeout(()=>Ie(),650);return()=>window.clearTimeout(y)},[j,Ie]),(0,I.useEffect)(()=>{let y=k.current;if(!y)return;let C=y.ownerDocument??document,E=()=>{let N=C.getSelection();if(!N||N.rangeCount===0||!N.anchorNode||!y.contains(N.anchorNode))return;let L=N.anchorNode,lt=(L.nodeType===Node.ELEMENT_NODE?L:L.parentElement)?.closest('strong[data-seg="completed"][data-param-id]')?.dataset.paramId??null;if(lt&&lt!==V?.id){Oe(lt);return}performance.now()-Se.current<50||De(F(y))};return C.addEventListener("selectionchange",E),()=>C.removeEventListener("selectionchange",E)},[V,Oe,De]),(0,I.useLayoutEffect)(()=>{let y=k.current;y&&Ke({input:y,segments:ge,newParamId:j,editingParamId:V?.id??null,placeholderText:Ae??"",isFocused:Ce})},[ge,j,V,Ae,Ce]),(0,I.useLayoutEffect)(()=>{let y=we.current,C=j??"";if(we.current=C,!C||C===y)return;let E=k.current;if(!E)return;E.focus();let N=ue.current??Fe(E);M(E,N)},[j]),(0,I.useLayoutEffect)(()=>{let y=te.current,C=V?.id??"";if(te.current=C,!C||C===y||A==null)return;let E=k.current;E&&M(E,A)},[V,A]),(0,I.useImperativeHandle)(U,()=>({focus:()=>k.current?.focus(),blur:()=>k.current?.blur(),reset:K,setMode:y=>x.current?.setMode(y)}),[K]);let z=(0,I.useCallback)(()=>{if(_.current)return;let y=k.current;if(!y)return;let C=ae(y),N=C.length>0&&C[0]!==C[0].toUpperCase()?C[0].toUpperCase()+C.slice(1):C;Ee(N)},[Ee]),Me=(0,I.useCallback)(()=>{Se.current=performance.now(),z();let y=k.current;y&&oe(F(y))},[z,oe]);(0,I.useEffect)(()=>{let y=k.current;if(!y)return;let C=E=>{let N=E,L=N.inputType;if(L==="insertParagraph"||L==="insertLineBreak"||L==="insertFromDrop"){E.preventDefault();return}if(L.startsWith("insert")||L.startsWith("delete")){let Q=L.startsWith("delete")?"":N.data??"";Le(Q)&&E.preventDefault()}};return y.addEventListener("beforeinput",C),()=>y.removeEventListener("beforeinput",C)},[Le]);let at=(0,I.useCallback)(()=>{_.current=!0},[]),S=(0,I.useCallback)(()=>{_.current=!1,z()},[z]),R=(0,I.useCallback)(y=>{y.preventDefault();let C=k.current;if(!C)return;let E=(y.clipboardData.getData("text/plain")??"").replace(/\r?\n/g," ");if(!E)return;let N=C.ownerDocument??document,L=N.getSelection();if(!L||L.rangeCount===0)return;let Q=L.getRangeAt(0);if(!C.contains(Q.startContainer))return;Q.deleteContents();let st=N.createTextNode(E);Q.insertNode(st),Q.setStartAfter(st),Q.collapse(!0),L.removeAllRanges(),L.addRange(Q),z()},[z]),D=(0,I.useCallback)(y=>ke(y),[ke]),G=!!ge.length||me.length>0,Y=(0,I.useCallback)(()=>{if(!G)return;let y=k.current?ae(k.current):"",{rawQuery:C,completedParams:E}=H(y,me);e({query:y.trim(),raw_query:C,completed_params:E}),K()},[G,me,e,K]);pe.current=Y;let Wt=(0,I.useCallback)(y=>{y.target?.closest("[data-aia-pill]")||k.current?.focus()},[]),$t=d==="inline",qt=d==="dropdown",Ut=fe>=0?`${_e}-option-${fe}`:void 0,Gt=In()?"plaintext-only":"true";return(0,B.jsxs)("div",{ref:ce,className:`magicx-aia ${X.container} ${a??""}`,"data-pill-placement":d,"data-options-position":p,"data-animations":u?"on":"off","data-mode":Pn(l),children:[(0,B.jsx)(Ne,{...rt,showPills:qt}),(0,B.jsxs)("div",{className:X.inputWrapper,onClick:Wt,children:[(0,B.jsxs)("div",{className:X.editorArea,"data-aia-editor":"",children:[(0,B.jsx)("div",{ref:k,className:X.input,"data-aia-input":"",contentEditable:Gt,suppressContentEditableWarning:!0,tabIndex:0,role:"combobox","aria-autocomplete":"list","aria-haspopup":"listbox","aria-controls":_e,"aria-expanded":ot,"aria-activedescendant":Ut,spellCheck:!0,enterKeyHint:"send",onInput:Me,onKeyDown:D,onCompositionStart:at,onCompositionEnd:S,onPaste:R,onFocus:()=>ne(!0),onBlur:()=>ne(!1)}),$t&&(Te||Pe.length>0)&&(0,B.jsx)("span",{className:X.pillListContainer,"data-aia-pill-list-container":"",children:(0,B.jsx)(be,{pills:Pe,activePillIndex:0,onSelectPill:nt,loading:Te})})]}),O===null?null:O===void 0?(0,B.jsx)("button",{type:"button","data-aia-submit":"",className:X.submitButton,disabled:!G,onClick:y=>{y.stopPropagation(),Y()},"aria-label":"Submit",children:(0,B.jsx)("svg",{width:"18",height:"18",viewBox:"0 0 18 18",fill:"none",role:"img","aria-label":"Submit",children:(0,B.jsx)("path",{d:"M9 14V4M9 4L4 9M9 4L14 9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}):(0,B.jsx)("span",{"data-aia-submit":"",className:X.submitSlot,onClick:y=>{G&&(y.stopPropagation(),Y())},children:O})]})]})});0&&(module.exports={AIAutocomplete,AIAutocompleteDropdown,useAIAutocomplete});
787
802
  //# sourceMappingURL=index.js.map