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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,6 +1,9 @@
1
- import{forwardRef as Tt,useCallback as Ot,useEffect as Re,useImperativeHandle as Et,useRef as he}from"react";if(typeof document<"u"&&!document.getElementById("ac-style-cc65f4cc")){let o=document.createElement("style");o.id="ac-style-cc65f4cc",o.textContent=`.AIAutocomplete-module_container_KKjFU {
1
+ import{forwardRef as Ln,useCallback as Q,useEffect as xe,useImperativeHandle as Mn,useLayoutEffect as ht,useRef as j}from"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
- font-family: "IBM Plex Sans", sans-serif;
3
+ /* Inherits the host page's font by default. Consumers can pin a specific
4
+ font on the library via \`--aia-font-family: 'Custom Font'\` without
5
+ affecting the surrounding page. */
6
+ font-family: var(--aia-font-family, inherit);
4
7
  container-type: inline-size;
5
8
  }
6
9
 
@@ -19,63 +22,77 @@ import{forwardRef as Tt,useCallback as Ot,useEffect as Re,useImperativeHandle as
19
22
  position: relative;
20
23
  flex: 1;
21
24
  min-width: 0;
22
- }
23
-
24
- .AIAutocomplete-module_sizerContent_DQgmV {
25
- position: relative;
26
- z-index: 1;
27
- pointer-events: none;
28
- white-space: pre-wrap;
29
- word-break: break-word;
25
+ min-height: 38px;
26
+ line-height: 38px;
30
27
  font-family: inherit;
31
28
  font-size: var(--aia-written-text-font-size, 19px);
32
- line-height: 38px;
33
- }
34
-
35
- .AIAutocomplete-module_sizerText_iZIMK {
36
- color: transparent;
29
+ white-space: pre-wrap;
30
+ word-break: break-word;
31
+ overflow-wrap: anywhere;
37
32
  }
38
33
 
39
- .AIAutocomplete-module_sizerTextVisible_HR-5h {
34
+ .AIAutocomplete-module_input_IW-P- {
35
+ display: inline;
36
+ outline: none;
37
+ background: transparent;
40
38
  color: var(--aia-written-text-color, var(--aia-color-text-default, #fff));
41
- font-size: var(--aia-written-text-font-size, inherit);
39
+ caret-color: var(
40
+ --aia-caret-color,
41
+ var(--aia-written-text-color, var(--aia-color-text-default, #fff))
42
+ );
43
+ font-weight: 200;
42
44
  }
43
45
 
44
- .AIAutocomplete-module_textareaHidden_UayJt {
45
- color: transparent !important;
46
+ /* Completed params render as inline bold runs. \`:where()\` keeps specificity
47
+ at (0,2,0) so consumers can override without \`!important\`. */
48
+ :where(.AIAutocomplete-module_input_IW-P-) strong {
49
+ font-weight: 500;
50
+ letter-spacing: -0.01em;
46
51
  }
47
52
 
48
- .AIAutocomplete-module_placeholderText_K3ayy {
49
- color: var(--aia-color-text-muted, #c1c4cb);
50
- opacity: 0.4;
53
+ /* Re-edit highlight \u2014 the editing class is written by the shared renderer
54
+ (a global string), so target it via an attribute selector to bypass
55
+ CSS Modules' class-name hashing. */
56
+ :where(.AIAutocomplete-module_input_IW-P-) strong[class~="magicx-aia-segment--editing"] {
57
+ outline: 1.5px solid var(--aia-edit-outline, currentColor);
58
+ outline-offset: 1px;
59
+ border-radius: 4px;
60
+ caret-color: transparent;
51
61
  }
52
62
 
53
- .AIAutocomplete-module_textarea_eyn6A {
54
- position: absolute;
55
- top: 0;
56
- left: 0;
57
- width: 100%;
58
- height: 100%;
59
- padding: 0;
60
- border: none;
63
+ :where(.AIAutocomplete-module_input_IW-P-) strong[class~="magicx-aia-segment--editing"]::selection {
61
64
  background: transparent;
62
- color: var(--aia-written-text-color, var(--aia-color-text-default, #fff));
63
- caret-color: var(
64
- --aia-caret-color,
65
- var(--aia-written-text-color, var(--aia-color-text-default, #fff))
66
- );
67
- font-family: inherit;
68
- font-size: var(--aia-written-text-font-size, 19px);
69
- line-height: 38px;
70
- white-space: pre-wrap;
71
- word-break: break-word;
72
- outline: none;
73
- resize: none;
74
- overflow: hidden;
65
+ color: inherit;
66
+ }
67
+ :where(.AIAutocomplete-module_input_IW-P-) strong[class~="magicx-aia-segment--editing"]::-moz-selection {
68
+ background: transparent;
69
+ color: inherit;
75
70
  }
76
71
 
77
- .AIAutocomplete-module_textarea_eyn6A::placeholder {
72
+ /* Placeholder via ::before so it doesn't enter the editable DOM. */
73
+ .AIAutocomplete-module_input_IW-P-[data-aia-empty="true"][data-placeholder]::before {
74
+ content: attr(data-placeholder);
78
75
  color: var(--aia-color-text-muted, #c1c4cb);
76
+ opacity: 0.7;
77
+ pointer-events: none;
78
+ }
79
+
80
+ /* Empty inline contentEditables have no inline box for the caret to render
81
+ in. Switch to inline-block (min-width matches the caret line) when empty,
82
+ so the caret stays visible while focused. */
83
+ .AIAutocomplete-module_input_IW-P-[data-aia-empty="true"] {
84
+ display: inline-block;
85
+ min-width: 1px;
86
+ vertical-align: top;
87
+ }
88
+
89
+ .AIAutocomplete-module_pillListContainer_h92IA {
90
+ display: inline;
91
+ margin-left: 8px;
92
+ }
93
+
94
+ .AIAutocomplete-module_pillListContainer_h92IA:empty {
95
+ margin-left: 0;
79
96
  }
80
97
 
81
98
  .AIAutocomplete-module_submitButton_sl1Mi {
@@ -102,18 +119,9 @@ import{forwardRef as Tt,useCallback as Ot,useEffect as Re,useImperativeHandle as
102
119
  display: contents;
103
120
  }
104
121
 
105
- /* Text shimmer on newly added completed param.
106
- The sizer sits above the textarea (z-index: 1). Normally sizer text is
107
- transparent and the textarea shows the real text. During the shimmer, we
108
- make this span visible with a moving gradient clipped to the text shape,
109
- so the shimmer renders on top of the textarea's static white text. */
110
-
111
- .AIAutocomplete-module_shimmer_13AnY {
112
- position: relative;
113
- z-index: 2;
114
- display: inline;
115
- }
116
-
122
+ /* Text shimmer on newly added completed param. The shimmer span wraps the
123
+ bold completion text inside the editor; a moving gradient clipped to the
124
+ text shape produces the sweep effect. */
117
125
  .AIAutocomplete-module_shimmerRevealed_RR8dp {
118
126
  color: transparent;
119
127
  background: linear-gradient(
@@ -142,11 +150,7 @@ import{forwardRef as Tt,useCallback as Ot,useEffect as Re,useImperativeHandle as
142
150
  background-position: -50% 0;
143
151
  }
144
152
  }
145
-
146
- .AIAutocomplete-module_shimmerHidden_45-Pf {
147
- color: transparent !important;
148
- }
149
- `,document.head.appendChild(o)}var _={container:"AIAutocomplete-module_container_KKjFU",inputWrapper:"AIAutocomplete-module_inputWrapper_FLq1b",editorArea:"AIAutocomplete-module_editorArea_7rBWq",sizerContent:"AIAutocomplete-module_sizerContent_DQgmV",sizerText:"AIAutocomplete-module_sizerText_iZIMK",sizerTextVisible:"AIAutocomplete-module_sizerTextVisible_HR-5h",textareaHidden:"AIAutocomplete-module_textareaHidden_UayJt",placeholderText:"AIAutocomplete-module_placeholderText_K3ayy",textarea:"AIAutocomplete-module_textarea_eyn6A",submitButton:"AIAutocomplete-module_submitButton_sl1Mi",submitSlot:"AIAutocomplete-module_submitSlot_GhuCM",shimmer:"AIAutocomplete-module_shimmer_13AnY",shimmerRevealed:"AIAutocomplete-module_shimmerRevealed_RR8dp",shimmerSweep:"AIAutocomplete-module_shimmerSweep_ARCon",textShimmer:"AIAutocomplete-module_textShimmer_eCLdq",shimmerHidden:"AIAutocomplete-module_shimmerHidden_45-Pf"};if(typeof document<"u"&&!document.getElementById("ac-style-2eef895d")){let o=document.createElement("style");o.id="ac-style-2eef895d",o.textContent=`.AIAutocompleteDropdown-module_dropdown_yz2KC {
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 {
150
154
  position: absolute;
151
155
  left: 0;
152
156
  right: 0;
@@ -184,7 +188,67 @@ import{forwardRef as Tt,useCallback as Ot,useEffect as Re,useImperativeHandle as
184
188
  .AIAutocompleteDropdown-module_pillBar_pwTXe {
185
189
  padding: 27px 27px 0px 27px;
186
190
  }
187
- `,document.head.appendChild(o)}var te={dropdown:"AIAutocompleteDropdown-module_dropdown_yz2KC",visible:"AIAutocompleteDropdown-module_visible_QCoXj",pillBar:"AIAutocompleteDropdown-module_pillBar_pwTXe"};if(typeof document<"u"&&!document.getElementById("ac-style-b745b4fb")){let o=document.createElement("style");o.id="ac-style-b745b4fb",o.textContent=`.PillList-module_list_qvLqO {
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
+
219
+ .AIAutocompleteDropdown-module_skeletonBars_HVr9C {
220
+ display: flex;
221
+ flex-direction: column;
222
+ gap: 20px;
223
+ }
224
+
225
+ .AIAutocompleteDropdown-module_skeletonBar_O3xIx {
226
+ display: block;
227
+ height: 19px;
228
+ border-radius: 999px;
229
+ background: var(--aia-skeleton-bg, var(--aia-pill-bg, rgba(189, 189, 189, 0.51)));
230
+ opacity: 0.5;
231
+ animation: AIAutocompleteDropdown-module_aiaSkeletonPulse_G8W7q 1.4s ease-in-out infinite;
232
+ }
233
+
234
+ .AIAutocompleteDropdown-module_skeletonBar_O3xIx:nth-child(2) {
235
+ animation-delay: 150ms;
236
+ }
237
+
238
+ .AIAutocompleteDropdown-module_skeletonBar_O3xIx:nth-child(3) {
239
+ animation-delay: 300ms;
240
+ }
241
+
242
+ @keyframes AIAutocompleteDropdown-module_aiaSkeletonPulse_G8W7q {
243
+ 0%,
244
+ 100% {
245
+ opacity: 0.5;
246
+ }
247
+ 50% {
248
+ opacity: 0.25;
249
+ }
250
+ }
251
+ `,document.head.appendChild(n)}var U={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 {
188
252
  position: relative;
189
253
  z-index: 1;
190
254
  pointer-events: auto;
@@ -210,7 +274,7 @@ import{forwardRef as Tt,useCallback as Ot,useEffect as Re,useImperativeHandle as
210
274
  transparent
211
275
  );
212
276
  color: var(--aia-pill-color, var(--aia-color-text-muted, #c1c4cb));
213
- font-family: "IBM Plex Sans", sans-serif;
277
+ font-family: inherit;
214
278
  font-size: var(--aia-pill-font-size, 19px);
215
279
  line-height: 30px;
216
280
  cursor: pointer;
@@ -234,6 +298,27 @@ import{forwardRef as Tt,useCallback as Ot,useEffect as Re,useImperativeHandle as
234
298
  border-radius: 999px;
235
299
  }
236
300
 
301
+ .PillList-module_skeleton_Lp8x6 {
302
+ pointer-events: none;
303
+ 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;
309
+ animation: PillList-module_skeletonPulse_xZ8Yf 1.4s ease-in-out infinite;
310
+ }
311
+
312
+ @keyframes PillList-module_skeletonPulse_xZ8Yf {
313
+ 0%,
314
+ 100% {
315
+ filter: brightness(1);
316
+ }
317
+ 50% {
318
+ filter: brightness(0.7);
319
+ }
320
+ }
321
+
237
322
  .PillList-module_pill_osSyz:hover {
238
323
  filter: brightness(1.2);
239
324
  }
@@ -247,7 +332,7 @@ import{forwardRef as Tt,useCallback as Ot,useEffect as Re,useImperativeHandle as
247
332
  opacity: 0;
248
333
  }
249
334
  }
250
- `,document.head.appendChild(o)}var V={list:"PillList-module_list_qvLqO",pill:"PillList-module_pill_osSyz",fadeIn:"PillList-module_fadeIn_Aezob",rounded:"PillList-module_rounded_WvXy4",active:"PillList-module_active_Oll--"};import{jsx as Me}from"react/jsx-runtime";function tt(o){return o===0?.4:o===1?.3:.15}function oe({pills:o,activePillIndex:e,onSelectPill:t,rounded:i}){return Me("span",{className:V.list,children:o.map((r,n)=>Me("button",{type:"button","data-aia-pill":"",className:`${V.pill} ${i?V.rounded:""} ${n===e?V.active:""}`,style:{opacity:tt(n)},onClick:()=>t(n),children:r.text},`${r.type}-${r.text}`))})}import{useEffect as nt,useLayoutEffect as st,useRef as at,useState as lt}from"react";if(typeof document<"u"&&!document.getElementById("ac-style-d91f2b06")){let o=document.createElement("style");o.id="ac-style-d91f2b06",o.textContent=`.SuggestionGrid-module_scrollWrapper_MOqfw {
335
+ `,document.head.appendChild(n)}var G={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--"};import{jsx as Le}from"react/jsx-runtime";var Jt=[125,69];function xt(n){return n===0?.4:n===1?.3:.15}function Me({pills:n,activePillIndex:e,onSelectPill:t,rounded:o,loading:r}){return r?Le("span",{className:G.list,"data-aia-pill-list-loading":"",children:Jt.map((a,i)=>Le("span",{"data-aia-pill-skeleton":"",className:`${G.pill} ${o?G.rounded:""} ${G.skeleton}`,style:{width:a,opacity:xt(i)}},`skel-${a}`))}):Le("span",{className:G.list,children:n.map((a,i)=>Le("button",{type:"button","data-aia-pill":"",tabIndex:-1,contentEditable:!1,suppressContentEditableWarning:!0,className:`${G.pill} ${o?G.rounded:""} ${i===e?G.active:""}`,style:{opacity:xt(i)},onMouseDown:s=>s.preventDefault(),onClick:()=>t(i),children:a.text},`${a.type}-${a.text}`))})}import{useEffect as tn,useLayoutEffect as nn,useRef as on,useState as rn}from"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 {
251
336
  position: relative;
252
337
  }
253
338
 
@@ -272,6 +357,9 @@ import{forwardRef as Tt,useCallback as Ot,useEffect as Re,useImperativeHandle as
272
357
  .SuggestionGrid-module_grid_jvaPb {
273
358
  display: grid;
274
359
  grid-template-columns: minmax(0, 250px);
360
+ /* Pack rows from the top instead of stretching to fill the grid container. */
361
+ grid-auto-rows: min-content;
362
+ align-content: start;
275
363
  max-width: 100cqi;
276
364
  padding: 8px 8px;
277
365
  max-height: 200px;
@@ -299,12 +387,14 @@ import{forwardRef as Tt,useCallback as Ot,useEffect as Re,useImperativeHandle as
299
387
  background: var(--aia-scrollbar-thumb, rgba(0, 0, 0, 0.3));
300
388
  border-radius: 3px;
301
389
  }
302
- `,document.head.appendChild(o)}var _e={scrollWrapper:"SuggestionGrid-module_scrollWrapper_MOqfw",grid:"SuggestionGrid-module_grid_jvaPb"};import{useEffect as ot,useRef as it,useState as rt}from"react";if(typeof document<"u"&&!document.getElementById("ac-style-f6bdc634")){let o=document.createElement("style");o.id="ac-style-f6bdc634",o.textContent=`.SuggestionItem-module_item_d4vpD {
390
+ `,document.head.appendChild(n)}var st={scrollWrapper:"SuggestionGrid-module_scrollWrapper_MOqfw",grid:"SuggestionGrid-module_grid_jvaPb"};import{useEffect as Yt,useRef as Zt,useState as en}from"react";if(typeof document<"u"&&!document.getElementById("ac-style-f6bdc634")){let n=document.createElement("style");n.id="ac-style-f6bdc634",n.textContent=`.SuggestionItem-module_item_d4vpD {
303
391
  position: relative;
304
392
  overflow: visible;
305
393
  display: flex;
306
- align-items: center;
307
- font-family: "IBM Plex Sans", sans-serif;
394
+ /* Top-align so single-line and multi-line options in the same row share
395
+ the same baseline at the top edge of the cell. */
396
+ align-items: flex-start;
397
+ font-family: inherit;
308
398
  font-size: var(--aia-option-font-size, 19px);
309
399
  line-height: 24px;
310
400
  color: var(--aia-option-color, var(--aia-color-text-muted, #c1c4cb));
@@ -610,7 +700,7 @@ import{forwardRef as Tt,useCallback as Ot,useEffect as Re,useImperativeHandle as
610
700
  box-shadow: 0 0 24px 10px rgba(var(--aia-streak-rgb, 255, 255, 255), 0.02);
611
701
  }
612
702
  }
613
- `,document.head.appendChild(o)}var O={item:"SuggestionItem-module_item_d4vpD",fadeIn:"SuggestionItem-module_fadeIn_I8u35",content:"SuggestionItem-module_content_T-Qba",tappable:"SuggestionItem-module_tappable_70KcX",nonTappable:"SuggestionItem-module_nonTappable_xSZM-",highlighted:"SuggestionItem-module_highlighted_Hb0SU",tag:"SuggestionItem-module_tag_e3Fwe",pressed:"SuggestionItem-module_pressed_98o-r",glassFade:"SuggestionItem-module_glassFade_oyiSj",tapDown:"SuggestionItem-module_tapDown_G3WGz",streaks:"SuggestionItem-module_streaks_d9PEB",streaksVert:"SuggestionItem-module_streaksVert_ERlV1",streakHorizRight:"SuggestionItem-module_streakHorizRight_aboGz",streakHorizLeft:"SuggestionItem-module_streakHorizLeft_BreWJ",streakVertUp:"SuggestionItem-module_streakVertUp_to1GD",streakVertDown:"SuggestionItem-module_streakVertDown_OrcLh"};import{jsx as Ce,jsxs as He}from"react/jsx-runtime";function Be({option:o,isHighlighted:e,onSelect:t,onHighlight:i,id:r}){let[n,s]=rt(!1),d=it(void 0);ot(()=>()=>clearTimeout(d.current),[]);let a=()=>{!o.is_tappable||n||(s(!0),t(o),clearTimeout(d.current),d.current=setTimeout(()=>s(!1),400))},l=[O.item,e?O.highlighted:"",o.is_tappable?O.tappable:O.nonTappable,n?O.pressed:""].filter(Boolean).join(" ");return He("div",{id:r,role:"option","data-aia-option":"","aria-selected":e,className:l,tabIndex:o.is_tappable?0:-1,onClick:a,onKeyDown:p=>{o.is_tappable&&(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),a())},onMouseEnter:o.is_tappable?i:void 0,children:[Ce("div",{className:O.streaks}),Ce("div",{className:O.streaksVert}),He("span",{className:O.content,children:[o.icon?`${o.icon} ${o.text}`:o.text,o.tag&&Ce("span",{className:O.tag,children:o.tag})]})]})}import{jsx as Ae}from"react/jsx-runtime";function ze({options:o,activeIndex:e,onSelect:t,onHighlight:i,listboxId:r}){let n=at(null),[s,d]=lt(!1);return nt(()=>{let a=n.current;if(!a)return;let l=()=>{d(a.scrollHeight-a.scrollTop-a.clientHeight>1)};a.addEventListener("scroll",l,{passive:!0});let p=new ResizeObserver(l);return p.observe(a),()=>{a.removeEventListener("scroll",l),p.disconnect()}},[]),st(()=>{let a=n.current;a&&d(a.scrollHeight-a.scrollTop-a.clientHeight>1)},[o]),Ae("div",{className:_e.scrollWrapper,"data-fade":s?"":void 0,children:Ae("div",{ref:n,className:_e.grid,children:o.map((a,l)=>Ae(Be,{option:a,isHighlighted:l===e,onSelect:t,onHighlight:()=>i(l),id:`${r}-option-${l}`},a.text))})})}import{jsx as Pe,jsxs as dt}from"react/jsx-runtime";function ke({suggestions:o,activeIndex:e,onSelect:t,onHighlight:i,isOpen:r,id:n,className:s,pills:d,onPillClick:a,showPills:l=!0}){let c=o[0]?.options??[],m=l&&d&&d.length>0&&a,x=r&&c.length>0||r&&m;return dt("div",{id:n,role:"listbox","data-aia-dropdown":"",className:`${te.dropdown} ${x?te.visible:""} ${s??""}`,onMouseDown:y=>y.preventDefault(),children:[m&&Pe("div",{className:te.pillBar,"data-aia-pillbar":"",children:Pe(oe,{pills:d,activePillIndex:0,onSelectPill:a,rounded:!0})}),c.length>0&&Pe(ze,{options:c,activeIndex:e,onSelect:t,onHighlight:i,listboxId:n})]})}if(typeof document<"u"&&!document.getElementById("ac-style-dc8da745")){let o=document.createElement("style");o.id="ac-style-dc8da745",o.textContent=`/*
703
+ `,document.head.appendChild(n)}var K={item:"SuggestionItem-module_item_d4vpD",fadeIn:"SuggestionItem-module_fadeIn_I8u35",content:"SuggestionItem-module_content_T-Qba",tappable:"SuggestionItem-module_tappable_70KcX",nonTappable:"SuggestionItem-module_nonTappable_xSZM-",highlighted:"SuggestionItem-module_highlighted_Hb0SU",tag:"SuggestionItem-module_tag_e3Fwe",pressed:"SuggestionItem-module_pressed_98o-r",glassFade:"SuggestionItem-module_glassFade_oyiSj",tapDown:"SuggestionItem-module_tapDown_G3WGz",streaks:"SuggestionItem-module_streaks_d9PEB",streaksVert:"SuggestionItem-module_streaksVert_ERlV1",streakHorizRight:"SuggestionItem-module_streakHorizRight_aboGz",streakHorizLeft:"SuggestionItem-module_streakHorizLeft_BreWJ",streakVertUp:"SuggestionItem-module_streakVertUp_to1GD",streakVertDown:"SuggestionItem-module_streakVertDown_OrcLh"};import{jsx as lt,jsxs as vt}from"react/jsx-runtime";function yt({option:n,isHighlighted:e,onSelect:t,onHighlight:o,id:r}){let[a,i]=en(!1),s=Zt(void 0);Yt(()=>()=>clearTimeout(s.current),[]);let l=()=>{!n.is_tappable||a||(i(!0),t(n),clearTimeout(s.current),s.current=setTimeout(()=>i(!1),400))},d=[K.item,e?K.highlighted:"",n.is_tappable?K.tappable:K.nonTappable,a?K.pressed:""].filter(Boolean).join(" ");return vt("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:[lt("div",{className:K.streaks}),lt("div",{className:K.streaksVert}),vt("span",{className:K.content,children:[n.icon?`${n.icon} ${n.text}`:n.text,n.tag&&lt("span",{className:K.tag,children:n.tag})]})]})}import{jsx as dt}from"react/jsx-runtime";function wt({options:n,activeIndex:e,onSelect:t,onHighlight:o,listboxId:r}){let a=on(null),[i,s]=rn(!1);return tn(()=>{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()}},[]),nn(()=>{let l=a.current;l&&s(l.scrollHeight-l.scrollTop-l.clientHeight>1)},[n]),dt("div",{className:st.scrollWrapper,"data-fade":i?"":void 0,children:dt("div",{ref:a,className:st.grid,children:n.map((l,d)=>dt(yt,{option:l,isHighlighted:d===e,onSelect:t,onHighlight:()=>o(d),id:`${r}-option-${d}`},l.text))})})}import{Fragment as ln,jsx as Y,jsxs as St}from"react/jsx-runtime";var an=[159,119,164],sn=[115,122];function ct({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 Y("div",{id:a,role:"listbox","data-aia-dropdown":"","data-aia-loading":c?"":void 0,className:`${U.dropdown} ${y?U.visible:""} ${i??""}`,onMouseDown:g=>g.preventDefault(),children:c?St("div",{className:U.skeleton,"data-aia-skeleton":"",children:[d&&Y("div",{className:U.skeletonPills,"data-aia-skeleton-pills":"",children:sn.map(g=>Y("span",{className:U.skeletonPill,style:{width:g}},`pill-${g}`))}),Y("div",{className:U.skeletonBars,children:an.map(g=>Y("span",{className:U.skeletonBar,style:{width:g}},`bar-${g}`))})]}):St(ln,{children:[x&&Y("div",{className:U.pillBar,"data-aia-pillbar":"",children:Y(Me,{pills:s,activePillIndex:0,onSelectPill:l,rounded:!0})}),u.length>0&&Y(wt,{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=`/*
614
704
  * Built-in appearance defaults \u2014 zero specificity via :where().
615
705
  * Consumer CSS always wins without !important.
616
706
  *
@@ -641,6 +731,8 @@ import{forwardRef as Tt,useCallback as Ot,useEffect as Re,useImperativeHandle as
641
731
 
642
732
  --aia-color-text-muted: #6b7280;
643
733
 
734
+ --aia-skeleton-bg: rgba(189, 189, 189, 0.51);
735
+
644
736
  --aia-streak-rgb: 99, 102, 241;
645
737
  --aia-streak-glass-bg: rgba(99, 102, 241, 0.1);
646
738
  }
@@ -665,6 +757,8 @@ import{forwardRef as Tt,useCallback as Ot,useEffect as Re,useImperativeHandle as
665
757
 
666
758
  --aia-color-text-muted: #c1c4cb;
667
759
 
760
+ --aia-skeleton-bg: #333539;
761
+
668
762
  --aia-streak-rgb: 255, 255, 255;
669
763
  --aia-streak-glass-bg: rgba(255, 255, 255, 0.1);
670
764
  }
@@ -689,5 +783,5 @@ import{forwardRef as Tt,useCallback as Ot,useEffect as Re,useImperativeHandle as
689
783
  animation-duration: 0s !important;
690
784
  transition-duration: 0s !important;
691
785
  }
692
- `,document.head.appendChild(o)}import{useCallback as P,useEffect as fe,useRef as E,useState as kt}from"react";function A(o,e){let t=o,i={},r=[];for(let n of e){let s=(i[n.type]??0)+1;i[n.type]=s;let a=`{{${n.type.toUpperCase().replace(/\s+/g,"_")}_${s}}}`,l=t.indexOf(n.text);l!==-1&&(t=t.slice(0,l)+a+t.slice(l+n.text.length)),r.push({...n,placeholder:a})}return{rawQuery:t,completedParams:r}}function Q(o,e,t){let i=o.slice(e);if(t||e===0||o[e-1]===" ")return i;let r=i.indexOf(" ");return r===-1?"":i.slice(r+1)}function Fe(o,e){let t=o.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let i=t.split(" "),r=e.toLowerCase();for(let n=0;n<i.length;n++){let s=i.slice(n).join(" ");if(r.startsWith(s.toLowerCase())){let d=t.length-s.length;return o.length-d}}return 0}function ie(o,e){if(!o)return[];let t=e.trimStart();if(!t)return o;let i=t.toLowerCase();return o.filter(r=>!r.is_tappable||r.text.toLowerCase().includes(i))}function Te(o,e){if(!o)return null;let t=e.trim();if(!t)return null;let i=t.toLowerCase();return o.find(r=>r.is_tappable&&r.text.toLowerCase()===i)??null}var K=class{constructor(e,t="auto"){this.container=e;this.mode=t;this.mediaQuery=null;this.onSystemChange=e=>{this.container.dataset.mode=e.matches?"dark":"light"};this.apply()}setMode(e){this.detachListener(),this.mode=e,this.apply()}destroy(){this.detachListener()}apply(){this.mode==="auto"?(this.mediaQuery??(this.mediaQuery=window.matchMedia("(prefers-color-scheme: dark)")),this.mediaQuery.addEventListener("change",this.onSystemChange),this.container.dataset.mode=this.mediaQuery.matches?"dark":"light"):this.container.dataset.mode=this.mode}detachListener(){this.mediaQuery?.removeEventListener("change",this.onSystemChange)}};function Ne(o,e){let t=[],i=0;for(let n of e){let s=o.indexOf(n.text,i);s!==-1&&(s>i&&t.push({type:"text",value:o.slice(i,s)}),t.push({type:"completed",value:n.text,param:n}),i=s+n.text.length)}let r=o.slice(i);return r&&t.push({type:"text",value:r}),t}function Ke(o,e){let t=[],i=[],r=0;for(let n of e){let s=o.indexOf(n.text,r);s===-1?i.push(n):(t.push(n),r=s+n.text.length)}return{valid:t,invalid:i}}var re=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;this.inFlightRefresh=null;e.accessToken&&(this.current=e.accessToken)}async getToken(e=!1){if(!e&&this.current&&!this.isExpired())return this.current;if(!e&&this.inFlightRefresh)return this.inFlightRefresh;this.inFlightRefresh=this.refresh();try{return await this.inFlightRefresh}finally{this.inFlightRefresh=null}}async refresh(){let e=await this.config.getAccessToken();return this.current=e.accessToken,this.expiresAt=e.expiresAt??null,this.current}isExpired(){return this.expiresAt==null?!1:Date.now()>=this.expiresAt-3e4}};var $e=new WeakMap;function G(o){return o?.type==="accessToken"}function pt(o){if(!(!o||G(o)))return o}function ne(o){let e=$e.get(o.getAccessToken);return e||(e=new re(o),$e.set(o.getAccessToken,e)),e}function se(o){return{"Content-Type":"application/json",...o?.appIdentifier&&{"X-App-Identifier":o.appIdentifier},...o?.headers}}function ae(o){let e=pt(o),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}var ct="https://api.ai-autocomplete.com/api/suggest",qe="/api/telemetry/events";function ut(o){let e=o??ct;try{return`${new URL(e).origin}${qe}`}catch{return`https://api.ai-autocomplete.com${qe}`}}async function mt(o){return G(o)?`Bearer ${await ne(o).getToken()}`:ae(o)}async function Ue(o){try{let e=ut(o.apiConfig?.endpoint),t=se(o.apiConfig),i=await mt(o.apiConfig);i&&(t.Authorization=i);let r=JSON.stringify({source:o.source,session_id:o.sessionId,type:o.type,at:new Date().toISOString(),query_data:o.queryData});await fetch(e,{method:"POST",headers:t,body:r})}catch{}}var gt="0.1.37",Ve=!1;function ft(){return crypto.randomUUID()}function ht(o,e){return{placeholder:o.placeholder,type:o.type,...e&&{text:o.text},kind:o.kind}}function xt(o,e,t,i){let r=e.find(s=>s.type==="contact"&&s.metadata?.contact_account_count)?.metadata?.contact_account_count,n=typeof r=="number"?r:void 0;return{data:{raw_query:o,completed_params:e.map(s=>ht(s,t)),...n!=null&&{contact_account_count:n}},meta:{request_id:ft(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:gt,session_id:i}}}async function Qe(o,e,t,i,r){return fetch(o,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:r})}async function Ge(o,e,t){let i=t.apiConfig,r=!t.maskCompletedText,n=xt(o,e,r,t.sessionId),s=se(i),d=i?.endpoint??"https://api.ai-autocomplete.com/api/suggest",a=JSON.stringify(n);if(G(i)){let c=ne(i),m=await c.getToken(),g=await Qe(d,s,m,a,t.signal);if(g.status===401){let x=await c.getToken(!0);g=await Qe(d,s,x,a,t.signal)}if(!g.ok)throw new Error(`API error: ${g.status} ${g.statusText}`);return g.json()}let l=ae(i);!l&&!Ve&&(Ve=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),l&&(s.Authorization=l);let p=await fetch(d,{method:"POST",headers:s,body:a,signal:t.signal});if(!p.ok)throw new Error(`API error: ${p.status} ${p.statusText}`);return p.json()}function We(o,e){return e?o.map(t=>{let i=e[t.type];if(!i)return t;let r=i("");if(r.length===0)return t;let n=new Set(r.map(d=>d.text)),s=(t.options??[]).filter(d=>!n.has(d.text));return{...t,options:[...r,...s]}}):o}var bt=100,vt=300,yt=2,le=class{constructor(e,t,i,r,n,s,d={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=r;this.getOnError=n;this.getSessionId=s;this.callbacks=d;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null}start(){this.doFetch("",[]);let e=this.store.get().text,t=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(i=>{(i.text!==e||i.completedParams!==t)&&(e=i.text,t=i.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let i=new AbortController;this.abortController=i;let r=++this.fetchVersion,n=this.store.get(),s=n.text.length;n.suggestions.some(a=>a.type!=="placeholder")||this.store.set({isLoading:!0}),this.store.set({error:null});try{let a=await Ge(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig()});if(r!==this.fetchVersion)return;let l=We(a.data.suggestions??[],this.getOptionOverrides()),p=a.data.input??[],c=p[p.length-1],m=this.store.get().text,g,x;if(c?.state==="in_progress"){x=!0;let S=m.toLowerCase().lastIndexOf(c.text.toLowerCase());g=S!==-1?S:s}else x=!1,g=s;let b=l.filter(S=>S.type!=="placeholder")[0],h=null;if(b){let S=Q(m,g,x),k=Te(b.options,S);k&&(h={id:crypto.randomUUID(),placeholder:"",type:b.type,text:k.text,kind:k.kind,suggestionType:b.type,suggestionPlaceholder:b.text,options:b.options??[],metadata:k.metadata},l=l.filter(H=>H!==b),this.callbacks.onAutoMatch?.({active:b,matched:k,rawQuery:e}))}this.store.set(S=>({suggestions:l,isLoading:!1,isReady:a.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:g,filterInProgress:x,...h?{completedParams:[...S.completedParams,h]}:{}}))}catch(a){if(r===this.fetchVersion){let l=a instanceof Error?a:new Error(String(a));this.store.set({error:l,isLoading:!1}),this.getOnError()?.(l)}}}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}let t=i=>{let r=this.store.get();if(!r.text&&r.completedParams.length===0)return this.doFetch("",[]),!0;let n=Q(r.text,r.filterBase,r.filterInProgress),d=r.suggestions.filter(b=>b.type!=="placeholder")[0],l=(d?ie(d.options,n):[]).filter(b=>b.is_tappable),p=d?Te(d.options,n)!==null:!1,c=n.trim().length>0;if(l.length>0&&!p&&c)return!1;if(r.completedParams.length===0&&r.text.length>0){let b=r.suggestions.filter(h=>h.type==="placeholder").map(h=>h.text).join(" ");if(b.length>0&&b.toLowerCase().startsWith(r.text.toLowerCase()))return!1}let{rawQuery:m,completedParams:g}=A(r.text,r.completedParams),x=m.length<r.lastRawQuery.length,y=Math.abs(m.length-r.lastRawQuery.length);return x||y>=i?(this.doFetch(m,g),!0):!1};this.debounceTimer=setTimeout(()=>{t(yt)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},bt),this.slowDebounceTimer=setTimeout(()=>t(1),vt)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var de=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:r}=this.ctx,n=this.getEffectiveColumns(),s=r(),d=this.getTappableIndices(n);switch(e.key){case"ArrowDown":{let a=e.target;if(!(a.selectionStart!=null&&a.selectionStart===a.value.length)&&t.activeDropdownIndex<0)break;if(e.preventDefault(),!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:d[0]??0});break}if(d.length===0)return;let p=d.indexOf(t.activeDropdownIndex),c=p<d.length-1?p+1:0;this.store.set({activeDropdownIndex:d[c]});break}case"ArrowUp":{if(d.length===0||t.activeDropdownIndex<0)break;if(e.preventDefault(),t.activeDropdownIndex<n){this.store.set({activeDropdownIndex:-1});break}let a=d.indexOf(t.activeDropdownIndex),l=a>0?a-1:d.length-1;this.store.set({activeDropdownIndex:d[l]});break}case"ArrowRight":{if(t.activeDropdownIndex<0){let l=e.target;l.selectionStart!=null&&l.selectionStart===l.value.length&&t.actionableSuggestions.length>1&&(e.preventDefault(),this.pillsSetActivePill(1));break}if(t.activeDropdownIndex%n<n-1){let l=t.activeDropdownIndex+1;l<t.filteredOptions.length&&t.filteredOptions[l]?.is_tappable&&(e.preventDefault(),this.store.set({activeDropdownIndex:l}))}break}case"ArrowLeft":{if(t.activeDropdownIndex<0)break;if(t.activeDropdownIndex%n>0){let a=t.activeDropdownIndex-1;a>=0&&t.filteredOptions[a]?.is_tappable&&(e.preventDefault(),this.store.set({activeDropdownIndex:a}))}break}case"Enter":{if(e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable)this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i);else if(s){let{rawQuery:a,completedParams:l}=A(t.text,t.completedParams);s({query:t.text.trim(),raw_query:a,completed_params:l}),this.ctx.afterSubmit?.()}break}case"Tab":{let a=!t.text&&!!t.placeholderText,l=t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable;if(a&&!l){e.preventDefault();let p=t.suggestions.find(c=>c.type==="placeholder");p?this.store.set(c=>({text:t.placeholderText,filterBase:t.placeholderText.length,completedParams:[...c.completedParams,{id:crypto.randomUUID(),placeholder:"",type:p.type,text:t.placeholderText,kind:null,suggestionType:p.type,suggestionPlaceholder:p.text,options:p.options??[]}],suggestions:c.suggestions.filter(m=>m!==p)})):this.store.set({text:t.placeholderText,filterBase:t.placeholderText.length})}else if(l)e.preventDefault(),this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i);else if(t.isDropdownOpen){let p=t.filteredOptions.findIndex(c=>c.is_tappable);p>=0&&(e.preventDefault(),this.clickOrSelect(p,t.filteredOptions,i))}break}case"Escape":this.store.set({activeDropdownIndex:-1});break}}getTappableIndices(e){let i=this.store.get().filteredOptions.map((n,s)=>n.is_tappable?s:-1).filter(n=>n!==-1),r=Array.from({length:e},()=>[]);for(let n of i)r[n%e].push(n);return r.flat()}getEffectiveColumns(){let t=document.getElementById(`${this.ctx.listboxId}-option-0`)?.parentElement;if(!t)return this.ctx.columns;let i=getComputedStyle(t).gridTemplateColumns.split(" ").filter(Boolean).length;return i>0?i:this.ctx.columns}clickOrSelect(e,t,i){let r=document.getElementById(`${i}-option-${e}`);r?r.click():this.ctx.selectOption(t[e])}pillsSetActivePill(e){let t=this.store.get(),i=t.suggestions.filter(d=>d.type!=="placeholder");if(e<0||e>=i.length)return;let r=i[e],n=i.filter((d,a)=>a!==e),s=t.suggestions.filter(d=>d.type==="placeholder");this.store.set({suggestions:[...s,r,...n],pillTapped:!0,activeDropdownIndex:-1})}};var pe=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),i=t.suggestions.filter(d=>d.type!=="placeholder");if(e<0||e>=i.length)return;let r=i[e],n=i.filter((d,a)=>a!==e),s=t.suggestions.filter(d=>d.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:d}=A(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:d,selectedPill:r.text,otherPills:n.map(a=>a.text)})}this.store.set({suggestions:[...s,r,...n],pillTapped:!0,activeDropdownIndex:-1})}removeLastParam(){let e=this.store.get();if(e.completedParams.length===0)return;let t=e.completedParams[e.completedParams.length-1],i={type:t.suggestionType,text:t.suggestionPlaceholder,required:!0,options:t.options};this.store.set(r=>({completedParams:r.completedParams.slice(0,-1),suggestions:[i,...r.suggestions],activeDropdownIndex:-1}))}};function wt(o){return o===0?.4:o===1?.3:.15}function ce(o,e,t,i,r=!1){let n=o.querySelector(".magicx-aia-pill-list");n||(n=document.createElement("span"),n.className="magicx-aia-pill-list",o.appendChild(n));let s=new Map;for(let a of n.querySelectorAll(".magicx-aia-pill"))s.set(a.dataset.pillKey??"",a);let d=new Set;for(let a=0;a<e.length;a++){let l=e[a],p=`${l.type}-${l.text}`;d.add(p);let c=s.get(p);c||(c=document.createElement("button"),c.type="button",c.dataset.pillKey=p,c.setAttribute("data-aia-pill",""),c.textContent=l.text),c.className=`magicx-aia-pill${r?" magicx-aia-pill--rounded":""}${a===t?" magicx-aia-pill--active":""}`,c.style.opacity=String(wt(a)),c.onclick=()=>i(a),n.children[a]!==c&&n.insertBefore(c,n.children[a]??null)}for(let[a,l]of s)d.has(a)||l.remove()}function ue(o){let e=document.createElement("div");return e.id=o,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",t=>t.preventDefault()),e}function me(o,e){let{filteredOptions:t,activeIndex:i,isOpen:r,pills:n,showPills:s,onSelect:d,onHighlight:a,onPillClick:l}=e,p=s&&n.length>0;r&&t.length>0||r&&p?o.classList.add("magicx-aia-dropdown--visible"):o.classList.remove("magicx-aia-dropdown--visible");let g=o.querySelector(".magicx-aia-pill-bar");p?(g||(g=document.createElement("div"),g.className="magicx-aia-pill-bar",g.setAttribute("data-aia-pillbar",""),o.insertBefore(g,o.firstChild)),ce(g,n,0,l,!0)):g&&g.remove();let x=o.querySelector(".magicx-aia-grid");t.length>0?(x||(x=document.createElement("div"),x.className="magicx-aia-grid",o.appendChild(x)),St(x,t,i,d,a,e.listboxId)):x&&(x.innerHTML="")}function St(o,e,t,i,r,n){let s=e.map(l=>l.text).join("\0"),d=o.dataset.optionsKey??"",a=s!==d;if(o.dataset.optionsKey=s,a){let l=document.createDocumentFragment();for(let p=0;p<e.length;p++){let c=e[p],m=It(c,p,t,i,r,n);l.appendChild(m)}o.innerHTML="",o.appendChild(l)}else{let l=o.querySelectorAll(".magicx-aia-option");for(let p=0;p<l.length;p++){let c=l[p],m=p===t;c.setAttribute("aria-selected",String(m)),m?c.classList.add("magicx-aia-option--highlighted"):c.classList.remove("magicx-aia-option--highlighted")}}}function It(o,e,t,i,r,n){let s=document.createElement("div");s.id=`${n}-option-${e}`,s.setAttribute("role","option"),s.setAttribute("data-aia-option",""),s.setAttribute("aria-selected",String(e===t)),s.tabIndex=o.is_tappable?0:-1;let d=["magicx-aia-option"];e===t&&d.push("magicx-aia-option--highlighted"),o.is_tappable?d.push("magicx-aia-option--tappable"):d.push("magicx-aia-option--non-tappable"),s.className=d.join(" ");let a=document.createElement("div");a.className="magicx-aia-streaks",s.appendChild(a);let l=document.createElement("div");l.className="magicx-aia-streaks-vert",s.appendChild(l);let p=document.createElement("span");if(p.className="magicx-aia-option-content",p.textContent=o.icon?`${o.icon} ${o.text}`:o.text,o.tag){let c=document.createElement("span");c.className="magicx-aia-option-tag",c.textContent=o.tag,p.appendChild(c)}return s.appendChild(p),o.is_tappable&&(s.addEventListener("click",()=>{s.classList.add("magicx-aia-option--pressed"),i(o),setTimeout(()=>s.classList.remove("magicx-aia-option--pressed"),400)}),s.addEventListener("mouseenter",()=>r(e))),s}function je(o,e){let t=ue(e.listboxId);return o.appendChild(t),{dropdown:t}}function Oe(o,e,t){me(o.dropdown,{suggestions:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,onSelect:t.selectOption,onHighlight:i=>t.store.set({activeDropdownIndex:i}),onPillClick:t.setActivePill})}function Xe(o,e,t,i,r){let n=o.querySelector(".magicx-aia-sizer-text"),s=o.querySelector(".magicx-aia-placeholder");if(i&&r){n&&(n.style.display="none"),s||(s=document.createElement("span"),s.className="magicx-aia-placeholder",o.insertBefore(s,o.firstChild)),s.style.display="",s.textContent=`${r} `,o.dataset.segmentKey="";return}s&&(s.style.display="none"),n||(n=document.createElement("span"),n.className="magicx-aia-sizer-text",o.insertBefore(n,o.firstChild)),n.style.display="",n.className=`magicx-aia-sizer-text${t?" magicx-aia-sizer-text--visible":""}`;let d=e.map(p=>`${p.type}:${p.value}`).join("\0"),a=o.dataset.segmentKey??"",l=o.dataset.newParamId??"";if(!(d===a&&(t??"")===l)){o.dataset.segmentKey=d,o.dataset.newParamId=t??"",n.innerHTML="";for(let p of e){let c=document.createElement("span");p.type==="completed"&&(p.param.id===t?c.className="magicx-aia-shimmer-revealed magicx-aia-shimmer-sweep":c.className="magicx-aia-segment magicx-aia-segment--completed"),c.textContent=p.value,n.appendChild(c)}e.length===0&&(n.textContent="\xA0")}}var _t='<svg width="18" height="18" viewBox="0 0 18 18" fill="none" role="img" aria-label="Submit"><path d="M9 14V4M9 4L4 9M9 4L14 9" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';function Je(o,e){let{listboxId:t}=e,i=ue(t);o.appendChild(i);let r=document.createElement("div");r.className="magicx-aia-input-wrapper",o.appendChild(r);let n=document.createElement("div");n.className="magicx-aia-editor",n.setAttribute("data-aia-editor",""),r.appendChild(n);let s=document.createElement("div");s.className="magicx-aia-sizer",s.setAttribute("aria-hidden","true"),n.appendChild(s);let d=document.createElement("span");s.appendChild(document.createTextNode(" ")),s.appendChild(d);let a=document.createElement("textarea");a.className="magicx-aia-textarea",a.rows=1,a.setAttribute("role","combobox"),a.setAttribute("aria-autocomplete","list"),a.setAttribute("aria-controls",t),a.setAttribute("data-aia-textarea",""),n.appendChild(a);let l=null,p=null;return e.submitButton===void 0?(l=document.createElement("button"),l.type="button",l.className="magicx-aia-submit",l.setAttribute("aria-label","Submit"),l.setAttribute("data-aia-submit",""),l.innerHTML=_t,r.appendChild(l),p=l):e.submitButton!==null&&(p=e.submitButton,p.hasAttribute("data-aia-submit")||p.setAttribute("data-aia-submit",""),r.appendChild(p)),r.addEventListener("click",()=>a.focus()),a.addEventListener("input",()=>{let c=a.value,g=c.length>0&&c[0]!==c[0].toUpperCase()?c[0].toUpperCase()+c.slice(1):c;e.handleChange(g)}),a.addEventListener("keydown",c=>e.handleKeyDown(c)),a.addEventListener("focus",()=>e.store.set({isFocused:!0})),a.addEventListener("blur",()=>e.store.set({isFocused:!1})),p&&p.addEventListener("click",c=>{let m=e.store.get();if(!(!!m.text||m.completedParams.length>0)||!e.onSubmit)return;c.stopPropagation();let{rawQuery:x,completedParams:y}=A(m.text,m.completedParams);e.onSubmit({query:m.text.trim(),raw_query:x,completed_params:y}),e.afterSubmit?.()}),e.autoFocus!==!1&&a.focus(),{textarea:a,dropdown:i,sizer:s,submitButton:l,inlinePillContainer:d}}function Ee(o,e,t){let{textarea:i,dropdown:r,sizer:n,submitButton:s,inlinePillContainer:d}=o,{pillPlacement:a,setActivePill:l,selectOption:p,store:c}=t;i.value!==e.text&&(i.value=e.text),e.placeholderText?i.placeholder=e.placeholderText:i.removeAttribute("placeholder"),i.setAttribute("aria-expanded",String(e.isDropdownOpen));let m=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(m?i.setAttribute("aria-activedescendant",m):i.removeAttribute("aria-activedescendant"),e.newParamId?i.classList.add("magicx-aia-textarea--hidden"):i.classList.remove("magicx-aia-textarea--hidden"),s){let g=!!e.text||e.completedParams.length>0;s.disabled=!g}Xe(n,e.segments,e.newParamId,!e.text,e.placeholderText),a==="inline"?ce(d,e.actionableSuggestions,0,l):d.innerHTML="",me(r,{suggestions:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:a==="dropdown",onSelect:p,onHighlight:g=>c.set({activeDropdownIndex:g}),onPillClick:l})}function Ye(o){let e=o,t=new Set;return{get:()=>e,set:i=>{let r=typeof i=="function"?i(e):i,n={...e,...r},s=e;e=n;for(let d of t)d(n,s)},subscribe:i=>(t.add(i),()=>{t.delete(i)})}}var De=!1;function Ze(){if(De||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){De=!0;return}De=!0;let o=document.createElement("style");o.setAttribute("data-magicx-aia",""),o.textContent=Ct,document.head.appendChild(o)}var Ct="";var At=0;function Pt(){return`:ac-${++At}:`}function et(){return{text:"",completedParams:[],suggestions:[],activeDropdownIndex:-1,newParamId:null,isLoading:!1,isReady:!1,error:null,segments:[],actionableSuggestions:[],filteredOptions:[],placeholderText:"",isDropdownOpen:!1,filterBase:0,filterInProgress:!1,pillTapped:!1,skipNextFetch:!1,lastRawQuery:"",isFocused:!1}}var ge=class{constructor(e,t={}){this.store=Ye(et());this._listboxId=Pt();this.modeController=null;this.unsubscribers=[];this.derivedInProgress=!1;this.domRefs=null;this.dropdownRefs=null;this.externalListeners=new Set;this.sessionId=crypto.randomUUID();this.container=e,this.opts=t,this.renderMode=t.renderMode??"full",t.value!==void 0&&this.store.set({text:t.value}),t.completedParams!==void 0&&this.store.set({completedParams:t.completedParams}),this.pillsController=new pe(this.store,{onPillSelected:({rawQuery:i,selectedPill:r,otherPills:n})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:r,other_pills:n})}}),this.fetchController=new le(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.opts.onError,()=>this.sessionId,{onAutoMatch:({active:i,matched:r,rawQuery:n})=>{this.fireTelemetry("option",{raw_query:n,selected_option:r.text,other_options:(i.options??[]).filter(s=>s.text!==r.text).map(s=>s.text)})}}),this.keyboardController=new de(this.store,{columns:t.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.opts.onSubmit,afterSubmit:this.renderMode==="full"?()=>this.reset():void 0,selectOption:i=>this.selectOption(i)}),this.unsubscribers.push(this.store.subscribe((i,r)=>{this.recomputeDerived(i,r)})),this.unsubscribers.push(this.store.subscribe((i,r)=>{i.text!==r.text&&this.opts.onChange?.(i.text),i.completedParams!==r.completedParams&&this.opts.onParamsChange?.(i.completedParams),i.isFocused!==r.isFocused&&(i.isFocused?this.opts.onFocus?.():this.opts.onBlur?.()),this.opts.onStateChange?.(i)})),this.renderMode!=="headless"&&(Ze(),this.setupContainer()),this.renderMode==="full"?this.buildAndRenderFull():this.renderMode==="dropdown"&&this.buildAndRenderDropdown(),this.fetchController.start()}focus(){this.domRefs?.textarea.focus()}blur(){this.domRefs?.textarea.blur()}reset(){this.store.set({...et(),skipNextFetch:!0}),this.sessionId=crypto.randomUUID(),this.fetchController.doFetch("",[])}destroy(){this.fetchController.dispose(),this.modeController?.destroy(),this.newParamTimer&&clearTimeout(this.newParamTimer),this.suggestionRemovalTimer&&clearTimeout(this.suggestionRemovalTimer),this.externalListeners.clear();for(let e of this.unsubscribers)e();this.unsubscribers=[],this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}setValue(e){this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e)}removeLastParam(){this.pillsController.removeLastParam()}clearNewParamId(){this.store.set({newParamId:null})}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}handleTextChange(e){this.handleChange(e)}handleKeyDown(e){this.keyboardController.handleKeyDown(e)}setFocused(e){this.store.get().isFocused!==e&&this.store.set({isFocused:e})}subscribe(e){return this.externalListeners.add(e),()=>{this.externalListeners.delete(e)}}getState(){return this.store.get()}get listboxId(){return this._listboxId}get isReady(){return this.store.get().isReady}on(e,t){switch(e){case"submit":return this.opts.onSubmit=t,()=>{this.opts.onSubmit=void 0};case"error":return this.opts.onError=t,()=>{this.opts.onError=void 0};case"change":return this.opts.onChange=t,()=>{this.opts.onChange=void 0};case"paramsChange":return this.opts.onParamsChange=t,()=>{this.opts.onParamsChange=void 0};case"stateChange":return this.opts.onStateChange=t,()=>{this.opts.onStateChange=void 0};case"focus":return this.opts.onFocus=t,()=>{this.opts.onFocus=void 0};case"blur":return this.opts.onBlur=t,()=>{this.opts.onBlur=void 0};default:return()=>{}}}update(e){Object.assign(this.opts,e),e.mode!==void 0&&this.modeController?.setMode(e.mode),e.optionsPosition!==void 0&&(this.container.dataset.optionsPosition=e.optionsPosition),e.animations!==void 0&&(this.container.dataset.animations=e.animations?"on":"off"),e.pillPlacement!==void 0&&(this.container.dataset.pillPlacement=e.pillPlacement,this.store.set({})),(e.dropdownTrigger!==void 0||e.closeDropdownOnBlur!==void 0)&&this.store.set({}),e.value!==void 0&&this.store.set({text:e.value}),e.completedParams!==void 0&&this.store.set({completedParams:e.completedParams})}selectOption(e){let t=this.store.get(),i=t.actionableSuggestions[0];if(!i)return;let{rawQuery:r}=A(t.text,t.completedParams);this.fireTelemetry("option",{raw_query:r,selected_option:e.text,other_options:t.filteredOptions.filter(h=>h.text!==e.text).map(h=>h.text)});let n=t.filterBase,s=t.text.slice(0,n),d=s.length===0&&t.text.length===0,a=s.length===0&&t.text.length>0&&t.placeholderText.length>0&&t.placeholderText.toLowerCase().startsWith(t.text.toLowerCase());(d||a)&&t.placeholderText&&(s=`${t.placeholderText} `);let l=Fe(s,e.text);l>0&&(s=s.slice(0,s.length-l));let p=s.length>0&&s[s.length-1]!==" ",c=`${s}${p?" ":""}${e.text} `,m=(d||a)&&c.length>0?c[0].toUpperCase()+c.slice(1):c,g=m.toLowerCase().lastIndexOf(e.text.toLowerCase()),x=g>=0?m.slice(g,g+e.text.length):e.text,y={id:crypto.randomUUID(),placeholder:"",type:i.type,text:x,kind:e.kind,suggestionType:i.type,suggestionPlaceholder:i.text,options:i.options??[],metadata:e.metadata},b=t.actionableSuggestions.length-1;this.store.set(h=>({text:m,filterBase:m.length,completedParams:[...h.completedParams,y],newParamId:y.id,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:b>0})),this.suggestionRemovalTimer=window.setTimeout(()=>{this.store.set(h=>({suggestions:h.suggestions.filter(S=>S!==i)}))},400)}fireTelemetry(e,t){let i=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");Ue({source:i,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}recomputeDerived(e,t){if(this.derivedInProgress)return;this.derivedInProgress=!0;let i=Ne(e.text,e.completedParams),r=e.suggestions.filter(h=>h.type!=="placeholder"),n=r[0],s=n?this.opts.optionOverrides?.[n.type]:void 0,d=Math.min(e.filterBase,e.text.length),l=e.lastRawQuery!==""||d>0?Q(e.text,d,e.filterInProgress):"",p=n?s?s(l.trim()):n.options??[]:[],c=ie(p,l),m=e.suggestions.filter(h=>h.type==="placeholder").map(h=>h.text).join(" "),g=this.opts.dropdownTrigger??"auto",x=this.opts.closeDropdownOnBlur??!0,y=!1;if(g==="auto"){let h=x?e.isFocused:!0;y=!e.isLoading&&c.length>0&&h}else g==="manual"&&(y=!e.isLoading&&c.length>0&&e.pillTapped);this.store.set({segments:i,actionableSuggestions:r,filteredOptions:c,placeholderText:m,isDropdownOpen:y}),this.derivedInProgress=!1;let b=this.store.get();for(let h of this.externalListeners)h(b)}setupContainer(){this.container.classList.add("magicx-aia"),this.container.dataset.pillPlacement=this.renderMode==="dropdown"?"dropdown":this.opts.pillPlacement??"inline",this.container.dataset.optionsPosition=this.opts.optionsPosition??"below",this.container.dataset.animations=this.opts.animations??!0?"on":"off",this.modeController=new K(this.container,this.opts.mode??"auto")}buildAndRenderFull(){let e=this,t={store:this.store,listboxId:this.listboxId,get pillPlacement(){return e.opts.pillPlacement??"inline"},get onSubmit(){return e.opts.onSubmit},afterSubmit:()=>e.reset(),submitButton:this.opts.submitButton,autoFocus:this.opts.autoFocus??!0,selectOption:i=>this.selectOption(i),setActivePill:i=>this.pillsController.setActivePill(i),handleKeyDown:i=>this.keyboardController.handleKeyDown(i),handleChange:i=>this.handleChange(i)};this.domRefs=Je(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&Ee(this.domRefs,this.store.get(),t)}),Ee(this.domRefs,this.store.get(),t),this.subscribeNewParamTimer()}buildAndRenderDropdown(){let e={store:this.store,listboxId:this.listboxId,selectOption:t=>this.selectOption(t),setActivePill:t=>this.pillsController.setActivePill(t)};this.dropdownRefs=je(this.container,e),this.subscribeBatchedRender(()=>{this.dropdownRefs&&Oe(this.dropdownRefs,this.store.get(),e)}),Oe(this.dropdownRefs,this.store.get(),e),this.subscribeNewParamTimer()}subscribeBatchedRender(e){let t=!1;this.unsubscribers.push(this.store.subscribe(()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,t)=>{e.newParamId&&e.newParamId!==t.newParamId&&(this.newParamTimer&&clearTimeout(this.newParamTimer),this.newParamTimer=window.setTimeout(()=>{this.store.set({newParamId:null})},650))}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:r}=Ke(e,t.completedParams);r.length>0&&this.store.set(n=>({completedParams:i,suggestions:[...r.map(s=>({type:s.suggestionType,text:s.suggestionPlaceholder,required:!0,options:s.options})),...n.suggestions]}))}};function Le({onSubmit:o,onError:e,optionOverrides:t,maskCompletedText:i,apiConfig:r,columns:n=2,dropdownTrigger:s,closeDropdownOnBlur:d,onFocus:a,onBlur:l,value:p,completedParams:c,onChange:m,onParamsChange:g,source:x}){let y=E(null),[b,h]=kt(null),S=E(o);S.current=o;let k=E(e);k.current=e;let H=E(m);H.current=m;let B=E(g);B.current=g;let W=E(a);W.current=a;let q=E(l);q.current=l,fe(()=>{if(typeof document>"u")return;let u=new ge(document.createElement("div"),{renderMode:"headless",apiConfig:r,optionOverrides:t,maskCompletedText:i,columns:n,dropdownTrigger:s,closeDropdownOnBlur:d,source:x,value:p,completedParams:c,onSubmit:(...C)=>S.current?.(...C),onError:(...C)=>k.current?.(...C),onChange:(...C)=>H.current?.(...C),onParamsChange:(...C)=>B.current?.(...C),onFocus:()=>W.current?.(),onBlur:()=>q.current?.()});y.current=u,h(u.getState());let w=u.subscribe(C=>h(C));return()=>{w(),u.destroy(),y.current===u&&(y.current=null)}},[]);let f=y.current,I=P(()=>{},[]);fe(()=>{p!==void 0&&f?.setValue(p)},[p,f]),fe(()=>{c!==void 0&&f?.setCompletedParams(c)},[c,f]);let L=JSON.stringify(r??null),R=E(t),j=E(0);if(t!==R.current){let u=R.current,w=t,C=Object.keys(u??{}),N=Object.keys(w??{});(C.length!==N.length||N.some(Ie=>!u?.[Ie]||w[Ie]!==u[Ie]))&&j.current++,R.current=t}fe(()=>{f?.update({apiConfig:r,optionOverrides:t,dropdownTrigger:s,closeDropdownOnBlur:d})},[L,j.current,s,d,f]);let xe=P(u=>{if(!f)return;let w=u.target.value,N=w.length>0&&!u.nativeEvent?.isComposing&&w[0]!==w[0].toUpperCase()?w[0].toUpperCase()+w.slice(1):w;f.handleTextChange(N)},[f]),X=P(u=>{f?.handleKeyDown(u.nativeEvent)},[f]),M=P(()=>f?.setFocused(!0),[f]),J=P(()=>f?.setFocused(!1),[f]),T=P(u=>f?.setActivePill(u),[f]),be=P(()=>f?.removeLastParam(),[f]),z=P(()=>f?.clearNewParamId(),[f]),Y=P(()=>f?.reset(),[f]),ve=P(u=>f?.selectOption(u),[f]),F=P(u=>f?.setActiveDropdownIndex(u),[f]);if(!f)return{completedParams:c??[],suggestionPills:[],setActivePill:I,removeLastParam:I,segments:[],newParamId:null,clearNewParamId:I,suggestions:[],activeIndex:-1,isReady:!1,isLoading:!0,error:null,inputProps:{value:p??"",placeholder:void 0,onChange:I,onKeyDown:I,onFocus:I,onBlur:I,role:"combobox","aria-expanded":!1,"aria-activedescendant":void 0,"aria-autocomplete":"list","aria-controls":""},reset:I,dropdownProps:{suggestions:[],activeIndex:-1,onSelect:I,onHighlight:I,isOpen:!1,id:"",pills:[],onPillClick:I}};let v=b??f.getState(),ye=p!==void 0?p:v.text,Z=c!==void 0?c:v.completedParams,U=v.actionableSuggestions,ee=U[0],we=v.filteredOptions,Se=v.activeDropdownIndex>=0?`${f.listboxId}-option-${v.activeDropdownIndex}`:void 0;return{completedParams:Z,suggestionPills:U,setActivePill:T,removeLastParam:be,segments:v.segments,newParamId:v.newParamId,clearNewParamId:z,suggestions:v.suggestions,activeIndex:v.activeDropdownIndex,isReady:v.isReady,isLoading:v.isLoading,error:v.error,inputProps:{value:ye,placeholder:v.placeholderText||void 0,onChange:xe,onKeyDown:X,onFocus:M,onBlur:J,role:"combobox","aria-expanded":v.isDropdownOpen,"aria-activedescendant":Se,"aria-autocomplete":"list","aria-controls":f.listboxId},reset:Y,dropdownProps:{suggestions:ee?[{...ee,options:we}]:[],activeIndex:v.activeDropdownIndex,onSelect:ve,onHighlight:F,isOpen:v.isDropdownOpen,id:f.listboxId,pills:U,onPillClick:T}}}import{jsx as D,jsxs as $}from"react/jsx-runtime";function Dt(o){return o!=="auto"?o:typeof window>"u"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}var Lt=Tt(function({onSubmit:e,onError:t,optionOverrides:i,maskCompletedText:r,className:n,apiConfig:s,columns:d,pillPlacement:a="inline",mode:l="auto",optionsPosition:p="below",animations:c=!0,dropdownTrigger:m,closeDropdownOnBlur:g,autoFocus:x=!0,onFocus:y,onBlur:b,value:h,completedParams:S,onChange:k,onParamsChange:H,submitButton:B},W){let q=he(null),f=he(null),I=he(()=>{}),L=he(null);Re(()=>{let u=q.current;if(u)return L.current?L.current.setMode(l):L.current=new K(u,l),()=>{L.current?.destroy(),L.current=null}},[l]);let{completedParams:R,suggestionPills:j,setActivePill:xe,segments:X,newParamId:M,clearNewParamId:J,inputProps:T,dropdownProps:be,reset:z}=Le({onSubmit:u=>I.current(u),onError:t,optionOverrides:i,maskCompletedText:r,apiConfig:s,columns:d,dropdownTrigger:m,closeDropdownOnBlur:g,onFocus:y,onBlur:b,value:h,completedParams:S,onChange:k,onParamsChange:H,source:"full-sdk"}),Y=T.onFocus;Re(()=>{if(!x)return;let u=f.current;u&&(document.activeElement===u?Y():u.focus())},[Y,x]),Re(()=>{if(!M)return;let u=window.setTimeout(()=>J(),650);return()=>window.clearTimeout(u)},[M,J]),Et(W,()=>({focus:()=>f.current?.focus(),blur:()=>f.current?.blur(),reset:z,setMode:u=>L.current?.setMode(u)}),[z]);let ve=()=>{f.current?.focus()},F=!!T.value||R.length>0,v=Ot(()=>{if(!F)return;let{rawQuery:u,completedParams:w}=A(T.value,R);e({query:T.value.trim(),raw_query:u,completed_params:w}),z()},[F,T.value,R,e,z]);I.current=v;let{onChange:ye,placeholder:Z,...U}=T,ee=!T.value,we=a==="inline",Se=a==="dropdown";return $("div",{ref:q,className:`magicx-aia ${_.container} ${n??""}`,"data-pill-placement":a,"data-options-position":p,"data-animations":c?"on":"off","data-mode":Dt(l),children:[D(ke,{...be,showPills:Se}),$("div",{className:_.inputWrapper,onClick:ve,children:[$("div",{className:_.editorArea,"data-aia-editor":"",children:[$("div",{className:_.sizerContent,"aria-hidden":"true",children:[ee&&Z?$("span",{className:_.placeholderText,children:[Z," "]}):$("span",{className:`${_.sizerText} ${M?_.sizerTextVisible:""}`,children:[X.map((u,w)=>{if(u.type==="completed"&&u.param.id===M){let N=`${_.shimmerRevealed} ${_.shimmerSweep}`;return D("span",{className:N,children:u.value},`${w}-${u.type}`)}return D("span",{children:u.value},`${w}-${u.type}`)}),X.length===0&&"\xA0"]})," ",we&&D(oe,{pills:j,activePillIndex:0,onSelectPill:xe})]}),D("textarea",{ref:f,"data-aia-textarea":"",className:`${_.textarea} ${M?_.textareaHidden:""}`,rows:1,onChange:ye,...U})]}),B===null?null:B===void 0?D("button",{type:"button","data-aia-submit":"",className:_.submitButton,disabled:!F,onClick:u=>{u.stopPropagation(),v()},"aria-label":"Submit",children:D("svg",{width:"18",height:"18",viewBox:"0 0 18 18",fill:"none",role:"img","aria-label":"Submit",children:D("path",{d:"M9 14V4M9 4L4 9M9 4L14 9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}):D("span",{"data-aia-submit":"",className:_.submitSlot,onClick:u=>{F&&(u.stopPropagation(),v())},children:B})]})]})});export{Lt as AIAutocomplete,ke as AIAutocompleteDropdown,Le as useAIAutocomplete};
786
+ `,document.head.appendChild(n)}var It='[contenteditable="false"]',ie;function dn(){if(ie!==void 0)return ie;let n=globalThis.Intl.Segmenter;if(!n)return ie=null,null;try{ie=new n(void 0,{granularity:"grapheme"})}catch{ie=null}return ie??null}function Re(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(It))return!0;t=t.parentNode}return!1}function Ne(n){return(n.ownerDocument??document).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return Re(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function re(n){let e=Ne(n),t="",o=e.nextNode();for(;o;)t+=o.data,o=e.nextNode();return t}function He(n){let e=Ne(n),t=0,o=e.nextNode();for(;o;)t+=o.data.length,o=e.nextNode();return t}function H(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(Re(r,n)&&r!==n)return null;let a=0;for(let i=0;i<o&&i<r.childNodes.length;i++)a+=Ct(r.childNodes[i],n);return a+Pt(r,n)}return t.nodeType!==Node.TEXT_NODE||Re(t,n)?null:Pt(t,n)+o}function Ct(n,e){if(n.nodeType===Node.TEXT_NODE)return Re(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(It))return 0;let o=0;for(let r of Array.from(t.childNodes))o+=Ct(r,e);return o}function Pt(n,e){let t=Ne(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 L(n,e){let t=n.ownerDocument??document,o=t.getSelection();if(!o)return;let r=Math.max(0,Math.min(e,He(n))),a=Ne(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 At(n){let e=H(n);return e==null?!1:e>=He(n)}function _t(n,e){if(e<=0)return 0;let t=dn();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 Be(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?H(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,S=g.param.id===r,C=["magicx-aia-segment","magicx-aia-segment--completed"];f&&C.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),S&&C.push("magicx-aia-segment--editing"),m.className=C.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&&L(e,Math.max(0,Math.min(u,y)))}import{useCallback as E,useEffect as Je,useRef as z,useState as Dn}from"react";function N(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 fe(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function ae(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 Tt(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 he(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 se(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 le=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 Et(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 kt(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 Fe=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 cn="https://api.ai-autocomplete.com",Ke=`${cn}/api/suggest`,Ot=new WeakMap;function be(n){return n?.type==="accessToken"}function pn(n){if(!(!n||be(n)))return n}function ze(n){let e=Ot.get(n.getAccessToken);return e||(e=new Fe(n),Ot.set(n.getAccessToken,e)),e}function We(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function $e(n){let e=pn(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}function un(n){return(n??Ke).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function mn(n){return be(n)?`Bearer ${await ze(n).getToken()}`:$e(n)}async function Dt(n){try{let e=un(n.apiConfig?.endpoint),t=We(n.apiConfig),o=await mn(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 gn="0.1.39",Lt=!1;function fn(){return crypto.randomUUID()}function hn(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.text},kind:n.kind}}function bn(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=>hn(i,t)),...a!=null&&{contact_account_count:a}},meta:{request_id:fn(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:gn,session_id:o}}}async function Mt(n,e,t,o,r){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:o,signal:r})}async function Rt(n,e,t){let o=t.apiConfig,r=!t.maskCompletedText,a=bn(n,e,r,t.sessionId),i=We(o),s=o?.endpoint??Ke,l=JSON.stringify(a);if(be(o)){let p=ze(o),u=await p.getToken(),x=await Mt(s,i,u,l,t.signal);if(x.status===401){let h=await p.getToken(!0);x=await Mt(s,i,h,l,t.signal)}if(!x.ok)throw new Error(`API error: ${x.status} ${x.statusText}`);return x.json()}let d=$e(o);!d&&!Lt&&(Lt=!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 Nt(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 xn=100,vn=300,yn=2,qe=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 Rt(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:o.signal,apiConfig:this.getApiConfig()});if(r!==this.fetchVersion)return;let s=Nt(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=ae(c,p,u),m=se(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=fe(r.text,r.filterBase,a),s=ae(r.text,i,r.filterInProgress),d=r.suggestions.filter(f=>f.type!=="placeholder")[0],p=(d?he(d.options,s):[]).filter(f=>f.is_tappable),u=d?se(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}=N(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(yn)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},xn),this.slowDebounceTimer=setTimeout(()=>t(1),vn)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};function Ht(n){return n instanceof HTMLTextAreaElement||n instanceof HTMLInputElement?n.selectionStart!=null&&n.selectionStart===n.value.length:n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?At(n):!1}function wn(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?H(n):null}var Ue=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=Ht(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?.(),L(d,c);break}Ht(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?.(),L(l,d);break}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let l=wn(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}=N(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(()=>L(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?.(),L(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 Ge=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}=N(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 Bt=[125,69];function Ft(n){return n===0?.4:n===1?.3:.15}function Qe(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<Bt.length;d++){let c=Bt[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(Ft(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(Ft(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 Sn=[159,119,164],Pn=[115,122];function je(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 Ve(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=In(s),n.appendChild(h);else{let m=h.querySelector(".magicx-aia-skeleton-pills");s&&!m?h.insertBefore(Kt(),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)),Qe(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)),Cn(g,t,o,l,d,e.listboxId)):g&&(g.innerHTML="")}function In(n){let e=document.createElement("div");e.className="magicx-aia-skeleton",e.setAttribute("data-aia-skeleton",""),n&&e.appendChild(Kt());let t=document.createElement("div");t.className="magicx-aia-skeleton-bars";for(let o of Sn){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 Kt(){let n=document.createElement("div");n.className="magicx-aia-skeleton-pills",n.setAttribute("data-aia-skeleton-pills","");for(let e of Pn){let t=document.createElement("span");t.className="magicx-aia-skeleton-pill",t.style.width=`${e}px`,n.appendChild(t)}return n}function Cn(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=An(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 An(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 zt(n,e){let t=je(e.listboxId);return n.appendChild(t),{dropdown:t}}function ut(n,e,t){Ve(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 _n='<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 Tn(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function Wt(n,e){let{listboxId:t}=e,o=je(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",Tn()?"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=_n,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=re(i),S=m.length>0&&m[0]!==m[0].toUpperCase()?m[0].toUpperCase()+m.slice(1):m;e.handleChange(S)},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(H(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(),S=e.store.get().editingParam?.id??null;if(f&&f!==S){e.startEditingParam(f);return}performance.now()-x<50||e.handleCaretMove(H(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,S=f.inputType;if(S==="insertParagraph"||S==="insertLineBreak"||S==="insertFromDrop"){m.preventDefault();return}if(S.startsWith("insert")||S.startsWith("delete")){let C=S.startsWith("delete")?"":f.data??"";e.replaceEditingRange(C)&&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 S=i.ownerDocument??document,C=S.getSelection();if(!C||C.rangeCount===0)return;let k=C.getRangeAt(0);if(!i.contains(k.startContainer))return;k.deleteContents();let W=S.createTextNode(f);k.insertNode(W),k.setStartAfter(W),k.collapse(!0),C.removeAllRanges(),C.addRange(k),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:C,completedParams:k}=N(f.text,f.completedParams);e.onSubmit({query:f.text.trim(),raw_query:C,completed_params:k}),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(Be({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?Qe(r,e.actionableSuggestions,0,l,!1,g):pt(r)}else pt(r);x?(o.focus(),L(o,e.caretOffset??e.text.length)):e.isFocused&&re(o)!==e.text&&L(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];Ve(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 $t(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 qt(){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=En,document.head.appendChild(n)}var En="";var kn=0;function On(){return`:ac-${++kn}:`}function Ut(){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 Xe=class{constructor(e,t={}){this.store=$t(Ut());this._listboxId=On();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 Ge(this.store,{onPillSelected:({rawQuery:o,selectedPill:r,otherPills:a})=>{this.fireTelemetry("pill",{raw_query:o,selected_pill:r,other_pills:a})}}),this.fetchController=new qe(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 Ue(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"&&(qt(),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({...Ut(),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=_t(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?L(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}=N(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=Tt(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:N(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");Dt({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=Et(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=fe(e.text,Math.min(e.filterBase,e.text.length),s),c=e.lastRawQuery!==""||l>0?ae(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,S=e.completedParams.some(W=>W.id===f),C=e.caretOffset??e.editingAnchor,k=S?"":e.text.slice(e.editingAnchor,C);x=he(e.editingParam.options,k)}else x=he(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,S=e.text.replace(/\s+$/,"").length,C=e.caretOffset==null||e.caretOffset>=S;g=(x.length>0||e.isLoading)&&f&&C}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 le(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=Wt(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=zt(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}=kt(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=fe(e,t.filterBase,a),s=ae(e,i,t.filterInProgress),l=se(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(S=>S!==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(S=>S.id===t.id))return;let a=e.text.slice(o,r),i=se(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 S=0;S<e.completedParams.length;S++){let C=u.indexOf(e.completedParams[S].text,m);if(C!==-1){if(C>=h){g=S;break}m=C+e.completedParams[S].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 ft({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=z(null),[m,f]=Dn(null),S=z(n);S.current=n;let C=z(e);C.current=e;let k=z(u);k.current=u;let W=z(x);W.current=x;let de=z(l);de.current=l;let T=z(d);T.current=d;let ce=z(y);ce.current=y,Je(()=>{if(typeof document>"u")return;let w=new Xe(document.createElement("div"),{renderMode:"headless",apiConfig:r,optionOverrides:t,maskCompletedText:o,columns:a,dropdownTrigger:i,closeDropdownOnBlur:s,source:h,value:c,completedParams:p,onSubmit:(...O)=>S.current?.(...O),onError:(...O)=>C.current?.(...O),onChange:(...O)=>k.current?.(...O),onParamsChange:(...O)=>W.current?.(...O),onFocus:()=>de.current?.(),onBlur:()=>T.current?.(),setCursor:O=>ce.current?.(O)});g.current=w,f(w.getState());let M=w.subscribe(O=>f(O));return()=>{M(),w.destroy(),g.current===w&&(g.current=null)}},[]);let b=g.current,A=E(()=>{},[]);Je(()=>{c!==void 0&&b?.setValue(c)},[c,b]),Je(()=>{p!==void 0&&b?.setCompletedParams(p)},[p,b]);let ve=JSON.stringify(r??null),te=z(t),pe=z(0);if(t!==te.current){let w=te.current,M=t,O=Object.keys(w??{}),$=Object.keys(M??{});(O.length!==$.length||$.some(ee=>!w?.[ee]||M[ee]!==w[ee]))&&pe.current++,te.current=t}Je(()=>{b?.update({apiConfig:r,optionOverrides:t,dropdownTrigger:i,closeDropdownOnBlur:s})},[ve,pe.current,i,s,b]);let ye=E(w=>{if(!b)return;let M=w.target.value,$=M.length>0&&!w.nativeEvent?.isComposing&&M[0]!==M[0].toUpperCase()?M[0].toUpperCase()+M.slice(1):M;b.handleTextChange($)},[b]),Ze=E(w=>{b?.handleKeyDown(w.nativeEvent)},[b]),ue=E(()=>b?.setFocused(!0),[b]),we=E(()=>b?.setFocused(!1),[b]),et=E(w=>b?.handleTextChange(w),[b]),me=E(w=>{if(!b)return;let M="nativeEvent"in w?w.nativeEvent:w;b.handleKeyDown(M)},[b]),V=E(w=>b?.setFocused(w),[b]),Se=E(w=>b?.startEditingParam(w),[b]),Pe=E(()=>b?.exitEditMode(),[b]),Ie=E(w=>b?.handleCaretAfterInput(w),[b]),tt=E(w=>b?.handleCaretMove(w),[b]),Ce=E(w=>b?.replaceEditingRange(w)??!1,[b]),ge=E(w=>b?.setActivePill(w),[b]),Ae=E(()=>b?.removeLastParam(),[b]),_e=E(()=>b?.clearNewParamId(),[b]),Te=E(()=>b?.reset(),[b]),ne=E(w=>b?.selectOption(w),[b]),X=E(w=>b?.setActiveDropdownIndex(w),[b]);if(!b)return{completedParams:p??[],suggestionPills:[],setActivePill:A,removeLastParam:A,segments:[],newParamId:null,clearNewParamId:A,suggestions:[],activeIndex:-1,isReady:!1,isLoading:!0,isFocused:!1,isDropdownOpen:!1,placeholderText:"",listboxId:"",error:null,handleTextChange:A,handleKeyDown:A,setFocused:A,editingParam:null,editingAnchor:null,caretOffset:null,startEditingParam:A,exitEditMode:A,handleCaretAfterInput:A,handleCaretMove:A,replaceEditingRange:()=>!1,inputProps:{value:c??"",placeholder:void 0,onChange:A,onKeyDown:A,onFocus:A,onBlur:A,role:"combobox","aria-expanded":!1,"aria-activedescendant":void 0,"aria-autocomplete":"list","aria-controls":""},reset:A,dropdownProps:{suggestions:[],activeIndex:-1,onSelect:A,onHighlight:A,isOpen:!1,id:"",pills:[],onPillClick:A}};let I=m??b.getState(),nt=c!==void 0?c:I.text,Ee=p!==void 0?p:I.completedParams,oe=I.actionableSuggestions,ke=oe[0],Oe=I.filteredOptions,ot=I.activeDropdownIndex>=0?`${b.listboxId}-option-${I.activeDropdownIndex}`:void 0,B=I.editingParam,F=B?{type:B.suggestionType,text:B.suggestionPlaceholder,required:!0,options:B.options}:null,De=F??ke,it=F?[F]:oe;return{completedParams:Ee,suggestionPills:oe,setActivePill:ge,removeLastParam:Ae,segments:I.segments,newParamId:I.newParamId,clearNewParamId:_e,suggestions:I.suggestions,activeIndex:I.activeDropdownIndex,isReady:I.isReady,isLoading:I.isLoading,isFocused:I.isFocused,isDropdownOpen:I.isDropdownOpen,placeholderText:I.placeholderText,listboxId:b.listboxId,error:I.error,handleTextChange:et,handleKeyDown:me,setFocused:V,editingParam:B,editingAnchor:I.editingAnchor,caretOffset:I.caretOffset,startEditingParam:Se,exitEditMode:Pe,handleCaretAfterInput:Ie,handleCaretMove:tt,replaceEditingRange:Ce,inputProps:{value:nt,placeholder:I.placeholderText||void 0,onChange:ye,onKeyDown:Ze,onFocus:ue,onBlur:we,role:"combobox","aria-expanded":I.isDropdownOpen,"aria-activedescendant":ot,"aria-autocomplete":"list","aria-controls":b.listboxId},reset:Te,dropdownProps:{suggestions:De?[{...De,options:Oe}]:[],activeIndex:I.activeDropdownIndex,onSelect:ne,onHighlight:X,isOpen:I.isDropdownOpen,id:b.listboxId,pills:it,onPillClick:ge,isLoading:I.isLoading&&!I.editingParam}}}import{jsx as Z,jsxs as bt}from"react/jsx-runtime";function Rn(n){return n!=="auto"?n:typeof window>"u"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}var Ye;function Nn(){if(Ye!==void 0)return Ye;if(typeof document>"u")return!1;let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),Ye=n.contentEditable==="plaintext-only",Ye}var Hn=Ln(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:S,onParamsChange:C,submitButton:k},W){let de=j(null),T=j(null),ce=j(()=>{}),b=j(null),A=j(!1),ve=j(""),te=j(""),pe=j(null),ye=j(0);xe(()=>{let v=de.current;if(v)return b.current?b.current.setMode(d):b.current=new le(v,d),()=>{b.current?.destroy(),b.current=null}},[d]);let Ze=Q(v=>{let P=T.current;P&&L(P,v)},[]),{completedParams:ue,suggestionPills:we,setActivePill:et,segments:me,newParamId:V,clearNewParamId:Se,placeholderText:Pe,isFocused:Ie,isDropdownOpen:tt,isLoading:Ce,activeIndex:ge,listboxId:Ae,handleTextChange:_e,handleKeyDown:Te,setFocused:ne,editingParam:X,editingAnchor:I,caretOffset:nt,startEditingParam:Ee,handleCaretAfterInput:oe,handleCaretMove:ke,replaceEditingRange:Oe,dropdownProps:ot,reset:B}=ft({onSubmit:v=>ce.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:S,onParamsChange:C,source:"full-sdk",setCursor:Ze});pe.current=nt,xe(()=>{if(!h)return;let v=T.current;v&&(document.activeElement===v?ne(!0):v.focus())},[h,ne]),xe(()=>{if(!V)return;let v=window.setTimeout(()=>Se(),650);return()=>window.clearTimeout(v)},[V,Se]),xe(()=>{let v=T.current;if(!v)return;let P=v.ownerDocument??document,_=()=>{let R=P.getSelection();if(!R||R.rangeCount===0||!R.anchorNode||!v.contains(R.anchorNode))return;let D=R.anchorNode,at=(D.nodeType===Node.ELEMENT_NODE?D:D.parentElement)?.closest('strong[data-seg="completed"][data-param-id]')?.dataset.paramId??null;if(at&&at!==X?.id){Ee(at);return}performance.now()-ye.current<50||ke(H(v))};return P.addEventListener("selectionchange",_),()=>P.removeEventListener("selectionchange",_)},[X,Ee,ke]),ht(()=>{let v=T.current;v&&Be({input:v,segments:me,newParamId:V,editingParamId:X?.id??null,placeholderText:Pe??"",isFocused:Ie})},[me,V,X,Pe,Ie]),ht(()=>{let v=ve.current,P=V??"";if(ve.current=P,!P||P===v)return;let _=T.current;if(!_)return;_.focus();let R=pe.current??He(_);L(_,R)},[V]),ht(()=>{let v=te.current,P=X?.id??"";if(te.current=P,!P||P===v||I==null)return;let _=T.current;_&&L(_,I)},[X,I]),Mn(W,()=>({focus:()=>T.current?.focus(),blur:()=>T.current?.blur(),reset:B,setMode:v=>b.current?.setMode(v)}),[B]);let F=Q(()=>{if(A.current)return;let v=T.current;if(!v)return;let P=re(v),R=P.length>0&&P[0]!==P[0].toUpperCase()?P[0].toUpperCase()+P.slice(1):P;_e(R)},[_e]),De=Q(()=>{ye.current=performance.now(),F();let v=T.current;v&&oe(H(v))},[F,oe]);xe(()=>{let v=T.current;if(!v)return;let P=_=>{let R=_,D=R.inputType;if(D==="insertParagraph"||D==="insertLineBreak"||D==="insertFromDrop"){_.preventDefault();return}if(D.startsWith("insert")||D.startsWith("delete")){let q=D.startsWith("delete")?"":R.data??"";Oe(q)&&_.preventDefault()}};return v.addEventListener("beforeinput",P),()=>v.removeEventListener("beforeinput",P)},[Oe]);let it=Q(()=>{A.current=!0},[]),w=Q(()=>{A.current=!1,F()},[F]),M=Q(v=>{v.preventDefault();let P=T.current;if(!P)return;let _=(v.clipboardData.getData("text/plain")??"").replace(/\r?\n/g," ");if(!_)return;let R=P.ownerDocument??document,D=R.getSelection();if(!D||D.rangeCount===0)return;let q=D.getRangeAt(0);if(!P.contains(q.startContainer))return;q.deleteContents();let rt=R.createTextNode(_);q.insertNode(rt),q.setStartAfter(rt),q.collapse(!0),D.removeAllRanges(),D.addRange(q),F()},[F]),O=Q(v=>Te(v),[Te]),$=!!me.length||ue.length>0,ee=Q(()=>{if(!$)return;let v=T.current?re(T.current):"",{rawQuery:P,completedParams:_}=N(v,ue);e({query:v.trim(),raw_query:P,completed_params:_}),B()},[$,ue,e,B]);ce.current=ee;let Gt=Q(v=>{v.target?.closest("[data-aia-pill]")||T.current?.focus()},[]),Qt=l==="inline",jt=l==="dropdown",Vt=ge>=0?`${Ae}-option-${ge}`:void 0,Xt=Nn()?"plaintext-only":"true";return bt("div",{ref:de,className:`magicx-aia ${J.container} ${a??""}`,"data-pill-placement":l,"data-options-position":c,"data-animations":p?"on":"off","data-mode":Rn(d),children:[Z(ct,{...ot,showPills:jt}),bt("div",{className:J.inputWrapper,onClick:Gt,children:[bt("div",{className:J.editorArea,"data-aia-editor":"",children:[Z("div",{ref:T,className:J.input,"data-aia-input":"",contentEditable:Xt,suppressContentEditableWarning:!0,tabIndex:0,role:"combobox","aria-autocomplete":"list","aria-haspopup":"listbox","aria-controls":Ae,"aria-expanded":tt,"aria-activedescendant":Vt,spellCheck:!0,enterKeyHint:"send",onInput:De,onKeyDown:O,onCompositionStart:it,onCompositionEnd:w,onPaste:M,onFocus:()=>ne(!0),onBlur:()=>ne(!1)}),Qt&&(Ce||we.length>0)&&Z("span",{className:J.pillListContainer,"data-aia-pill-list-container":"",children:Z(Me,{pills:we,activePillIndex:0,onSelectPill:et,loading:Ce})})]}),k===null?null:k===void 0?Z("button",{type:"button","data-aia-submit":"",className:J.submitButton,disabled:!$,onClick:v=>{v.stopPropagation(),ee()},"aria-label":"Submit",children:Z("svg",{width:"18",height:"18",viewBox:"0 0 18 18",fill:"none",role:"img","aria-label":"Submit",children:Z("path",{d:"M9 14V4M9 4L4 9M9 4L14 9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}):Z("span",{"data-aia-submit":"",className:J.submitSlot,onClick:v=>{$&&(v.stopPropagation(),ee())},children:k})]})]})});export{Hn as AIAutocomplete,ct as AIAutocompleteDropdown,ft as useAIAutocomplete};
693
787
  //# sourceMappingURL=index.mjs.map