@magicx-eng/ai-autocomplete-react 0.1.41 → 0.1.42
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/index.d.mts +5 -1
- package/dist/index.d.ts +5 -1
- package/dist/index.js +40 -19
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +40 -19
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -186,6 +186,7 @@ function App() {
|
|
|
186
186
|
| `animations?` | `boolean` | `true` | Enable/disable all SDK animations (streak + shimmer). |
|
|
187
187
|
| `dropdownTrigger?` | `"auto" \| "manual" \| "hidden"` | `"auto"` | When the dropdown appears. `"auto"` = when options available. `"manual"` = only on pill tap, closes after selection. `"hidden"` = never shows. |
|
|
188
188
|
| `closeDropdownOnBlur?` | `boolean` | `true` | When `true`, the dropdown closes if the input loses focus. Set to `false` to keep it open whenever options are available, regardless of focus. |
|
|
189
|
+
| `showNonTappableOptions?` | `boolean` | `true` | When `true`, non-tappable options are rendered alongside tappable ones in the dropdown. Set to `false` to hide non-tappable options entirely. |
|
|
189
190
|
| `autoFocus?` | `boolean` | `true` | Focus the input on mount. Set to `false` to leave focus to the consumer. |
|
|
190
191
|
| `onFocus?` | `() => void` | — | Called when the input gains focus. |
|
|
191
192
|
| `onBlur?` | `() => void` | — | Called when the input loses focus. |
|
package/dist/index.d.mts
CHANGED
|
@@ -91,6 +91,8 @@ interface AIAutocompleteProps {
|
|
|
91
91
|
dropdownTrigger?: "auto" | "manual" | "hidden";
|
|
92
92
|
/** When true (default), the dropdown closes when the input loses focus. Set to false to keep it open whenever options are available, regardless of focus. */
|
|
93
93
|
closeDropdownOnBlur?: boolean;
|
|
94
|
+
/** When true (default), non-tappable options are rendered in the dropdown alongside tappable ones. Set to false to hide them entirely. */
|
|
95
|
+
showNonTappableOptions?: boolean;
|
|
94
96
|
/** Focus the input on mount. Default: true. */
|
|
95
97
|
autoFocus?: boolean;
|
|
96
98
|
/** Called when the input gains focus. */
|
|
@@ -131,6 +133,8 @@ interface UseAIAutocompleteOptions {
|
|
|
131
133
|
dropdownTrigger?: "auto" | "manual" | "hidden";
|
|
132
134
|
/** When true (default), the dropdown closes when the input loses focus. Set to false to keep it open whenever options are available. */
|
|
133
135
|
closeDropdownOnBlur?: boolean;
|
|
136
|
+
/** When true (default), non-tappable options are rendered in the dropdown alongside tappable ones. Set to false to hide them entirely. */
|
|
137
|
+
showNonTappableOptions?: boolean;
|
|
134
138
|
/** Called when the input gains focus. */
|
|
135
139
|
onFocus?: () => void;
|
|
136
140
|
/** Called when the input loses focus. */
|
|
@@ -225,6 +229,6 @@ declare const AIAutocomplete: react.ForwardRefExoticComponent<AIAutocompleteProp
|
|
|
225
229
|
|
|
226
230
|
declare function AIAutocompleteDropdown({ suggestions, activeIndex, onSelect, onHighlight, isOpen, id, className, pills, onPillClick, showPills, isLoading, }: AIAutocompleteDropdownProps): react_jsx_runtime.JSX.Element;
|
|
227
231
|
|
|
228
|
-
declare function useAIAutocomplete({ onSubmit, onError, optionOverrides, maskCompletedText, apiConfig, columns, dropdownTrigger, closeDropdownOnBlur, onFocus, onBlur, value: controlledValue, completedParams: controlledParams, onChange: onChangeProp, onParamsChange, source, setCursor, }: UseAIAutocompleteOptions): UseAIAutocompleteReturn;
|
|
232
|
+
declare function useAIAutocomplete({ onSubmit, onError, optionOverrides, maskCompletedText, apiConfig, columns, dropdownTrigger, closeDropdownOnBlur, showNonTappableOptions, onFocus, onBlur, value: controlledValue, completedParams: controlledParams, onChange: onChangeProp, onParamsChange, source, setCursor, }: UseAIAutocompleteOptions): UseAIAutocompleteReturn;
|
|
229
233
|
|
|
230
234
|
export { AIAutocomplete, AIAutocompleteDropdown, type AIAutocompleteDropdownProps, type AIAutocompleteHandle, type AIAutocompleteProps, type APIConfig, type APIKeyConfig, type AccessTokenConfig, type AccessTokenResult, type AppearanceMode, type AutocompleteResult, type CompletedParam, type CompletedParamState, type OptionOverrides, type Segment, type Suggestion, type SuggestionOption, type TaskKind, type UseAIAutocompleteOptions, type UseAIAutocompleteReturn, useAIAutocomplete };
|
package/dist/index.d.ts
CHANGED
|
@@ -91,6 +91,8 @@ interface AIAutocompleteProps {
|
|
|
91
91
|
dropdownTrigger?: "auto" | "manual" | "hidden";
|
|
92
92
|
/** When true (default), the dropdown closes when the input loses focus. Set to false to keep it open whenever options are available, regardless of focus. */
|
|
93
93
|
closeDropdownOnBlur?: boolean;
|
|
94
|
+
/** When true (default), non-tappable options are rendered in the dropdown alongside tappable ones. Set to false to hide them entirely. */
|
|
95
|
+
showNonTappableOptions?: boolean;
|
|
94
96
|
/** Focus the input on mount. Default: true. */
|
|
95
97
|
autoFocus?: boolean;
|
|
96
98
|
/** Called when the input gains focus. */
|
|
@@ -131,6 +133,8 @@ interface UseAIAutocompleteOptions {
|
|
|
131
133
|
dropdownTrigger?: "auto" | "manual" | "hidden";
|
|
132
134
|
/** When true (default), the dropdown closes when the input loses focus. Set to false to keep it open whenever options are available. */
|
|
133
135
|
closeDropdownOnBlur?: boolean;
|
|
136
|
+
/** When true (default), non-tappable options are rendered in the dropdown alongside tappable ones. Set to false to hide them entirely. */
|
|
137
|
+
showNonTappableOptions?: boolean;
|
|
134
138
|
/** Called when the input gains focus. */
|
|
135
139
|
onFocus?: () => void;
|
|
136
140
|
/** Called when the input loses focus. */
|
|
@@ -225,6 +229,6 @@ declare const AIAutocomplete: react.ForwardRefExoticComponent<AIAutocompleteProp
|
|
|
225
229
|
|
|
226
230
|
declare function AIAutocompleteDropdown({ suggestions, activeIndex, onSelect, onHighlight, isOpen, id, className, pills, onPillClick, showPills, isLoading, }: AIAutocompleteDropdownProps): react_jsx_runtime.JSX.Element;
|
|
227
231
|
|
|
228
|
-
declare function useAIAutocomplete({ onSubmit, onError, optionOverrides, maskCompletedText, apiConfig, columns, dropdownTrigger, closeDropdownOnBlur, onFocus, onBlur, value: controlledValue, completedParams: controlledParams, onChange: onChangeProp, onParamsChange, source, setCursor, }: UseAIAutocompleteOptions): UseAIAutocompleteReturn;
|
|
232
|
+
declare function useAIAutocomplete({ onSubmit, onError, optionOverrides, maskCompletedText, apiConfig, columns, dropdownTrigger, closeDropdownOnBlur, showNonTappableOptions, onFocus, onBlur, value: controlledValue, completedParams: controlledParams, onChange: onChangeProp, onParamsChange, source, setCursor, }: UseAIAutocompleteOptions): UseAIAutocompleteReturn;
|
|
229
233
|
|
|
230
234
|
export { AIAutocomplete, AIAutocompleteDropdown, type AIAutocompleteDropdownProps, type AIAutocompleteHandle, type AIAutocompleteProps, type APIConfig, type APIKeyConfig, type AccessTokenConfig, type AccessTokenResult, type AppearanceMode, type AutocompleteResult, type CompletedParam, type CompletedParamState, type OptionOverrides, type Segment, type Suggestion, type SuggestionOption, type TaskKind, type UseAIAutocompleteOptions, type UseAIAutocompleteReturn, useAIAutocomplete };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var nt=Object.defineProperty;var en=Object.getOwnPropertyDescriptor;var tn=Object.getOwnPropertyNames;var nn=Object.prototype.hasOwnProperty;var on=(n,e)=>{for(var t in e)nt(n,t,{get:e[t],enumerable:!0})},rn=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of tn(e))!nn.call(n,i)&&i!==t&&nt(n,i,{get:()=>e[i],enumerable:!(o=en(e,i))||o.enumerable});return n};var an=n=>rn(nt({},"__esModule",{value:!0}),n);var Fn={};on(Fn,{AIAutocomplete:()=>qt,AIAutocompleteDropdown:()=>_e,useAIAutocomplete:()=>Je});module.exports=an(Fn);var D=require("react");if(typeof document<"u"&&!document.getElementById("ac-style-cc65f4cc")){let n=document.createElement("style");n.id="ac-style-cc65f4cc",n.textContent=`.AIAutocomplete-module_container_KKjFU {
|
|
2
2
|
position: relative;
|
|
3
3
|
/* Inherits the host page's font by default. Consumers can pin a specific
|
|
4
4
|
font on the library via \`--aia-font-family: 'Custom Font'\` without
|
|
@@ -15,15 +15,15 @@
|
|
|
15
15
|
overflow: hidden;
|
|
16
16
|
display: flex;
|
|
17
17
|
align-items: center;
|
|
18
|
-
gap:
|
|
18
|
+
gap: 4px;
|
|
19
19
|
}
|
|
20
20
|
|
|
21
21
|
.AIAutocomplete-module_editorArea_7rBWq {
|
|
22
22
|
position: relative;
|
|
23
23
|
flex: 1;
|
|
24
24
|
min-width: 0;
|
|
25
|
-
min-height:
|
|
26
|
-
line-height:
|
|
25
|
+
min-height: 26.6px;
|
|
26
|
+
line-height: 26.6px;
|
|
27
27
|
font-family: inherit;
|
|
28
28
|
font-size: var(--aia-written-text-font-size, 19px);
|
|
29
29
|
white-space: pre-wrap;
|
|
@@ -40,7 +40,10 @@
|
|
|
40
40
|
--aia-caret-color,
|
|
41
41
|
var(--aia-written-text-color, var(--aia-color-text-default, #fff))
|
|
42
42
|
);
|
|
43
|
-
font-weight:
|
|
43
|
+
font-weight: 250;
|
|
44
|
+
/* Align the text's inline box with the pill list (also vertical-align: middle)
|
|
45
|
+
so they share a vertical center when pills stretch the line box to ~36px. */
|
|
46
|
+
vertical-align: middle;
|
|
44
47
|
}
|
|
45
48
|
|
|
46
49
|
/* Completed params render as inline bold runs. \`:where()\` keeps specificity
|
|
@@ -54,12 +57,19 @@
|
|
|
54
57
|
(a global string), so target it via an attribute selector to bypass
|
|
55
58
|
CSS Modules' class-name hashing. */
|
|
56
59
|
:where(.AIAutocomplete-module_input_IW-P-) strong[class~="magicx-aia-segment--editing"] {
|
|
57
|
-
|
|
58
|
-
outline-offset: 1px;
|
|
60
|
+
background-color: color-mix(in srgb, var(--aia-edit-outline, currentColor) 20%, transparent);
|
|
59
61
|
border-radius: 4px;
|
|
60
62
|
caret-color: transparent;
|
|
61
63
|
}
|
|
62
64
|
|
|
65
|
+
/* In re-edit mode the caret is parked just *before* the bold strong (see
|
|
66
|
+
useContentEditableEditor.ts) \u2014 that means it sits in the parent .input, not
|
|
67
|
+
inside the strong, so the rule above doesn't hide it. Use :has() to hide
|
|
68
|
+
the caret on the whole editor while any completed param is selected. */
|
|
69
|
+
.AIAutocomplete-module_input_IW-P-:has(strong[class~="magicx-aia-segment--editing"]) {
|
|
70
|
+
caret-color: transparent;
|
|
71
|
+
}
|
|
72
|
+
|
|
63
73
|
:where(.AIAutocomplete-module_input_IW-P-) strong[class~="magicx-aia-segment--editing"]::selection {
|
|
64
74
|
background: transparent;
|
|
65
75
|
color: inherit;
|
|
@@ -91,7 +101,8 @@
|
|
|
91
101
|
margin-left: 8px;
|
|
92
102
|
}
|
|
93
103
|
|
|
94
|
-
.AIAutocomplete-module_pillListContainer_h92IA:empty
|
|
104
|
+
.AIAutocomplete-module_pillListContainer_h92IA:empty,
|
|
105
|
+
.AIAutocomplete-module_pillListContainer_h92IA[data-aia-pill-wrapped] {
|
|
95
106
|
margin-left: 0;
|
|
96
107
|
}
|
|
97
108
|
|
|
@@ -119,10 +130,11 @@
|
|
|
119
130
|
display: contents;
|
|
120
131
|
}
|
|
121
132
|
|
|
122
|
-
/* Text shimmer on newly
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
133
|
+
/* Text shimmer on a newly promoted completed param. The shared renderer
|
|
134
|
+
(core/render/renderEditable.ts) stamps the global class names below onto
|
|
135
|
+
the just-added <strong>; we match them via [class~=] to bypass CSS Modules'
|
|
136
|
+
hashing \u2014 same trick as the editing-outline rule above. */
|
|
137
|
+
:where(.AIAutocomplete-module_input_IW-P-) strong[class~="magicx-aia-shimmer-revealed"] {
|
|
126
138
|
color: transparent;
|
|
127
139
|
background: linear-gradient(
|
|
128
140
|
120deg,
|
|
@@ -138,7 +150,7 @@
|
|
|
138
150
|
background-clip: text;
|
|
139
151
|
}
|
|
140
152
|
|
|
141
|
-
.AIAutocomplete-
|
|
153
|
+
:where(.AIAutocomplete-module_input_IW-P-) strong[class~="magicx-aia-shimmer-sweep"] {
|
|
142
154
|
animation: AIAutocomplete-module_textShimmer_eCLdq 650ms ease-out forwards;
|
|
143
155
|
}
|
|
144
156
|
|
|
@@ -150,7 +162,7 @@
|
|
|
150
162
|
background-position: -50% 0;
|
|
151
163
|
}
|
|
152
164
|
}
|
|
153
|
-
`,document.head.appendChild(n)}var
|
|
165
|
+
`,document.head.appendChild(n)}var ee={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",textShimmer:"AIAutocomplete-module_textShimmer_eCLdq"};if(typeof document<"u"&&!document.getElementById("ac-style-2eef895d")){let n=document.createElement("style");n.id="ac-style-2eef895d",n.textContent=`.AIAutocompleteDropdown-module_dropdown_yz2KC {
|
|
154
166
|
position: absolute;
|
|
155
167
|
left: 0;
|
|
156
168
|
right: 0;
|
|
@@ -187,6 +199,15 @@
|
|
|
187
199
|
|
|
188
200
|
.AIAutocompleteDropdown-module_pillBar_pwTXe {
|
|
189
201
|
padding: 27px 27px 0px 27px;
|
|
202
|
+
overflow-x: auto;
|
|
203
|
+
overflow-y: hidden;
|
|
204
|
+
scrollbar-width: none;
|
|
205
|
+
mask-image: linear-gradient(to right, #000 0, #000 calc(100% - 48px), transparent 100%);
|
|
206
|
+
-webkit-mask-image: linear-gradient(to right, #000 0, #000 calc(100% - 48px), transparent 100%);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
.AIAutocompleteDropdown-module_pillBar_pwTXe::-webkit-scrollbar {
|
|
210
|
+
display: none;
|
|
190
211
|
}
|
|
191
212
|
|
|
192
213
|
/* --- Fallback loading skeleton (only when no pills/options are cached) --- */
|
|
@@ -223,7 +244,7 @@
|
|
|
223
244
|
opacity: 0.25;
|
|
224
245
|
}
|
|
225
246
|
}
|
|
226
|
-
`,document.head.appendChild(n)}var
|
|
247
|
+
`,document.head.appendChild(n)}var re={dropdown:"AIAutocompleteDropdown-module_dropdown_yz2KC",visible:"AIAutocompleteDropdown-module_visible_QCoXj",pillBar:"AIAutocompleteDropdown-module_pillBar_pwTXe",skeletonBars:"AIAutocompleteDropdown-module_skeletonBars_HVr9C",skeletonBar:"AIAutocompleteDropdown-module_skeletonBar_O3xIx",aiaSkeletonPulse:"AIAutocompleteDropdown-module_aiaSkeletonPulse_G8W7q"};if(typeof document<"u"&&!document.getElementById("ac-style-b745b4fb")){let n=document.createElement("style");n.id="ac-style-b745b4fb",n.textContent=`.PillList-module_list_qvLqO {
|
|
227
248
|
position: relative;
|
|
228
249
|
z-index: 1;
|
|
229
250
|
pointer-events: auto;
|
|
@@ -306,7 +327,7 @@
|
|
|
306
327
|
opacity: 0;
|
|
307
328
|
}
|
|
308
329
|
}
|
|
309
|
-
`,document.head.appendChild(n)}var
|
|
330
|
+
`,document.head.appendChild(n)}var q={list:"PillList-module_list_qvLqO",pill:"PillList-module_pill_osSyz",fadeIn:"PillList-module_fadeIn_Aezob",rounded:"PillList-module_rounded_WvXy4",skeleton:"PillList-module_skeleton_Lp8x6",skeletonPulse:"PillList-module_skeletonPulse_xZ8Yf",active:"PillList-module_active_Oll--"};var ye=require("react/jsx-runtime"),sn=[125,69];function ut(n){return n===0?.4:n===1?.3:.15}function we({pills:n,activePillIndex:e,onSelectPill:t,rounded:o,loading:i}){return i&&n.length===0?(0,ye.jsx)("span",{className:q.list,"data-aia-pill-list-loading":"",children:sn.map((a,r)=>(0,ye.jsx)("span",{"data-aia-pill-skeleton":"",className:`${q.pill} ${o?q.rounded:""} ${q.skeleton}`,style:{width:a,opacity:ut(r)}},`skel-${a}`))}):(0,ye.jsx)("span",{className:q.list,"data-aia-pill-list-loading":i?"":void 0,children:n.map((a,r)=>(0,ye.jsx)("button",{type:"button","data-aia-pill":"","data-aia-loading":i?"":void 0,tabIndex:-1,contentEditable:!1,suppressContentEditableWarning:!0,className:`${q.pill} ${o?q.rounded:""} ${r===e&&!i?q.active:""} ${i?q.skeleton:""}`,style:{opacity:ut(r)},onMouseDown:s=>s.preventDefault(),onClick:i?void 0:()=>t(r),disabled:i,children:a.text},`${a.type}-${a.text}`))})}var te=require("react");if(typeof document<"u"&&!document.getElementById("ac-style-d91f2b06")){let n=document.createElement("style");n.id="ac-style-d91f2b06",n.textContent=`.SuggestionGrid-module_scrollWrapper_MOqfw {
|
|
310
331
|
position: relative;
|
|
311
332
|
}
|
|
312
333
|
|
|
@@ -361,7 +382,7 @@
|
|
|
361
382
|
background: var(--aia-scrollbar-thumb, rgba(0, 0, 0, 0.3));
|
|
362
383
|
border-radius: 3px;
|
|
363
384
|
}
|
|
364
|
-
`,document.head.appendChild(n)}var
|
|
385
|
+
`,document.head.appendChild(n)}var ot={scrollWrapper:"SuggestionGrid-module_scrollWrapper_MOqfw",grid:"SuggestionGrid-module_grid_jvaPb"};var pe=require("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 {
|
|
365
386
|
position: relative;
|
|
366
387
|
overflow: visible;
|
|
367
388
|
display: flex;
|
|
@@ -703,7 +724,7 @@
|
|
|
703
724
|
filter: brightness(0.55);
|
|
704
725
|
}
|
|
705
726
|
}
|
|
706
|
-
`,document.head.appendChild(n)}var
|
|
727
|
+
`,document.head.appendChild(n)}var G={item:"SuggestionItem-module_item_d4vpD",fadeIn:"SuggestionItem-module_fadeIn_I8u35",content:"SuggestionItem-module_content_T-Qba",tappable:"SuggestionItem-module_tappable_70KcX",nonTappable:"SuggestionItem-module_nonTappable_xSZM-",highlighted:"SuggestionItem-module_highlighted_Hb0SU",tag:"SuggestionItem-module_tag_e3Fwe",pressed:"SuggestionItem-module_pressed_98o-r",glassFade:"SuggestionItem-module_glassFade_oyiSj",tapDown:"SuggestionItem-module_tapDown_G3WGz",streaks:"SuggestionItem-module_streaks_d9PEB",streaksVert:"SuggestionItem-module_streaksVert_ERlV1",streakHorizRight:"SuggestionItem-module_streakHorizRight_aboGz",streakHorizLeft:"SuggestionItem-module_streakHorizLeft_BreWJ",streakVertUp:"SuggestionItem-module_streakVertUp_to1GD",streakVertDown:"SuggestionItem-module_streakVertDown_OrcLh",skeletonPulse:"SuggestionItem-module_skeletonPulse_plvdD"};var ae=require("react/jsx-runtime");function mt({option:n,isHighlighted:e,onSelect:t,onHighlight:o,id:i,loading:a}){let[r,s]=(0,pe.useState)(!1),l=(0,pe.useRef)(void 0);(0,pe.useEffect)(()=>()=>clearTimeout(l.current),[]);let d=()=>{a||!n.is_tappable||r||(s(!0),t(n),clearTimeout(l.current),l.current=setTimeout(()=>s(!1),500))},u=[G.item,e&&!a?G.highlighted:"",n.is_tappable?G.tappable:G.nonTappable,r?G.pressed:""].filter(Boolean).join(" ");return(0,ae.jsxs)("div",{id:i,role:"option","data-aia-option":"","data-aia-loading":a?"":void 0,"aria-selected":e,className:u,tabIndex:a||!n.is_tappable?-1:0,onClick:d,onKeyDown:p=>{!a&&n.is_tappable&&(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),d())},onMouseEnter:!a&&n.is_tappable?o:void 0,children:[(0,ae.jsx)("div",{className:G.streaks}),(0,ae.jsx)("div",{className:G.streaksVert}),(0,ae.jsxs)("span",{className:G.content,children:[n.icon?`${n.icon} ${n.text}`:n.text,n.tag&&(0,ae.jsx)("span",{className:G.tag,children:n.tag})]})]})}var Te=require("react/jsx-runtime");function gt({options:n,activeIndex:e,onSelect:t,onHighlight:o,listboxId:i,loading:a}){let r=(0,te.useRef)(null),[s,l]=(0,te.useState)(!1);return(0,te.useEffect)(()=>{let d=r.current;if(!d)return;let u=()=>{l(d.scrollHeight-d.scrollTop-d.clientHeight>1)};d.addEventListener("scroll",u,{passive:!0});let p=new ResizeObserver(u);return p.observe(d),()=>{d.removeEventListener("scroll",u),p.disconnect()}},[]),(0,te.useLayoutEffect)(()=>{let d=r.current;d&&l(d.scrollHeight-d.scrollTop-d.clientHeight>1)},[n]),(0,Te.jsx)("div",{className:ot.scrollWrapper,"data-fade":s?"":void 0,children:(0,Te.jsx)("div",{ref:r,className:ot.grid,children:n.map((d,u)=>(0,Te.jsx)(mt,{option:d,isHighlighted:u===e,onSelect:t,onHighlight:()=>o(u),id:`${i}-option-${u}`,loading:a},d.text))})})}var Q=require("react/jsx-runtime"),ln=[159,119,164];function _e({suggestions:n,activeIndex:e,onSelect:t,onHighlight:o,isOpen:i,id:a,className:r,pills:s,onPillClick:l,showPills:d=!0,isLoading:u=!1}){let m=n[0]?.options??[],v=d&&s&&s.length>0&&l,g=m.length>0,b=u&&!g,f=i&&(g||v||u);return(0,Q.jsxs)("div",{id:a,role:"listbox","data-aia-dropdown":"","data-aia-loading":u?"":void 0,className:`${re.dropdown} ${f?re.visible:""} ${r??""}`,onMouseDown:c=>c.preventDefault(),children:[d&&s&&s.length>0&&l&&(0,Q.jsx)("div",{className:re.pillBar,"data-aia-pillbar":"",children:(0,Q.jsx)(we,{pills:s,activePillIndex:0,onSelectPill:l,rounded:!0,loading:u})}),d&&(!s||s.length===0)&&u&&(0,Q.jsx)("div",{className:re.pillBar,"data-aia-pillbar":"",children:(0,Q.jsx)(we,{pills:[],activePillIndex:0,onSelectPill:()=>{},rounded:!0,loading:!0})}),g&&(0,Q.jsx)(gt,{options:m,activeIndex:e,onSelect:t,onHighlight:o,listboxId:a,loading:u}),b&&(0,Q.jsx)("div",{className:re.skeletonBars,"data-aia-skeleton-bars":"",children:ln.map(c=>(0,Q.jsx)("span",{className:re.skeletonBar,style:{width:c}},`bar-${c}`))})]})}if(typeof document<"u"&&!document.getElementById("ac-style-dc8da745")){let n=document.createElement("style");n.id="ac-style-dc8da745",n.textContent=`/*
|
|
707
728
|
* Built-in appearance defaults \u2014 zero specificity via :where().
|
|
708
729
|
* Consumer CSS always wins without !important.
|
|
709
730
|
*
|
|
@@ -798,5 +819,5 @@
|
|
|
798
819
|
animation-duration: 0s !important;
|
|
799
820
|
transition-duration: 0s !important;
|
|
800
821
|
}
|
|
801
|
-
`,document.head.appendChild(n)}var vt='[contenteditable="false"]',re;function tn(){if(re!==void 0)return re;let n=globalThis.Intl.Segmenter;if(!n)return re=null,null;try{re=new n(void 0,{granularity:"grapheme"})}catch{re=null}return re??null}function He(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(vt))return!0;t=t.parentNode}return!1}function Be(n){return(n.ownerDocument??document).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return He(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function ae(n){let e=Be(n),t="",o=e.nextNode();for(;o;)t+=o.data,o=e.nextNode();return t}function Fe(n){let e=Be(n),t=0,o=e.nextNode();for(;o;)t+=o.data.length,o=e.nextNode();return t}function F(n){let e=(n.ownerDocument??document).getSelection();if(!e||e.rangeCount===0)return null;let t=e.anchorNode,o=e.anchorOffset;if(!t||!n.contains(t))return null;if(t.nodeType===Node.ELEMENT_NODE){let r=t;if(He(r,n)&&r!==n)return null;let a=0;for(let i=0;i<o&&i<r.childNodes.length;i++)a+=yt(r.childNodes[i],n);return a+xt(r,n)}return t.nodeType!==Node.TEXT_NODE||He(t,n)?null:xt(t,n)+o}function yt(n,e){if(n.nodeType===Node.TEXT_NODE)return He(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(vt))return 0;let o=0;for(let r of Array.from(t.childNodes))o+=yt(r,e);return o}function xt(n,e){let t=Be(e),o=0,r=t.nextNode();for(;r;){if(r===n||n.nodeType===Node.ELEMENT_NODE&&n.contains(r))return o;o+=r.data.length,r=t.nextNode()}return o}function M(n,e){let t=n.ownerDocument??document,o=t.getSelection();if(!o)return;let r=Math.max(0,Math.min(e,Fe(n))),a=Be(n),i=0,s=null,d=0,l=a.nextNode(),p=null;for(;l;){let c=l.data.length;if(r<i+c){s=l,d=r-i;break}if(r===i+c){let h=a.nextNode();h?(s=h,d=0):(s=l,d=c);break}i+=c,p=l,l=a.nextNode()}let u=t.createRange();if(s){let c=s.parentElement?.closest('strong[data-seg="completed"]');c&&c!==n&&n.contains(c)?d===0?u.setStartBefore(c):d===s.data.length?u.setStartAfter(c):u.setStart(s,d):u.setStart(s,d)}else p?u.setStart(p,p.data.length):u.setStart(n,0);u.collapse(!0),o.removeAllRanges(),o.addRange(u)}function wt(n){let e=F(n);return e==null?!1:e>=Fe(n)}function St(n,e){if(e<=0)return 0;let t=tn();if(!t)return e-1;let o=n.slice(0,e),r=0;for(let{index:a}of t.segment(o))a<e&&(r=a);return r}function Ke(n){let{input:e,segments:t,newParamId:o,editingParamId:r,placeholderText:a,isFocused:i}=n,s=t.length===0;e.dataset.aiaEmpty=s?"true":"false",s&&a?e.dataset.placeholder=a:delete e.dataset.placeholder;let d=t.map(f=>`${f.type}:${f.value}`).join("\0"),l=e.dataset.segKey??"",p=e.dataset.newParamId??"",u=e.dataset.editingParamId??"";if(d===l&&(o??"")===p&&(r??"")===u)return;let c=i?F(e):null;e.dataset.segKey=d,e.dataset.newParamId=o??"",e.dataset.editingParamId=r??"";let h=e.ownerDocument??document,b=h.createDocumentFragment(),v=0;for(let f of t)if(v+=f.value.length,f.type==="completed"){let m=h.createElement("strong");m.dataset.seg="completed",m.dataset.paramId=f.param.id;let g=f.param.id===o,w=f.param.id===r,T=["magicx-aia-segment","magicx-aia-segment--completed"];g&&T.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),w&&T.push("magicx-aia-segment--editing"),m.className=T.join(" "),m.textContent=f.value,b.appendChild(m)}else b.appendChild(h.createTextNode(f.value));e.replaceChildren(b),e.dataset.aiaTextLength=String(v),c!=null&&M(e,Math.max(0,Math.min(c,v)))}var P=require("react");function H(n,e){let t=n,o={},r=[];for(let a of e){let i=(o[a.type]??0)+1;o[a.type]=i;let d=`{{${a.type.toUpperCase().replace(/\s+/g,"_")}_${i}}}`,l=t.indexOf(a.text);l!==-1&&(t=t.slice(0,l)+d+t.slice(l+a.text.length)),r.push({...a,placeholder:d})}return{rawQuery:t,completedParams:r}}function xe(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function se(n,e,t){let o=n.slice(e);if(t||e===0||n[e-1]===" ")return o;let r=o.indexOf(" ");return r===-1?"":o.slice(r+1)}function Pt(n,e){let t=n.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let o=t.split(" "),r=e.toLowerCase();for(let a=0;a<o.length;a++){let i=o.slice(a).join(" ");if(r.startsWith(i.toLowerCase())){let s=t.length-i.length;return n.length-s}}return 0}function ve(n,e){if(!n)return[];let t=e.trimStart();if(!t)return n;let o=t.toLowerCase();return n.filter(r=>!r.is_tappable||r.text.toLowerCase().includes(o))}function le(n,e){if(!n)return null;let t=e.trim();if(!t)return null;let o=t.toLowerCase();return n.find(r=>r.is_tappable&&r.text.toLowerCase()===o)??null}var de=class{constructor(e,t="auto"){this.container=e;this.mode=t;this.mediaQuery=null;this.onSystemChange=e=>{this.container.dataset.mode=e.matches?"dark":"light"};this.apply()}setMode(e){this.detachListener(),this.mode=e,this.apply()}destroy(){this.detachListener()}apply(){this.mode==="auto"?(this.mediaQuery??(this.mediaQuery=window.matchMedia("(prefers-color-scheme: dark)")),this.mediaQuery.addEventListener("change",this.onSystemChange),this.container.dataset.mode=this.mediaQuery.matches?"dark":"light"):this.container.dataset.mode=this.mode}detachListener(){this.mediaQuery?.removeEventListener("change",this.onSystemChange)}};function It(n,e){let t=[],o=0;for(let a of e){let i=n.indexOf(a.text,o);i!==-1&&(i>o&&t.push({type:"text",value:n.slice(o,i)}),t.push({type:"completed",value:a.text,param:a}),o=i+a.text.length)}let r=n.slice(o);return r&&t.push({type:"text",value:r}),t}function At(n,e){let t=[],o=[],r=0;for(let a of e){let i=n.indexOf(a.text,r);i===-1?o.push(a):(t.push(a),r=i+a.text.length)}return{valid:t,invalid:o}}var ze=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;this.inFlightRefresh=null;e.accessToken&&(this.current=e.accessToken)}async getToken(e=!1){if(!e&&this.current&&!this.isExpired())return this.current;if(!e&&this.inFlightRefresh)return this.inFlightRefresh;this.inFlightRefresh=this.refresh();try{return await this.inFlightRefresh}finally{this.inFlightRefresh=null}}async refresh(){let e=await this.config.getAccessToken();return this.current=e.accessToken,this.expiresAt=e.expiresAt??null,this.current}isExpired(){return this.expiresAt==null?!1:Date.now()>=this.expiresAt-3e4}};var nn="https://api.ai-autocomplete.com",We=`${nn}/api/suggest`,Ct=new WeakMap;function ye(n){return n?.type==="accessToken"}function on(n){if(!(!n||ye(n)))return n}function $e(n){let e=Ct.get(n.getAccessToken);return e||(e=new ze(n),Ct.set(n.getAccessToken,e)),e}function qe(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function Ue(n){let e=on(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}function rn(n){return(n??We).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function an(n){return ye(n)?`Bearer ${await $e(n).getToken()}`:Ue(n)}async function Tt(n){try{let e=rn(n.apiConfig?.endpoint),t=qe(n.apiConfig),o=await an(n.apiConfig);o&&(t.Authorization=o);let r=JSON.stringify({source:n.source,session_id:n.sessionId,type:n.type,at:new Date().toISOString(),query_data:n.queryData});await fetch(e,{method:"POST",headers:t,body:r})}catch{}}var sn="0.1.41",_t=!1;function ln(){return crypto.randomUUID()}function dn(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.text},kind:n.kind}}function cn(n,e,t,o){let r=e.find(i=>i.type==="contact"&&i.metadata?.contact_account_count)?.metadata?.contact_account_count,a=typeof r=="number"?r:void 0;return{data:{raw_query:n,completed_params:e.map(i=>dn(i,t)),...a!=null&&{contact_account_count:a}},meta:{request_id:ln(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:sn,session_id:o}}}async function Et(n,e,t,o,r){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:o,signal:r})}async function kt(n,e,t){let o=t.apiConfig,r=!t.maskCompletedText,a=cn(n,e,r,t.sessionId),i=qe(o),s=o?.endpoint??We,d=JSON.stringify(a);if(ye(o)){let u=$e(o),c=await u.getToken(),h=await Et(s,i,c,d,t.signal);if(h.status===401){let b=await u.getToken(!0);h=await Et(s,i,b,d,t.signal)}if(!h.ok)throw new Error(`API error: ${h.status} ${h.statusText}`);return h.json()}let l=Ue(o);!l&&!_t&&(_t=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),l&&(i.Authorization=l);let p=await fetch(s,{method:"POST",headers:i,body:d,signal:t.signal});if(!p.ok)throw new Error(`API error: ${p.status} ${p.statusText}`);return p.json()}function Ot(n,e){return e?n.map(t=>{let o=e[t.type];if(!o)return t;let r=o("");if(r.length===0)return t;let a=new Set(r.map(s=>s.text)),i=(t.options??[]).filter(s=>!a.has(s.text));return{...t,options:[...r,...i]}}):n}var pn=100,un=300,mn=2,Ge=class{constructor(e,t,o,r,a,i,s={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=o;this.getMaskCompletedText=r;this.getOnError=a;this.getSessionId=i;this.callbacks=s;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null}start(){this.doFetch("",[]);let e=this.store.get().text,t=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(o=>{(o.text!==e||o.completedParams!==t)&&(e=o.text,t=o.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let o=new AbortController;this.abortController=o;let r=++this.fetchVersion,a=this.store.get().text.length;this.store.set({isLoading:!0,error:null});try{let i=await kt(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:o.signal,apiConfig:this.getApiConfig()});if(r!==this.fetchVersion)return;let s=Ot(i.data.suggestions??[],this.getOptionOverrides()),d=i.data.input??[],l=d[d.length-1],p=this.store.get().text,u,c;if(l?.state==="in_progress"){c=!0;let f=p.toLowerCase().lastIndexOf(l.text.toLowerCase());u=f!==-1?f:a}else c=!1,u=a;let b=s.filter(f=>f.type!=="placeholder")[0],v=null;if(b){let f=se(p,u,c),m=le(b.options,f);m&&(v={id:crypto.randomUUID(),placeholder:"",type:b.type,text:m.text,kind:m.kind,suggestionType:b.type,suggestionPlaceholder:b.text,options:b.options??[],metadata:m.metadata},s=s.filter(g=>g!==b),this.callbacks.onAutoMatch?.({active:b,matched:m,rawQuery:e}))}this.store.set(f=>({suggestions:s,isLoading:!1,isReady:i.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:u,filterInProgress:c,...v?{completedParams:[...f.completedParams,v]}:{}}))}catch(i){if(r===this.fetchVersion){let s=i instanceof Error?i:new Error(String(i));this.store.set({error:s,isLoading:!1}),this.getOnError()?.(s)}}}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}let t=o=>{let r=this.store.get();if(!r.text&&r.completedParams.length===0)return this.doFetch("",[]),!0;let a=r.suggestions.filter(g=>g.type==="placeholder").map(g=>g.text).join(" "),i=xe(r.text,r.filterBase,a),s=se(r.text,i,r.filterInProgress),l=r.suggestions.filter(g=>g.type!=="placeholder")[0],u=(l?ve(l.options,s):[]).filter(g=>g.is_tappable),c=l?le(l.options,s)!==null:!1,h=s.trim().length>0;if(u.length>0&&!c&&h||r.completedParams.length===0&&r.text.length>0&&a.length>0&&a.toLowerCase().startsWith(r.text.toLowerCase()))return!1;let{rawQuery:b,completedParams:v}=H(r.text,r.completedParams),f=b.length<r.lastRawQuery.length,m=Math.abs(b.length-r.lastRawQuery.length);return f||m>=o?(this.doFetch(b,v),!0):!1};this.debounceTimer=setTimeout(()=>{t(mn)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},pn),this.slowDebounceTimer=setTimeout(()=>t(1),un)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};function Dt(n){return n instanceof HTMLTextAreaElement||n instanceof HTMLInputElement?n.selectionStart!=null&&n.selectionStart===n.value.length:n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?wt(n):!1}function gn(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?F(n):null}var Qe=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:o,getOnSubmit:r}=this.ctx,a=this.getEffectiveColumns(),i=r(),s=this.getTappableIndices(a);switch(e.key){case"ArrowDown":{let d=Dt(e.target),l=!!t.editingParam;if(!d&&!l&&t.activeDropdownIndex<0)break;if(e.preventDefault(),!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:s[0]??0});break}if(s.length===0)return;let p=s.indexOf(t.activeDropdownIndex),u=p<s.length-1?p+1:0;this.store.set({activeDropdownIndex:s[u]});break}case"ArrowUp":{if(s.length===0||t.activeDropdownIndex<0)break;if(e.preventDefault(),t.activeDropdownIndex<a){this.store.set({activeDropdownIndex:-1});break}let d=s.indexOf(t.activeDropdownIndex),l=d>0?d-1:s.length-1;this.store.set({activeDropdownIndex:s[l]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%a<a-1){let p=t.activeDropdownIndex+1;p<t.filteredOptions.length&&t.filteredOptions[p]?.is_tappable&&this.store.set({activeDropdownIndex:p})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let l=e.target.closest("[data-aia-input]")??e.target,p=t.editingTail;this.ctx.exitEditMode?.(),M(l,p);break}Dt(e.target)&&t.actionableSuggestions.length>1&&(e.preventDefault(),this.pillsSetActivePill(1));break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%a>0){let d=t.activeDropdownIndex-1;d>=0&&t.filteredOptions[d]?.is_tappable&&this.store.set({activeDropdownIndex:d})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let d=e.target.closest("[data-aia-input]")??e.target,l=t.editingAnchor;this.ctx.exitEditMode?.(),M(d,l);break}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let d=gn(e.target);if(d==null)break;this.ctx.removeParamAtCaret(d)&&e.preventDefault();break}case"Enter":{if(e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable)this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,o);else if(i){let{rawQuery:d,completedParams:l}=H(t.text,t.completedParams);i({query:t.text.trim(),raw_query:d,completed_params:l}),this.ctx.afterSubmit?.()}break}case"Tab":{let d=!t.text&&!!t.placeholderText,l=t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable;if(d&&!l){e.preventDefault();let p=t.placeholderText;if(this.store.set(u=>({text:p,filterBase:p.length,suggestions:u.suggestions.filter(c=>c.type!=="placeholder")})),e.target instanceof HTMLElement){let u=e.target.closest("[data-aia-input]")??e.target;queueMicrotask(()=>M(u,p.length))}}else if(l)e.preventDefault(),this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,o);else if(t.isDropdownOpen){let p=t.filteredOptions.findIndex(u=>u.is_tappable);p>=0&&(e.preventDefault(),this.clickOrSelect(p,t.filteredOptions,o))}break}case"Escape":{if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){let d=e.target.closest("[data-aia-input]")??e.target,l=t.editingTail;this.ctx.exitEditMode?.(),M(d,l)}this.store.set({activeDropdownIndex:-1});break}}}getTappableIndices(e){let o=this.store.get().filteredOptions.map((a,i)=>a.is_tappable?i:-1).filter(a=>a!==-1),r=Array.from({length:e},()=>[]);for(let a of o)r[a%e].push(a);return r.flat()}getEffectiveColumns(){let t=document.getElementById(`${this.ctx.listboxId}-option-0`)?.parentElement;if(!t)return this.ctx.columns;let o=getComputedStyle(t).gridTemplateColumns.split(" ").filter(Boolean).length;return o>0?o:this.ctx.columns}clickOrSelect(e,t,o){let r=document.getElementById(`${o}-option-${e}`);r?r.click():this.ctx.selectOption(t[e])}pillsSetActivePill(e){let t=this.store.get(),o=t.suggestions.filter(s=>s.type!=="placeholder");if(e<0||e>=o.length)return;let r=o[e],a=o.filter((s,d)=>d!==e),i=t.suggestions.filter(s=>s.type==="placeholder");this.store.set({suggestions:[...i,r,...a],pillTapped:!0,activeDropdownIndex:-1})}};var je=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),o=t.suggestions.filter(s=>s.type!=="placeholder");if(e<0||e>=o.length)return;let r=o[e],a=o.filter((s,d)=>d!==e),i=t.suggestions.filter(s=>s.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:s}=H(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:s,selectedPill:r.text,otherPills:a.map(d=>d.text)})}this.store.set({suggestions:[...i,r,...a],pillTapped:!0,activeDropdownIndex:-1})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};var Lt=[125,69];function Mt(n){return n===0?.4:n===1?.3:.15}function Ve(n,e,t,o,r=!1,a=!1){let i=n.querySelector(".magicx-aia-pill-list");if(i||(i=document.createElement("span"),i.className="magicx-aia-pill-list",n.appendChild(i)),a&&e.length===0){i.setAttribute("data-aia-pill-list-loading",""),i.innerHTML="";for(let l=0;l<Lt.length;l++){let p=Lt[l],u=document.createElement("span");u.setAttribute("data-aia-pill-skeleton",""),u.className=`magicx-aia-pill magicx-aia-pill--skeleton${r?" magicx-aia-pill--rounded":""}`,u.style.width=`${p}px`,u.style.opacity=String(Mt(l)),i.appendChild(u)}return}a?i.setAttribute("data-aia-pill-list-loading",""):i.removeAttribute("data-aia-pill-list-loading");for(let l of i.querySelectorAll("[data-aia-pill-skeleton]"))l.remove();let s=new Map;for(let l of i.querySelectorAll(".magicx-aia-pill"))s.set(l.dataset.pillKey??"",l);let d=new Set;for(let l=0;l<e.length;l++){let p=e[l],u=`${p.type}-${p.text}`;d.add(u);let c=s.get(u);(!c||c.tagName!=="BUTTON")&&(c?.remove(),c=document.createElement("button"),c.type="button",c.tabIndex=-1,c.dataset.pillKey=u,c.setAttribute("data-aia-pill",""),c.setAttribute("contenteditable","false"),c.textContent=p.text,c.addEventListener("mousedown",b=>b.preventDefault()));let h=["magicx-aia-pill"];r&&h.push("magicx-aia-pill--rounded"),l===t&&!a&&h.push("magicx-aia-pill--active"),a&&h.push("magicx-aia-pill--skeleton"),c.className=h.join(" "),c.style.width="",c.style.opacity=String(Mt(l)),a?(c.setAttribute("data-aia-loading",""),c.disabled=!0,c.onclick=null):(c.removeAttribute("data-aia-loading"),c.disabled=!1,c.onclick=()=>o(l)),i.children[l]!==c&&i.insertBefore(c,i.children[l]??null)}for(let[l,p]of s)d.has(l)||p.remove()}function pt(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var fn=[159,119,164];function Xe(n){let e=document.createElement("div");return e.id=n,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",t=>t.preventDefault()),e}function Je(n,e){let{filteredOptions:t,activeIndex:o,isOpen:r,isLoading:a,pills:i,showPills:s,onSelect:d,onHighlight:l,onPillClick:p}=e,u=s&&i.length>0,c=t.length>0;r&&(c||u||a)?n.classList.add("magicx-aia-dropdown--visible"):n.classList.remove("magicx-aia-dropdown--visible"),a?n.setAttribute("data-aia-loading",""):n.removeAttribute("data-aia-loading");let b=u||a&&s,v=n.querySelector(".magicx-aia-pill-bar");b?(v||(v=document.createElement("div"),v.className="magicx-aia-pill-bar",v.setAttribute("data-aia-pillbar",""),n.insertBefore(v,n.firstChild)),Ve(v,i,0,p,!0,a)):v&&v.remove();let f=n.querySelector(".magicx-aia-grid");c?(f||(f=document.createElement("div"),f.className="magicx-aia-grid",n.appendChild(f)),hn(f,t,o,d,l,e.listboxId,a)):f&&f.remove();let m=n.querySelector(".magicx-aia-skeleton-bars");if(a&&!c){if(!m){m=document.createElement("div"),m.className="magicx-aia-skeleton-bars",m.setAttribute("data-aia-skeleton-bars","");for(let g of fn){let w=document.createElement("span");w.className="magicx-aia-skeleton-bar",w.style.width=`${g}px`,m.appendChild(w)}n.appendChild(m)}}else m&&m.remove()}function hn(n,e,t,o,r,a,i){let s=e.map(c=>c.text).join("\0"),d=n.dataset.optionsKey??"",l=n.dataset.loading??"",p=i?"1":"0",u=s!==d||l!==p;if(n.dataset.optionsKey=s,n.dataset.loading=p,u){let c=document.createDocumentFragment();for(let h=0;h<e.length;h++){let b=e[h],v=bn(b,h,t,o,r,a,i);c.appendChild(v)}n.innerHTML="",n.appendChild(c)}else{let c=n.querySelectorAll(".magicx-aia-option");for(let h=0;h<c.length;h++){let b=c[h],v=h===t&&!i;b.setAttribute("aria-selected",String(v)),v?b.classList.add("magicx-aia-option--highlighted"):b.classList.remove("magicx-aia-option--highlighted")}}}function bn(n,e,t,o,r,a,i){let s=document.createElement("div");s.id=`${a}-option-${e}`,s.setAttribute("role","option"),s.setAttribute("data-aia-option",""),i&&s.setAttribute("data-aia-loading",""),s.setAttribute("aria-selected",String(e===t&&!i)),s.tabIndex=i||!n.is_tappable?-1:0;let d=["magicx-aia-option"];e===t&&!i&&d.push("magicx-aia-option--highlighted"),n.is_tappable?d.push("magicx-aia-option--tappable"):d.push("magicx-aia-option--non-tappable"),s.className=d.join(" ");let l=document.createElement("div");l.className="magicx-aia-streaks",s.appendChild(l);let p=document.createElement("div");p.className="magicx-aia-streaks-vert",s.appendChild(p);let u=document.createElement("span");if(u.className="magicx-aia-option-content",u.textContent=n.icon?`${n.icon} ${n.text}`:n.text,n.tag){let c=document.createElement("span");c.className="magicx-aia-option-tag",c.textContent=n.tag,u.appendChild(c)}return s.appendChild(u),!i&&n.is_tappable&&(s.addEventListener("click",()=>{s.classList.add("magicx-aia-option--pressed"),o(n),setTimeout(()=>s.classList.remove("magicx-aia-option--pressed"),500)}),s.addEventListener("mouseenter",()=>r(e))),s}function Rt(n,e){let t=Xe(e.listboxId);return n.appendChild(t),{dropdown:t}}function ut(n,e,t){Je(n.dropdown,{suggestions:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,onSelect:t.selectOption,onHighlight:o=>t.store.set({activeDropdownIndex:o}),onPillClick:t.setActivePill})}var xn='<svg width="18" height="18" viewBox="0 0 18 18" fill="none" role="img" aria-label="Submit"><path d="M9 14V4M9 4L4 9M9 4L14 9" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';function vn(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function Nt(n,e){let{listboxId:t}=e,o=Xe(t);n.appendChild(o);let r=document.createElement("div");r.className="magicx-aia-input-wrapper",n.appendChild(r);let a=document.createElement("div");a.className="magicx-aia-editor",a.setAttribute("data-aia-editor",""),r.appendChild(a);let i=document.createElement("div");i.className="magicx-aia-input",i.setAttribute("data-aia-input",""),i.setAttribute("contenteditable",vn()?"plaintext-only":"true"),i.setAttribute("role","combobox"),i.setAttribute("aria-autocomplete","list"),i.setAttribute("aria-haspopup","listbox"),i.setAttribute("aria-controls",t),i.setAttribute("aria-expanded","false"),i.setAttribute("spellcheck","true"),i.setAttribute("enterkeyhint","send"),a.appendChild(i);let s=document.createElement("span");s.className="magicx-aia-pill-list-container",s.setAttribute("data-aia-pill-list-container",""),a.appendChild(s);let d=null,l=null;e.submitButton===void 0?(d=document.createElement("button"),d.type="button",d.className="magicx-aia-submit",d.setAttribute("aria-label","Submit"),d.setAttribute("data-aia-submit",""),d.innerHTML=xn,r.appendChild(d),l=d):e.submitButton!==null&&(l=e.submitButton,l.hasAttribute("data-aia-submit")||l.setAttribute("data-aia-submit",""),r.appendChild(l));let p=new AbortController,{signal:u}=p,c=!1,h=0,b=()=>{let m=ae(i),w=m.length>0&&m[0]!==m[0].toUpperCase()?m[0].toUpperCase()+m.slice(1):m;e.handleChange(w)},v=()=>{let m=(i.ownerDocument??document).getSelection();if(!m||m.rangeCount===0)return null;let g=m.anchorNode;return!g||!i.contains(g)?null:(g.nodeType===Node.ELEMENT_NODE?g:g.parentElement)?.closest('strong[data-seg="completed"][data-param-id]')?.dataset.paramId??null};r.addEventListener("click",m=>{m.target?.closest("[data-aia-pill]")||i.focus()},{signal:u}),i.addEventListener("input",()=>{c||(h=performance.now(),b(),e.handleCaretAfterInput(F(i)))},{signal:u});let f=i.ownerDocument??document;return f.addEventListener("selectionchange",()=>{let m=f.getSelection();if(!m||m.rangeCount===0||!i.contains(m.anchorNode))return;let g=v(),w=e.store.get().editingParam?.id??null;if(g&&g!==w){e.startEditingParam(g);return}performance.now()-h<50||e.handleCaretMove(F(i))},{signal:u}),i.addEventListener("compositionstart",()=>{c=!0},{signal:u}),i.addEventListener("compositionend",()=>{c=!1,b()},{signal:u}),i.addEventListener("beforeinput",m=>{let g=m,w=g.inputType;if(w==="insertParagraph"||w==="insertLineBreak"||w==="insertFromDrop"){m.preventDefault();return}if(w.startsWith("insert")||w.startsWith("delete")){let T=w.startsWith("delete")?"":g.data??"";e.replaceEditingRange(T)&&m.preventDefault()}},{signal:u}),i.addEventListener("paste",m=>{m.preventDefault();let g=(m.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!g)return;let w=i.ownerDocument??document,T=w.getSelection();if(!T||T.rangeCount===0)return;let O=T.getRangeAt(0);if(!i.contains(O.startContainer))return;O.deleteContents();let U=w.createTextNode(g);O.insertNode(U),O.setStartAfter(U),O.collapse(!0),T.removeAllRanges(),T.addRange(O),b()},{signal:u}),i.addEventListener("keydown",m=>e.handleKeyDown(m),{signal:u}),i.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:u}),i.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:u}),l&&l.addEventListener("click",m=>{let g=e.store.get();if(!(!!g.text||g.completedParams.length>0)||!e.onSubmit)return;m.stopPropagation();let{rawQuery:T,completedParams:O}=H(g.text,g.completedParams);e.onSubmit({query:g.text.trim(),raw_query:T,completed_params:O}),e.afterSubmit?.()},{signal:u}),e.autoFocus!==!1&&i.focus(),{input:i,inlinePillContainer:s,dropdown:o,submitButton:d,abort:p}}function mt(n,e,t){let{input:o,inlinePillContainer:r,dropdown:a,submitButton:i}=n,{pillPlacement:s,setActivePill:d,selectOption:l,store:p}=t;o.setAttribute("aria-expanded",String(e.isDropdownOpen));let u=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(u?o.setAttribute("aria-activedescendant",u):o.removeAttribute("aria-activedescendant"),i){let f=!!e.text||e.completedParams.length>0;i.disabled=!f}let c=o.dataset.newParamId??"",h=e.newParamId!==null&&e.newParamId!==c;if(Ke({input:o,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused}),s==="inline"){let f=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;f||e.actionableSuggestions.length>0?Ve(r,e.actionableSuggestions,0,d,!1,f):pt(r)}else pt(r);h?(o.focus(),M(o,e.caretOffset??e.text.length)):e.isFocused&&ae(o)!==e.text&&M(o,e.text.length);let b=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:null,v=b??e.actionableSuggestions[0];Je(a,{suggestions:v?[{...v,options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation,listboxId:t.listboxId,pills:b?[b]:e.actionableSuggestions,showPills:s==="dropdown",onSelect:l,onHighlight:f=>p.set({activeDropdownIndex:f}),onPillClick:d})}function Ht(n){let e=n,t=new Set;return{get:()=>e,set:o=>{let r=typeof o=="function"?o(e):o,a={...e,...r},i=e;e=a;for(let s of t)s(a,i)},subscribe:o=>(t.add(o),()=>{t.delete(o)})}}var gt=!1;function Bt(){if(gt||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){gt=!0;return}gt=!0;let n=document.createElement("style");n.setAttribute("data-magicx-aia",""),n.textContent=yn,document.head.appendChild(n)}var yn="";var wn=0;function Sn(){return`:ac-${++wn}:`}var Ft=500;function Kt(){return{text:"",completedParams:[],suggestions:[],activeDropdownIndex:-1,newParamId:null,isLoading:!1,isReady:!1,error:null,segments:[],actionableSuggestions:[],filteredOptions:[],placeholderText:"",isDropdownOpen:!1,filterBase:0,filterInProgress:!1,pillTapped:!1,skipNextFetch:!1,lastRawQuery:"",isFocused:!1,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:null,inSelectionAnimation:!1}}var Ye=class{constructor(e,t={}){this.store=Ht(Kt());this._listboxId=Sn();this.modeController=null;this.unsubscribers=[];this.derivedInProgress=!1;this.domRefs=null;this.dropdownRefs=null;this.externalListeners=new Set;this.sessionId=crypto.randomUUID();this.container=e,this.opts=t,this.renderMode=t.renderMode??"full",t.value!==void 0&&this.store.set({text:t.value}),t.completedParams!==void 0&&this.store.set({completedParams:t.completedParams}),this.pillsController=new je(this.store,{onPillSelected:({rawQuery:o,selectedPill:r,otherPills:a})=>{this.fireTelemetry("pill",{raw_query:o,selected_pill:r,other_pills:a})}}),this.fetchController=new Ge(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.opts.onError,()=>this.sessionId,{onAutoMatch:({active:o,matched:r,rawQuery:a})=>{this.fireTelemetry("option",{raw_query:a,selected_option:r.text,other_options:(o.options??[]).filter(i=>i.text!==r.text).map(i=>i.text)})}}),this.keyboardController=new Qe(this.store,{columns:t.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.opts.onSubmit,afterSubmit:this.renderMode==="full"?()=>this.reset():void 0,selectOption:o=>this.selectOption(o),removeParamAtCaret:o=>this.removeParamAtCaret(o),exitEditMode:()=>this.exitEditMode()}),this.unsubscribers.push(this.store.subscribe((o,r)=>{this.recomputeDerived(o,r)})),this.unsubscribers.push(this.store.subscribe((o,r)=>{o.text!==r.text&&this.opts.onChange?.(o.text),o.completedParams!==r.completedParams&&this.opts.onParamsChange?.(o.completedParams),o.isFocused!==r.isFocused&&(o.isFocused?this.opts.onFocus?.():this.opts.onBlur?.()),this.opts.onStateChange?.(o)})),this.renderMode!=="headless"&&(Bt(),this.setupContainer()),this.renderMode==="full"?this.buildAndRenderFull():this.renderMode==="dropdown"&&this.buildAndRenderDropdown(),this.fetchController.start()}focus(){this.domRefs?.input.focus()}blur(){this.domRefs?.input.blur()}reset(){this.store.set({...Kt(),skipNextFetch:!0}),this.sessionId=crypto.randomUUID(),this.fetchController.doFetch("",[])}destroy(){this.fetchController.dispose(),this.modeController?.destroy(),this.newParamTimer&&clearTimeout(this.newParamTimer),this.suggestionRemovalTimer&&clearTimeout(this.suggestionRemovalTimer),this.selectionAnimationTimer&&clearTimeout(this.selectionAnimationTimer),this.externalListeners.clear();for(let e of this.unsubscribers)e();this.unsubscribers=[],this.domRefs?.abort.abort(),this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}setValue(e){this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e)}removeLastParam(){this.pillsController.removeLastParam()}removeParamAtCaret(e){let t=this.store.get(),{text:o,completedParams:r}=t,a=0;for(let i=0;i<r.length;i++){let s=r[i],d=o.indexOf(s.text,a);if(d===-1)continue;let l=d,p=d+s.text.length;if(e>l&&e<=p){let u=St(o,e),c=o.slice(0,u)+o.slice(e),h=r.filter((b,v)=>v!==i);return this.store.set(b=>({text:c,filterBase:Math.min(b.filterBase,c.length),completedParams:h,pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(u),!0}a=p}return!1}scheduleSetCursor(e){queueMicrotask(()=>{let t=this.domRefs;t?M(t.input,e):this.opts.setCursor?.(e)})}clearNewParamId(){this.store.set({newParamId:null})}startEditingParam(e){let t=this.store.get();if(t.editingParam?.id===e)return;let o=t.completedParams.find(i=>i.id===e);if(!o)return;let r=0,a=-1;for(let i of t.completedParams){let s=t.text.indexOf(i.text,r);if(s!==-1){if(i.id===e){a=s;break}r=s+i.text.length}}a<0||this.store.set({editingParam:o,editingAnchor:a,editingTail:a+o.text.length,caretOffset:a+o.text.length,activeDropdownIndex:-1})}replaceEditingRange(e){let t=this.store.get(),o=t.editingParam,r=t.editingAnchor,a=t.editingTail;if(!o||r==null||a==null||!t.completedParams.some(d=>d.id===o.id))return!1;let i=t.text.slice(0,r)+e+t.text.slice(a),s=r+e.length;return this.store.set(d=>({text:i,completedParams:d.completedParams.filter(l=>l.id!==o.id),editingTail:s,caretOffset:s,activeDropdownIndex:-1})),this.scheduleSetCursor(s),this.maybePromoteEditExactMatch(),!0}exitEditMode(){this.store.get().editingParam&&this.store.set({editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1})}handleCaretAfterInput(e){let t=this.store.get(),o={caretOffset:e};t.editingParam&&t.editingAnchor!=null&&e!=null&&(e<t.editingAnchor?(o.editingParam=null,o.editingAnchor=null,o.editingTail=null,o.activeDropdownIndex=-1):t.editingTail!=null&&(o.editingTail=Math.max(t.editingTail,e))),this.store.set(o),this.maybePromoteEditExactMatch()}handleCaretMove(e){let t=this.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null&&e!=null&&(e<t.editingAnchor||e>t.editingTail)){this.store.set({caretOffset:e,editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1});return}this.store.set({caretOffset:e})}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}handleTextChange(e){this.handleChange(e)}handleKeyDown(e){this.keyboardController.handleKeyDown(e)}setFocused(e){this.store.get().isFocused!==e&&this.store.set({isFocused:e})}subscribe(e){return this.externalListeners.add(e),()=>{this.externalListeners.delete(e)}}getState(){return this.store.get()}get listboxId(){return this._listboxId}get isReady(){return this.store.get().isReady}on(e,t){switch(e){case"submit":return this.opts.onSubmit=t,()=>{this.opts.onSubmit=void 0};case"error":return this.opts.onError=t,()=>{this.opts.onError=void 0};case"change":return this.opts.onChange=t,()=>{this.opts.onChange=void 0};case"paramsChange":return this.opts.onParamsChange=t,()=>{this.opts.onParamsChange=void 0};case"stateChange":return this.opts.onStateChange=t,()=>{this.opts.onStateChange=void 0};case"focus":return this.opts.onFocus=t,()=>{this.opts.onFocus=void 0};case"blur":return this.opts.onBlur=t,()=>{this.opts.onBlur=void 0};default:return()=>{}}}update(e){Object.assign(this.opts,e),e.mode!==void 0&&this.modeController?.setMode(e.mode),e.optionsPosition!==void 0&&(this.container.dataset.optionsPosition=e.optionsPosition),e.animations!==void 0&&(this.container.dataset.animations=e.animations?"on":"off"),e.pillPlacement!==void 0&&(this.container.dataset.pillPlacement=e.pillPlacement,this.store.set({})),(e.dropdownTrigger!==void 0||e.closeDropdownOnBlur!==void 0)&&this.store.set({}),e.value!==void 0&&this.store.set({text:e.value}),e.completedParams!==void 0&&this.store.set({completedParams:e.completedParams})}selectOption(e){let t=this.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null){this.selectOptionInEditMode(e);return}let o=t.actionableSuggestions[0];if(!o)return;let{rawQuery:r}=H(t.text,t.completedParams);this.fireTelemetry("option",{raw_query:r,selected_option:e.text,other_options:t.filteredOptions.filter(m=>m.text!==e.text).map(m=>m.text)});let a=t.filterBase,i=t.text.slice(0,a),s=i.length===0&&t.text.length===0,d=i.length===0&&t.text.length>0&&t.placeholderText.length>0&&t.placeholderText.toLowerCase().startsWith(t.text.toLowerCase());(s||d)&&t.placeholderText&&(i=`${t.placeholderText} `);let l=Pt(i,e.text);l>0&&(i=i.slice(0,i.length-l));let p=i.length>0&&i[i.length-1]!==" ",u=`${i}${p?" ":""}${e.text} `,c=(s||d)&&u.length>0?u[0].toUpperCase()+u.slice(1):u,h=c.toLowerCase().lastIndexOf(e.text.toLowerCase()),b=h>=0?c.slice(h,h+e.text.length):e.text,v={id:crypto.randomUUID(),placeholder:"",type:o.type,text:b,kind:e.kind,suggestionType:o.type,suggestionPlaceholder:o.text,options:o.options??[],metadata:e.metadata},f=t.actionableSuggestions.length-1;this.store.set(m=>({text:c,filterBase:c.length,completedParams:[...m.completedParams,v],newParamId:v.id,caretOffset:c.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:f>0,inSelectionAnimation:!0})),this.startSelectionAnimationTimer(),this.suggestionRemovalTimer&&clearTimeout(this.suggestionRemovalTimer),f>0&&(this.suggestionRemovalTimer=window.setTimeout(()=>{this.store.set(m=>({suggestions:m.suggestions.filter(g=>g!==o)}))},Ft))}startSelectionAnimationTimer(){this.selectionAnimationTimer&&clearTimeout(this.selectionAnimationTimer),this.selectionAnimationTimer=window.setTimeout(()=>{this.store.set({inSelectionAnimation:!1})},Ft)}selectOptionInEditMode(e){let t=this.store.get(),o=t.editingParam,r=t.editingAnchor,a=t.editingTail;if(!o||r==null||a==null)return;this.fireTelemetry("option",{raw_query:H(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:o.options.filter(m=>m.text!==e.text).map(m=>m.text)});let i=t.text.slice(0,r),s=t.text.slice(a),d=r===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,l=s.length===0||s[0]!==" ",p=l?`${d} `:d,u=i+p+s,c=r+p.length+(l?0:1),h={id:crypto.randomUUID(),placeholder:"",type:o.suggestionType,text:d,kind:e.kind,suggestionType:o.suggestionType,suggestionPlaceholder:o.suggestionPlaceholder,options:o.options,metadata:e.metadata},b=t.completedParams.findIndex(m=>m.id===o.id),v=t.completedParams.filter(m=>m.id!==o.id),f=b>=0?Math.min(b,v.length):v.length;v.splice(f,0,h),this.store.set({text:u,completedParams:v,newParamId:h.id,filterBase:c,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:c,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.startSelectionAnimationTimer(),this.scheduleSetCursor(c)}fireTelemetry(e,t){let o=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");Tt({source:o,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}recomputeDerived(e,t){if(this.derivedInProgress)return;this.derivedInProgress=!0;let o=It(e.text,e.completedParams),r=e.suggestions.filter(g=>g.type!=="placeholder"),a=r[0],i=a?this.opts.optionOverrides?.[a.type]:void 0,s=e.suggestions.filter(g=>g.type==="placeholder").map(g=>g.text).join(" "),d=xe(e.text,Math.min(e.filterBase,e.text.length),s),p=e.lastRawQuery!==""||d>0?se(e.text,d,e.filterInProgress):"",u=a?i?i(p.trim()):a.options??[]:[],c=e.editingParam!=null&&e.editingAnchor!=null,h;if(c&&e.editingParam&&e.editingAnchor!=null){let g=e.editingParam.id,w=e.completedParams.some(U=>U.id===g),T=e.caretOffset??e.editingAnchor,O=w?"":e.text.slice(e.editingAnchor,T);h=ve(e.editingParam.options,O)}else h=ve(u,p);let b=this.opts.dropdownTrigger??"auto",v=this.opts.closeDropdownOnBlur??!0,f=!1;if(c){let g=v?e.isFocused:!0;f=h.length>0&&g}else if(b==="auto"){let g=v?e.isFocused:!0,w=e.text.replace(/\s+$/,"").length,T=e.caretOffset==null||e.caretOffset>=w;f=(h.length>0||e.isLoading)&&g&&T}else b==="manual"&&(f=(h.length>0||e.isLoading)&&e.pillTapped);this.store.set({segments:o,actionableSuggestions:r,filteredOptions:h,placeholderText:s,isDropdownOpen:f}),this.derivedInProgress=!1;let m=this.store.get();for(let g of this.externalListeners)g(m)}setupContainer(){this.container.classList.add("magicx-aia"),this.container.dataset.pillPlacement=this.renderMode==="dropdown"?"dropdown":this.opts.pillPlacement??"inline",this.container.dataset.optionsPosition=this.opts.optionsPosition??"below",this.container.dataset.animations=this.opts.animations??!0?"on":"off",this.modeController=new de(this.container,this.opts.mode??"auto")}buildAndRenderFull(){let e=this,t={store:this.store,listboxId:this.listboxId,get pillPlacement(){return e.opts.pillPlacement??"inline"},get onSubmit(){return e.opts.onSubmit},afterSubmit:()=>e.reset(),submitButton:this.opts.submitButton,autoFocus:this.opts.autoFocus??!0,selectOption:o=>this.selectOption(o),setActivePill:o=>this.pillsController.setActivePill(o),handleKeyDown:o=>this.keyboardController.handleKeyDown(o),handleChange:o=>this.handleChange(o),startEditingParam:o=>this.startEditingParam(o),handleCaretAfterInput:o=>this.handleCaretAfterInput(o),handleCaretMove:o=>this.handleCaretMove(o),replaceEditingRange:o=>this.replaceEditingRange(o)};this.domRefs=Nt(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&mt(this.domRefs,this.store.get(),t)}),mt(this.domRefs,this.store.get(),t),this.subscribeNewParamTimer()}buildAndRenderDropdown(){let e={store:this.store,listboxId:this.listboxId,selectOption:t=>this.selectOption(t),setActivePill:t=>this.pillsController.setActivePill(t)};this.dropdownRefs=Rt(this.container,e),this.subscribeBatchedRender(()=>{this.dropdownRefs&&ut(this.dropdownRefs,this.store.get(),e)}),ut(this.dropdownRefs,this.store.get(),e),this.subscribeNewParamTimer()}subscribeBatchedRender(e){let t=!1;this.unsubscribers.push(this.store.subscribe(()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,t)=>{e.newParamId&&e.newParamId!==t.newParamId&&(this.newParamTimer&&clearTimeout(this.newParamTimer),this.newParamTimer=window.setTimeout(()=>{this.store.set({newParamId:null})},650))}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:o,invalid:r}=At(e,t.completedParams);r.length>0&&this.store.set({completedParams:o}),this.maybePromoteExactMatch(e)}maybePromoteExactMatch(e){let t=this.store.get(),r=t.suggestions.filter(g=>g.type!=="placeholder")[0];if(!r?.options)return;let a=t.suggestions.filter(g=>g.type==="placeholder").map(g=>g.text).join(" "),i=xe(e,t.filterBase,a),s=se(e,i,t.filterInProgress),d=le(r.options,s);if(!d)return;let l=d.text.toLowerCase(),p=e.toLowerCase().lastIndexOf(l),u=p>=0?p:Math.max(0,e.length-d.text.length),c=u+d.text.length,h=e.slice(u,c),b=e,f=c<e.length&&e[c]===" "?c+1:c,m={id:crypto.randomUUID(),placeholder:"",type:r.type,text:h,kind:d.kind,suggestionType:r.type,suggestionPlaceholder:r.text,options:r.options??[],metadata:d.metadata};this.store.set(g=>({text:b,completedParams:[...g.completedParams,m],suggestions:g.suggestions.filter(w=>w!==r),filterBase:f,newParamId:m.id,caretOffset:f,activeDropdownIndex:-1}))}maybePromoteEditExactMatch(){let e=this.store.get(),t=e.editingParam,o=e.editingAnchor,r=e.editingTail;if(!t||o==null||r==null||e.completedParams.some(w=>w.id===t.id))return;let a=e.text.slice(o,r),i=le(t.options,a);if(!i)return;let s=i.text.toLowerCase(),d=a.toLowerCase().lastIndexOf(s),l=o+Math.max(0,d),p=l+i.text.length,u=e.text.slice(l,p),c=e.text,b=p<e.text.length&&e.text[p]===" "?p+1:p,v={id:crypto.randomUUID(),placeholder:"",type:t.suggestionType,text:u,kind:i.kind,suggestionType:t.suggestionType,suggestionPlaceholder:t.suggestionPlaceholder,options:t.options,metadata:i.metadata},f=e.completedParams.length,m=0;for(let w=0;w<e.completedParams.length;w++){let T=c.indexOf(e.completedParams[w].text,m);if(T!==-1){if(T>=b){f=w;break}m=T+e.completedParams[w].text.length}}let g=[...e.completedParams];g.splice(f,0,v),this.store.set(()=>({text:c,completedParams:g,newParamId:v.id,filterBase:b,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:b,activeDropdownIndex:-1})),this.scheduleSetCursor(b)}};function Ze({onSubmit:n,onError:e,optionOverrides:t,maskCompletedText:o,apiConfig:r,columns:a=2,dropdownTrigger:i,closeDropdownOnBlur:s,onFocus:d,onBlur:l,value:p,completedParams:u,onChange:c,onParamsChange:h,source:b,setCursor:v}){let f=(0,P.useRef)(null),[m,g]=(0,P.useState)(null),w=(0,P.useRef)(n);w.current=n;let T=(0,P.useRef)(e);T.current=e;let O=(0,P.useRef)(c);O.current=c;let U=(0,P.useRef)(h);U.current=h;let ce=(0,P.useRef)(d);ce.current=d;let k=(0,P.useRef)(l);k.current=l;let pe=(0,P.useRef)(v);pe.current=v,(0,P.useEffect)(()=>{if(typeof document>"u")return;let S=new Ye(document.createElement("div"),{renderMode:"headless",apiConfig:r,optionOverrides:t,maskCompletedText:o,columns:a,dropdownTrigger:i,closeDropdownOnBlur:s,source:b,value:p,completedParams:u,onSubmit:(...D)=>w.current?.(...D),onError:(...D)=>T.current?.(...D),onChange:(...D)=>O.current?.(...D),onParamsChange:(...D)=>U.current?.(...D),onFocus:()=>ce.current?.(),onBlur:()=>k.current?.(),setCursor:D=>pe.current?.(D)});f.current=S,g(S.getState());let R=S.subscribe(D=>g(D));return()=>{R(),S.destroy(),f.current===S&&(f.current=null)}},[]);let x=f.current,_=(0,P.useCallback)(()=>{},[]);(0,P.useEffect)(()=>{p!==void 0&&x?.setValue(p)},[p,x]),(0,P.useEffect)(()=>{u!==void 0&&x?.setCompletedParams(u)},[u,x]);let we=JSON.stringify(r??null),te=(0,P.useRef)(t),ue=(0,P.useRef)(0);if(t!==te.current){let S=te.current,R=t,D=Object.keys(S??{}),G=Object.keys(R??{});(D.length!==G.length||G.some(Y=>!S?.[Y]||R[Y]!==S[Y]))&&ue.current++,te.current=t}(0,P.useEffect)(()=>{x?.update({apiConfig:r,optionOverrides:t,dropdownTrigger:i,closeDropdownOnBlur:s})},[we,ue.current,i,s,x]);let Se=(0,P.useCallback)(S=>{if(!x)return;let R=S.target.value,G=R.length>0&&!S.nativeEvent?.isComposing&&R[0]!==R[0].toUpperCase()?R[0].toUpperCase()+R.slice(1):R;x.handleTextChange(G)},[x]),tt=(0,P.useCallback)(S=>{x?.handleKeyDown(S.nativeEvent)},[x]),me=(0,P.useCallback)(()=>x?.setFocused(!0),[x]),Pe=(0,P.useCallback)(()=>x?.setFocused(!1),[x]),nt=(0,P.useCallback)(S=>x?.handleTextChange(S),[x]),ge=(0,P.useCallback)(S=>{if(!x)return;let R="nativeEvent"in S?S.nativeEvent:S;x.handleKeyDown(R)},[x]),j=(0,P.useCallback)(S=>x?.setFocused(S),[x]),Ie=(0,P.useCallback)(S=>x?.startEditingParam(S),[x]),Ae=(0,P.useCallback)(()=>x?.exitEditMode(),[x]),Ce=(0,P.useCallback)(S=>x?.handleCaretAfterInput(S),[x]),ot=(0,P.useCallback)(S=>x?.handleCaretMove(S),[x]),Te=(0,P.useCallback)(S=>x?.replaceEditingRange(S)??!1,[x]),fe=(0,P.useCallback)(S=>x?.setActivePill(S),[x]),_e=(0,P.useCallback)(()=>x?.removeLastParam(),[x]),Ee=(0,P.useCallback)(()=>x?.clearNewParamId(),[x]),ke=(0,P.useCallback)(()=>x?.reset(),[x]),ne=(0,P.useCallback)(S=>x?.selectOption(S),[x]),V=(0,P.useCallback)(S=>x?.setActiveDropdownIndex(S),[x]);if(!x)return{completedParams:u??[],suggestionPills:[],setActivePill:_,removeLastParam:_,segments:[],newParamId:null,clearNewParamId:_,suggestions:[],activeIndex:-1,isReady:!1,isLoading:!0,isFocused:!1,isDropdownOpen:!1,placeholderText:"",listboxId:"",error:null,handleTextChange:_,handleKeyDown:_,setFocused:_,editingParam:null,editingAnchor:null,caretOffset:null,startEditingParam:_,exitEditMode:_,handleCaretAfterInput:_,handleCaretMove:_,replaceEditingRange:()=>!1,inputProps:{value:p??"",placeholder:void 0,onChange:_,onKeyDown:_,onFocus:_,onBlur:_,role:"combobox","aria-expanded":!1,"aria-activedescendant":void 0,"aria-autocomplete":"list","aria-controls":""},reset:_,dropdownProps:{suggestions:[],activeIndex:-1,onSelect:_,onHighlight:_,isOpen:!1,id:"",pills:[],onPillClick:_}};let A=m??x.getState(),it=p!==void 0?p:A.text,Oe=u!==void 0?u:A.completedParams,oe=A.actionableSuggestions,De=oe[0],Le=A.filteredOptions,rt=A.activeDropdownIndex>=0?`${x.listboxId}-option-${A.activeDropdownIndex}`:void 0,K=A.editingParam,z=K?{type:K.suggestionType,text:K.suggestionPlaceholder,required:!0,options:K.options}:null,Me=z??De,at=z?[z]:oe;return{completedParams:Oe,suggestionPills:oe,setActivePill:fe,removeLastParam:_e,segments:A.segments,newParamId:A.newParamId,clearNewParamId:Ee,suggestions:A.suggestions,activeIndex:A.activeDropdownIndex,isReady:A.isReady,isLoading:A.isLoading&&!A.editingParam&&!A.inSelectionAnimation,isFocused:A.isFocused,isDropdownOpen:A.isDropdownOpen,placeholderText:A.placeholderText,listboxId:x.listboxId,error:A.error,handleTextChange:nt,handleKeyDown:ge,setFocused:j,editingParam:K,editingAnchor:A.editingAnchor,caretOffset:A.caretOffset,startEditingParam:Ie,exitEditMode:Ae,handleCaretAfterInput:Ce,handleCaretMove:ot,replaceEditingRange:Te,inputProps:{value:it,placeholder:A.placeholderText||void 0,onChange:Se,onKeyDown:tt,onFocus:me,onBlur:Pe,role:"combobox","aria-expanded":A.isDropdownOpen,"aria-activedescendant":rt,"aria-autocomplete":"list","aria-controls":x.listboxId},reset:ke,dropdownProps:{suggestions:Me?[{...Me,options:Le}]:[],activeIndex:A.activeDropdownIndex,onSelect:ne,onHighlight:V,isOpen:A.isDropdownOpen,id:x.listboxId,pills:at,onPillClick:fe,isLoading:A.isLoading&&!A.editingParam&&!A.inSelectionAnimation}}}var B=require("react/jsx-runtime");function Pn(n){return n!=="auto"?n:typeof window>"u"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}var et;function In(){if(et!==void 0)return et;if(typeof document>"u")return!1;let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),et=n.contentEditable==="plaintext-only",et}var zt=(0,I.forwardRef)(function({onSubmit:e,onError:t,optionOverrides:o,maskCompletedText:r,className:a,apiConfig:i,columns:s,pillPlacement:d="inline",mode:l="auto",optionsPosition:p="below",animations:u=!0,dropdownTrigger:c,closeDropdownOnBlur:h,autoFocus:b=!0,onFocus:v,onBlur:f,value:m,completedParams:g,onChange:w,onParamsChange:T,submitButton:O},U){let ce=(0,I.useRef)(null),k=(0,I.useRef)(null),pe=(0,I.useRef)(()=>{}),x=(0,I.useRef)(null),_=(0,I.useRef)(!1),we=(0,I.useRef)(""),te=(0,I.useRef)(""),ue=(0,I.useRef)(null),Se=(0,I.useRef)(0);(0,I.useEffect)(()=>{let y=ce.current;if(y)return x.current?x.current.setMode(l):x.current=new de(y,l),()=>{x.current?.destroy(),x.current=null}},[l]);let tt=(0,I.useCallback)(y=>{let C=k.current;C&&M(C,y)},[]),{completedParams:me,suggestionPills:Pe,setActivePill:nt,segments:ge,newParamId:j,clearNewParamId:Ie,placeholderText:Ae,isFocused:Ce,isDropdownOpen:ot,isLoading:Te,activeIndex:fe,listboxId:_e,handleTextChange:Ee,handleKeyDown:ke,setFocused:ne,editingParam:V,editingAnchor:A,caretOffset:it,startEditingParam:Oe,handleCaretAfterInput:oe,handleCaretMove:De,replaceEditingRange:Le,dropdownProps:rt,reset:K}=Ze({onSubmit:y=>pe.current(y),onError:t,optionOverrides:o,maskCompletedText:r,apiConfig:i,columns:s,dropdownTrigger:c,closeDropdownOnBlur:h,onFocus:v,onBlur:f,value:m,completedParams:g,onChange:w,onParamsChange:T,source:"full-sdk",setCursor:tt});ue.current=it,(0,I.useEffect)(()=>{if(!b)return;let y=k.current;y&&(document.activeElement===y?ne(!0):y.focus())},[b,ne]),(0,I.useEffect)(()=>{if(!j)return;let y=window.setTimeout(()=>Ie(),650);return()=>window.clearTimeout(y)},[j,Ie]),(0,I.useEffect)(()=>{let y=k.current;if(!y)return;let C=y.ownerDocument??document,E=()=>{let N=C.getSelection();if(!N||N.rangeCount===0||!N.anchorNode||!y.contains(N.anchorNode))return;let L=N.anchorNode,lt=(L.nodeType===Node.ELEMENT_NODE?L:L.parentElement)?.closest('strong[data-seg="completed"][data-param-id]')?.dataset.paramId??null;if(lt&<!==V?.id){Oe(lt);return}performance.now()-Se.current<50||De(F(y))};return C.addEventListener("selectionchange",E),()=>C.removeEventListener("selectionchange",E)},[V,Oe,De]),(0,I.useLayoutEffect)(()=>{let y=k.current;y&&Ke({input:y,segments:ge,newParamId:j,editingParamId:V?.id??null,placeholderText:Ae??"",isFocused:Ce})},[ge,j,V,Ae,Ce]),(0,I.useLayoutEffect)(()=>{let y=we.current,C=j??"";if(we.current=C,!C||C===y)return;let E=k.current;if(!E)return;E.focus();let N=ue.current??Fe(E);M(E,N)},[j]),(0,I.useLayoutEffect)(()=>{let y=te.current,C=V?.id??"";if(te.current=C,!C||C===y||A==null)return;let E=k.current;E&&M(E,A)},[V,A]),(0,I.useImperativeHandle)(U,()=>({focus:()=>k.current?.focus(),blur:()=>k.current?.blur(),reset:K,setMode:y=>x.current?.setMode(y)}),[K]);let z=(0,I.useCallback)(()=>{if(_.current)return;let y=k.current;if(!y)return;let C=ae(y),N=C.length>0&&C[0]!==C[0].toUpperCase()?C[0].toUpperCase()+C.slice(1):C;Ee(N)},[Ee]),Me=(0,I.useCallback)(()=>{Se.current=performance.now(),z();let y=k.current;y&&oe(F(y))},[z,oe]);(0,I.useEffect)(()=>{let y=k.current;if(!y)return;let C=E=>{let N=E,L=N.inputType;if(L==="insertParagraph"||L==="insertLineBreak"||L==="insertFromDrop"){E.preventDefault();return}if(L.startsWith("insert")||L.startsWith("delete")){let Q=L.startsWith("delete")?"":N.data??"";Le(Q)&&E.preventDefault()}};return y.addEventListener("beforeinput",C),()=>y.removeEventListener("beforeinput",C)},[Le]);let at=(0,I.useCallback)(()=>{_.current=!0},[]),S=(0,I.useCallback)(()=>{_.current=!1,z()},[z]),R=(0,I.useCallback)(y=>{y.preventDefault();let C=k.current;if(!C)return;let E=(y.clipboardData.getData("text/plain")??"").replace(/\r?\n/g," ");if(!E)return;let N=C.ownerDocument??document,L=N.getSelection();if(!L||L.rangeCount===0)return;let Q=L.getRangeAt(0);if(!C.contains(Q.startContainer))return;Q.deleteContents();let st=N.createTextNode(E);Q.insertNode(st),Q.setStartAfter(st),Q.collapse(!0),L.removeAllRanges(),L.addRange(Q),z()},[z]),D=(0,I.useCallback)(y=>ke(y),[ke]),G=!!ge.length||me.length>0,Y=(0,I.useCallback)(()=>{if(!G)return;let y=k.current?ae(k.current):"",{rawQuery:C,completedParams:E}=H(y,me);e({query:y.trim(),raw_query:C,completed_params:E}),K()},[G,me,e,K]);pe.current=Y;let Wt=(0,I.useCallback)(y=>{y.target?.closest("[data-aia-pill]")||k.current?.focus()},[]),$t=d==="inline",qt=d==="dropdown",Ut=fe>=0?`${_e}-option-${fe}`:void 0,Gt=In()?"plaintext-only":"true";return(0,B.jsxs)("div",{ref:ce,className:`magicx-aia ${X.container} ${a??""}`,"data-pill-placement":d,"data-options-position":p,"data-animations":u?"on":"off","data-mode":Pn(l),children:[(0,B.jsx)(Ne,{...rt,showPills:qt}),(0,B.jsxs)("div",{className:X.inputWrapper,onClick:Wt,children:[(0,B.jsxs)("div",{className:X.editorArea,"data-aia-editor":"",children:[(0,B.jsx)("div",{ref:k,className:X.input,"data-aia-input":"",contentEditable:Gt,suppressContentEditableWarning:!0,tabIndex:0,role:"combobox","aria-autocomplete":"list","aria-haspopup":"listbox","aria-controls":_e,"aria-expanded":ot,"aria-activedescendant":Ut,spellCheck:!0,enterKeyHint:"send",onInput:Me,onKeyDown:D,onCompositionStart:at,onCompositionEnd:S,onPaste:R,onFocus:()=>ne(!0),onBlur:()=>ne(!1)}),$t&&(Te||Pe.length>0)&&(0,B.jsx)("span",{className:X.pillListContainer,"data-aia-pill-list-container":"",children:(0,B.jsx)(be,{pills:Pe,activePillIndex:0,onSelectPill:nt,loading:Te})})]}),O===null?null:O===void 0?(0,B.jsx)("button",{type:"button","data-aia-submit":"",className:X.submitButton,disabled:!G,onClick:y=>{y.stopPropagation(),Y()},"aria-label":"Submit",children:(0,B.jsx)("svg",{width:"18",height:"18",viewBox:"0 0 18 18",fill:"none",role:"img","aria-label":"Submit",children:(0,B.jsx)("path",{d:"M9 14V4M9 4L4 9M9 4L14 9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}):(0,B.jsx)("span",{"data-aia-submit":"",className:X.submitSlot,onClick:y=>{G&&(y.stopPropagation(),Y())},children:O})]})]})});0&&(module.exports={AIAutocomplete,AIAutocompleteDropdown,useAIAutocomplete});
|
|
822
|
+
`,document.head.appendChild(n)}var ht='[contenteditable="false"]',ue;function dn(){if(ue!==void 0)return ue;let n=globalThis.Intl.Segmenter;if(!n)return ue=null,null;try{ue=new n(void 0,{granularity:"grapheme"})}catch{ue=null}return ue??null}function ke(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(ht))return!0;t=t.parentNode}return!1}function Oe(n){return(n.ownerDocument??document).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return ke(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function me(n){let e=Oe(n),t="",o=e.nextNode();for(;o;)t+=o.data,o=e.nextNode();return t}function De(n){let e=Oe(n),t=0,o=e.nextNode();for(;o;)t+=o.data.length,o=e.nextNode();return t}function $(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 i=t;if(ke(i,n)&&i!==n)return null;let a=0;for(let r=0;r<o&&r<i.childNodes.length;r++)a+=bt(i.childNodes[r],n);return a+ft(i,n)}return t.nodeType!==Node.TEXT_NODE||ke(t,n)?null:ft(t,n)+o}function bt(n,e){if(n.nodeType===Node.TEXT_NODE)return ke(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(ht))return 0;let o=0;for(let i of Array.from(t.childNodes))o+=bt(i,e);return o}function ft(n,e){let t=Oe(e),o=0,i=t.nextNode();for(;i;){if(i===n||n.nodeType===Node.ELEMENT_NODE&&n.contains(i))return o;o+=i.data.length,i=t.nextNode()}return o}function M(n,e){let t=n.ownerDocument??document,o=t.getSelection();if(!o)return;let i=Math.max(0,Math.min(e,De(n))),a=Oe(n),r=0,s=null,l=0,d=a.nextNode(),u=null;for(;d;){let m=d.data.length;if(i<r+m){s=d,l=i-r;break}if(i===r+m){let v=a.nextNode();v?(s=v,l=0):(s=d,l=m);break}r+=m,u=d,d=a.nextNode()}let p=t.createRange();if(s){let m=s.parentElement?.closest('strong[data-seg="completed"]');m&&m!==n&&n.contains(m)?l===0?p.setStartBefore(m):l===s.data.length?p.setStartAfter(m):p.setStart(s,l):p.setStart(s,l)}else u?p.setStart(u,u.data.length):p.setStart(n,0);p.collapse(!0),o.removeAllRanges(),o.addRange(p)}function xt(n){let e=$(n);return e==null?!1:e>=De(n)}function vt(n,e){if(e<=0)return 0;let t=dn();if(!t)return e-1;let o=n.slice(0,e),i=0;for(let{index:a}of t.segment(o))a<e&&(i=a);return i}var k=require("react");function F(n,e){let t=n,o={},i=[];for(let a of e){let r=(o[a.type]??0)+1;o[a.type]=r;let l=`{{${a.type.toUpperCase().replace(/\s+/g,"_")}_${r}}}`,d=t.indexOf(a.text);d!==-1&&(t=t.slice(0,d)+l+t.slice(d+a.text.length)),i.push({...a,placeholder:l})}return{rawQuery:t,completedParams:i}}function ge(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function se(n,e,t){let o=n.slice(e);if(t||e===0||n[e-1]===" ")return o;let i=o.indexOf(" ");return i===-1?"":o.slice(i+1)}function yt(n,e){let t=n.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let o=t.split(" "),i=e.toLowerCase();for(let a=0;a<o.length;a++){let r=o.slice(a).join(" ");if(i.startsWith(r.toLowerCase())){let s=t.length-r.length;return n.length-s}}return 0}function le(n,e){if(!n)return[];let t=e.trimStart();if(!t)return n;let o=t.toLowerCase();return n.filter(i=>!i.is_tappable||i.text.toLowerCase().includes(o))}function fe(n,e){if(!n)return null;let t=e.trim();if(!t)return null;let o=t.toLowerCase();return n.find(i=>i.is_tappable&&i.text.toLowerCase()===o)??null}var he=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 wt(n,e){let t=[],o=0;for(let a of e){let r=n.indexOf(a.text,o);r!==-1&&(r>o&&t.push({type:"text",value:n.slice(o,r)}),t.push({type:"completed",value:a.text,param:a}),o=r+a.text.length)}let i=n.slice(o);return i&&t.push({type:"text",value:i}),t}function St(n,e){let t=[],o=[],i=0;for(let a of e){let r=n.indexOf(a.text,i);r===-1?o.push(a):(t.push(a),i=r+a.text.length)}return{valid:t,invalid:o}}var Le=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",Me=`${cn}/api/suggest`,Pt=new WeakMap;function Se(n){return n?.type==="accessToken"}function pn(n){if(!(!n||Se(n)))return n}function Re(n){let e=Pt.get(n.getAccessToken);return e||(e=new Le(n),Pt.set(n.getAccessToken,e)),e}function Ne(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function He(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??Me).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function mn(n){return Se(n)?`Bearer ${await Re(n).getToken()}`:He(n)}async function It(n){try{let e=un(n.apiConfig?.endpoint),t=Ne(n.apiConfig),o=await mn(n.apiConfig);o&&(t.Authorization=o);let i=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:i})}catch{}}var gn="0.1.42",Ct=!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 i=e.find(r=>r.type==="contact"&&r.metadata?.contact_account_count)?.metadata?.contact_account_count,a=typeof i=="number"?i:void 0;return{data:{raw_query:n,completed_params:e.map(r=>hn(r,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 At(n,e,t,o,i){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:o,signal:i})}async function Et(n,e,t){let o=t.apiConfig,i=!t.maskCompletedText,a=bn(n,e,i,t.sessionId),r=Ne(o),s=o?.endpoint??Me,l=JSON.stringify(a);if(Se(o)){let p=Re(o),m=await p.getToken(),v=await At(s,r,m,l,t.signal);if(v.status===401){let g=await p.getToken(!0);v=await At(s,r,g,l,t.signal)}if(!v.ok)throw new Error(`API error: ${v.status} ${v.statusText}`);return v.json()}let d=He(o);!d&&!Ct&&(Ct=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),d&&(r.Authorization=d);let u=await fetch(s,{method:"POST",headers:r,body:l,signal:t.signal});if(!u.ok)throw new Error(`API error: ${u.status} ${u.statusText}`);return u.json()}function Tt(n,e){return e?n.map(t=>{let o=e[t.type];if(!o)return t;let i=o("");if(i.length===0)return t;let a=new Set(i.map(s=>s.text)),r=(t.options??[]).filter(s=>!a.has(s.text));return{...t,options:[...i,...r]}}):n}var xn=100,vn=300,yn=2,Fe=class{constructor(e,t,o,i,a,r,s={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=o;this.getMaskCompletedText=i;this.getOnError=a;this.getSessionId=r;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 i=++this.fetchVersion,a=this.store.get().text.length;this.store.set({isLoading:!0,error:null});try{let r=await Et(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:o.signal,apiConfig:this.getApiConfig()});if(i!==this.fetchVersion)return;let s=Tt(r.data.suggestions??[],this.getOptionOverrides()),l=r.data.input??[],d=l[l.length-1],u=this.store.get().text,p,m;if(d?.state==="in_progress"){m=!0;let f=u.toLowerCase().lastIndexOf(d.text.toLowerCase());p=f!==-1?f:a}else m=!1,p=a;let g=s.filter(f=>f.type!=="placeholder")[0],b=null;if(g){let f=se(u,p,m),c=fe(g.options,f);c&&(b={id:crypto.randomUUID(),placeholder:"",type:g.type,text:c.text,kind:c.kind,suggestionType:g.type,suggestionPlaceholder:g.text,options:g.options??[],metadata:c.metadata},s=s.filter(h=>h!==g),this.callbacks.onAutoMatch?.({active:g,matched:c,rawQuery:e}))}this.store.set(f=>({suggestions:s,isLoading:!1,isReady:r.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:p,filterInProgress:m,...b?{completedParams:[...f.completedParams,b]}:{}}))}catch(r){if(i===this.fetchVersion){let s=r instanceof Error?r:new Error(String(r));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 i=this.store.get();if(!i.text&&i.completedParams.length===0)return this.doFetch("",[]),!0;let a=i.suggestions.filter(h=>h.type==="placeholder").map(h=>h.text).join(" "),r=ge(i.text,i.filterBase,a),s=se(i.text,r,i.filterInProgress),d=i.suggestions.filter(h=>h.type!=="placeholder")[0],p=(d?le(d.options,s):[]).filter(h=>h.is_tappable),m=d?fe(d.options,s)!==null:!1,v=s.trim().length>0;if(p.length>0&&!m&&v||i.completedParams.length===0&&i.text.length>0&&a.length>0&&a.toLowerCase().startsWith(i.text.toLowerCase()))return!1;let{rawQuery:g,completedParams:b}=F(i.text,i.completedParams),f=g.length<i.lastRawQuery.length,c=Math.abs(g.length-i.lastRawQuery.length);return f||c>=o?(this.doFetch(g,b),!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 _t(n){return n instanceof HTMLTextAreaElement||n instanceof HTMLInputElement?n.selectionStart!=null&&n.selectionStart===n.value.length:n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?xt(n):!1}function wn(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?$(n):null}var Be=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:o,getOnSubmit:i}=this.ctx,a=this.getEffectiveColumns(),r=i(),s=this.getTappableIndices(a);switch(e.key){case"ArrowDown":{let l=_t(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 u=s.indexOf(t.activeDropdownIndex),p=u<s.length-1?u+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 u=t.activeDropdownIndex+1;u<t.filteredOptions.length&&t.filteredOptions[u]?.is_tappable&&this.store.set({activeDropdownIndex:u})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let d=e.target.closest("[data-aia-input]")??e.target,u=t.editingTail;this.ctx.exitEditMode?.(),M(d,u);break}_t(e.target)&&t.actionableSuggestions.length>1&&(e.preventDefault(),this.pillsSetActivePill(1));break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%a>0){let l=t.activeDropdownIndex-1;l>=0&&t.filteredOptions[l]?.is_tappable&&this.store.set({activeDropdownIndex:l})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let l=e.target.closest("[data-aia-input]")??e.target,d=t.editingAnchor;this.ctx.exitEditMode?.(),M(l,d);break}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let l=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(r){let{rawQuery:l,completedParams:d}=F(t.text,t.completedParams);r({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 u=t.placeholderText;if(this.store.set(p=>({text:u,filterBase:u.length,suggestions:p.suggestions.filter(m=>m.type!=="placeholder")})),e.target instanceof HTMLElement){let p=e.target.closest("[data-aia-input]")??e.target;queueMicrotask(()=>M(p,u.length))}}else if(d)e.preventDefault(),this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,o);else if(t.isDropdownOpen){let u=t.filteredOptions.findIndex(p=>p.is_tappable);u>=0&&(e.preventDefault(),this.clickOrSelect(u,t.filteredOptions,o))}break}case"Escape":{if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){let l=e.target.closest("[data-aia-input]")??e.target,d=t.editingTail;this.ctx.exitEditMode?.(),M(l,d)}this.store.set({activeDropdownIndex:-1});break}}}getTappableIndices(e){let o=this.store.get().filteredOptions.map((a,r)=>a.is_tappable?r:-1).filter(a=>a!==-1),i=Array.from({length:e},()=>[]);for(let a of o)i[a%e].push(a);return i.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 i=document.getElementById(`${o}-option-${e}`);i?i.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 i=o[e],a=o.filter((s,l)=>l!==e),r=t.suggestions.filter(s=>s.type==="placeholder");this.store.set({suggestions:[...r,i,...a],pillTapped:!0,activeDropdownIndex:-1})}};var Ke=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 i=o[e],a=o.filter((s,l)=>l!==e),r=t.suggestions.filter(s=>s.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:s}=F(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:s,selectedPill:i.text,otherPills:a.map(l=>l.text)})}this.store.set({suggestions:[...r,i,...a],pillTapped:!0,activeDropdownIndex:-1})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};function kt(n,e){let t=e.dropdownTrigger??"auto",o=e.closeDropdownOnBlur??!0,i=n.filteredOptionsLength>0;if(n.inEditMode){let a=o?n.isFocused:!0;return i&&a}if(t==="auto"){let a=o?n.isFocused:!0,r=n.text.replace(/\s+$/,"").length,s=n.caretOffset==null||n.caretOffset>=r;return(i||n.isLoading)&&a&&s}return t==="manual"?(i||n.isLoading)&&n.pillTapped:!1}function Ot(n,e){let t=wt(n.text,n.completedParams),o=n.suggestions.filter(g=>g.type!=="placeholder"),i=o[0],a=i?e.optionOverrides?.[i.type]:void 0,r=n.suggestions.filter(g=>g.type==="placeholder").map(g=>g.text).join(" "),s=ge(n.text,Math.min(n.filterBase,n.text.length),r),d=n.lastRawQuery!==""||s>0?se(n.text,s,n.filterInProgress):"",u=i?a?a(d.trim()):i.options??[]:[],p=n.editingParam!=null&&n.editingAnchor!=null,m;if(p&&n.editingParam&&n.editingAnchor!=null){let g=n.editingParam.id,b=n.completedParams.some(h=>h.id===g),f=n.caretOffset??n.editingAnchor,c=b?"":n.text.slice(n.editingAnchor,f);m=le(n.editingParam.options,c)}else m=le(u,d);e.showNonTappableOptions===!1&&(m=m.filter(g=>g.is_tappable));let v=kt({inEditMode:p,filteredOptionsLength:m.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading,pillTapped:n.pillTapped},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur});return{segments:t,actionableSuggestions:o,filteredOptions:m,placeholderText:r,isDropdownOpen:v}}function ze(n){return n.mode==="fresh"?Sn(n):Pn(n)}function Sn(n){let{text:e,completedParams:t,suggestions:o,filterBase:i,filterInProgress:a}=n,s=o.filter(S=>S.type!=="placeholder")[0];if(!s?.options)return null;let l=o.filter(S=>S.type==="placeholder").map(S=>S.text).join(" "),d=ge(e,i,l),u=se(e,d,a),p=fe(s.options,u);if(!p)return null;let m=p.text.toLowerCase(),v=e.toLowerCase().lastIndexOf(m),g=v>=0?v:Math.max(0,e.length-p.text.length),b=g+p.text.length,f=e.slice(g,b),h=b<e.length&&e[b]===" "?b+1:b,x={id:crypto.randomUUID(),placeholder:"",type:s.type,text:f,kind:p.kind,suggestionType:s.type,suggestionPlaceholder:s.text,options:s.options??[],metadata:p.metadata};return{patch:{text:e,completedParams:[...t,x],suggestions:o.filter(S=>S!==s),filterBase:h,newParamId:x.id,caretOffset:h,activeDropdownIndex:-1},caretPos:h}}function Pn(n){let{text:e,completedParams:t,editingParam:o,editingAnchor:i,editingTail:a}=n;if(t.some(x=>x.id===o.id))return null;let r=e.slice(i,a),s=fe(o.options,r);if(!s)return null;let l=s.text.toLowerCase(),d=r.toLowerCase().lastIndexOf(l),u=i+Math.max(0,d),p=u+s.text.length,m=e.slice(u,p),g=p<e.length&&e[p]===" "?p+1:p,b={id:crypto.randomUUID(),placeholder:"",type:o.suggestionType,text:m,kind:s.kind,suggestionType:o.suggestionType,suggestionPlaceholder:o.suggestionPlaceholder,options:o.options,metadata:s.metadata},f=t.length,c=0;for(let x=0;x<t.length;x++){let S=e.indexOf(t[x].text,c);if(S!==-1){if(S>=g){f=x;break}c=S+t[x].text.length}}let h=[...t];return h.splice(f,0,b),{patch:{text:e,completedParams:h,newParamId:b.id,filterBase:g,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:g,activeDropdownIndex:-1},caretPos:g}}var We=class{constructor(e){this.deps=e}start(e){let t=this.deps.store.get();if(t.editingParam?.id===e)return;let o=t.completedParams.find(r=>r.id===e);if(!o)return;let i=0,a=-1;for(let r of t.completedParams){let s=t.text.indexOf(r.text,i);if(s!==-1){if(r.id===e){a=s;break}i=s+r.text.length}}a<0||this.deps.store.set({editingParam:o,editingAnchor:a,editingTail:a+o.text.length,caretOffset:a+o.text.length,activeDropdownIndex:-1})}exit(){this.deps.store.get().editingParam&&this.deps.store.set({editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1})}replaceRange(e){let t=this.deps.store.get(),o=t.editingParam,i=t.editingAnchor,a=t.editingTail;if(!o||i==null||a==null||!t.completedParams.some(l=>l.id===o.id))return!1;let r=t.text.slice(0,i)+e+t.text.slice(a),s=i+e.length;return this.deps.store.set(l=>({text:r,completedParams:l.completedParams.filter(d=>d.id!==o.id),editingTail:s,caretOffset:s,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(s),this.tryPromote(),!0}caretAfterInput(e){let t=this.deps.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.deps.store.set(o),this.tryPromote()}caretMove(e){let t=this.deps.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null&&e!=null&&(e<t.editingAnchor||e>t.editingTail)){this.deps.store.set({caretOffset:e,editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1});return}this.deps.store.set({caretOffset:e})}selectOption(e){let t=this.deps.store.get(),o=t.editingParam,i=t.editingAnchor,a=t.editingTail;if(!o||i==null||a==null)return;this.deps.fireTelemetry("option",{raw_query:F(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:o.options.filter(c=>c.text!==e.text).map(c=>c.text)});let r=t.text.slice(0,i),s=t.text.slice(a),l=i===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,d=s.length===0||s[0]!==" ",u=d?`${l} `:l,p=r+u+s,m=i+u.length+(d?0:1),v={id:crypto.randomUUID(),placeholder:"",type:o.suggestionType,text:l,kind:e.kind,suggestionType:o.suggestionType,suggestionPlaceholder:o.suggestionPlaceholder,options:o.options,metadata:e.metadata},g=t.completedParams.findIndex(c=>c.id===o.id),b=t.completedParams.filter(c=>c.id!==o.id),f=g>=0?Math.min(g,b.length):b.length;b.splice(f,0,v),this.deps.store.set({text:p,completedParams:b,newParamId:v.id,filterBase:m,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:m,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.deps.startSelectionAnimationTimer(),this.deps.scheduleSetCursor(m)}tryPromote(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let t=ze({mode:"edit",text:e.text,completedParams:e.completedParams,editingParam:e.editingParam,editingAnchor:e.editingAnchor,editingTail:e.editingTail});t&&(this.deps.store.set(t.patch),this.deps.scheduleSetCursor(t.caretPos))}};var Dt="data-aia-key";function $e(n,e,t){let o=new Map;for(let r of Array.from(n.children)){let s=r.getAttribute(Dt);s!=null&&o.set(s,r)}let i=new Set,a=[];for(let r=0;r<e.length;r++){let s=e[r],l=t.keyOf(s,r);i.add(l);let d=o.get(l);d||(d=t.create(s,r),d.setAttribute(Dt,l)),t.update?.(d,s,r),n.children[r]!==d&&n.insertBefore(d,n.children[r]??null),a.push(d)}for(let[r,s]of o)i.has(r)||s.remove();return a}var Lt=[125,69];function Mt(n){return n===0?.4:n===1?.3:.15}function Ue(n,e,t,o,i=!1,a=!1){let r=n.querySelector(".magicx-aia-pill-list");if(r||(r=document.createElement("span"),r.className="magicx-aia-pill-list",n.appendChild(r)),a&&e.length===0){r.setAttribute("data-aia-pill-list-loading",""),r.innerHTML="";for(let s=0;s<Lt.length;s++){let l=Lt[s],d=document.createElement("span");d.setAttribute("data-aia-pill-skeleton",""),d.className=`magicx-aia-pill magicx-aia-pill--skeleton${i?" magicx-aia-pill--rounded":""}`,d.style.width=`${l}px`,d.style.opacity=String(Mt(s)),r.appendChild(d)}return}a?r.setAttribute("data-aia-pill-list-loading",""):r.removeAttribute("data-aia-pill-list-loading");for(let s of r.querySelectorAll("[data-aia-pill-skeleton]"))s.remove();$e(r,e,{keyOf:s=>`${s.type}-${s.text}`,create:s=>{let l=document.createElement("button");return l.type="button",l.tabIndex=-1,l.setAttribute("data-aia-pill",""),l.setAttribute("contenteditable","false"),l.textContent=s.text,l.addEventListener("mousedown",d=>d.preventDefault()),l},update:(s,l,d)=>{let u=s,p=["magicx-aia-pill"];i&&p.push("magicx-aia-pill--rounded"),d===t&&!a&&p.push("magicx-aia-pill--active"),a&&p.push("magicx-aia-pill--skeleton"),u.className=p.join(" "),u.style.width="",u.style.opacity=String(Mt(d)),a?(u.setAttribute("data-aia-loading",""),u.disabled=!0,u.onclick=null):(u.removeAttribute("data-aia-loading"),u.disabled=!1,u.onclick=()=>o(d))}})}function it(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var In=[159,119,164];function qe(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 Ge(n,e){let{filteredOptions:t,activeIndex:o,isOpen:i,isLoading:a,pills:r,showPills:s,onSelect:l,onHighlight:d,onPillClick:u}=e,p=s&&r.length>0,m=t.length>0;i&&(m||p||a)?n.classList.add("magicx-aia-dropdown--visible"):n.classList.remove("magicx-aia-dropdown--visible"),a?n.setAttribute("data-aia-loading",""):n.removeAttribute("data-aia-loading");let g=p||a&&s,b=n.querySelector(".magicx-aia-pill-bar");g?(b||(b=document.createElement("div"),b.className="magicx-aia-pill-bar",b.setAttribute("data-aia-pillbar",""),n.insertBefore(b,n.firstChild)),Ue(b,r,0,u,!0,a)):b&&b.remove();let f=n.querySelector(".magicx-aia-grid");m?(f||(f=document.createElement("div"),f.className="magicx-aia-grid",n.appendChild(f)),Cn(f,t,o,l,d,e.listboxId,a)):f&&f.remove();let c=n.querySelector(".magicx-aia-skeleton-bars");if(a&&!m){if(!c){c=document.createElement("div"),c.className="magicx-aia-skeleton-bars",c.setAttribute("data-aia-skeleton-bars","");for(let h of In){let x=document.createElement("span");x.className="magicx-aia-skeleton-bar",x.style.width=`${h}px`,c.appendChild(x)}n.appendChild(c)}}else c&&c.remove()}function Cn(n,e,t,o,i,a,r){let s=r?"1":"0";$e(n,e,{keyOf:l=>`${l.text}\0${s}`,create:l=>An(l,r),update:(l,d,u)=>{let p=u===t&&!r;l.id=`${a}-option-${u}`,l.dataset.aiaIndex=String(u),l.setAttribute("aria-selected",String(p)),l.classList.toggle("magicx-aia-option--highlighted",p),!r&&d.is_tappable?(l.onclick=()=>{l.classList.add("magicx-aia-option--pressed"),o(d),setTimeout(()=>l.classList.remove("magicx-aia-option--pressed"),500)},l.onmouseenter=()=>{let m=Number.parseInt(l.dataset.aiaIndex??"-1",10);m>=0&&i(m)}):(l.onclick=null,l.onmouseenter=null)}})}function An(n,e){let t=document.createElement("div");t.setAttribute("role","option"),t.setAttribute("data-aia-option",""),e&&t.setAttribute("data-aia-loading",""),t.tabIndex=e||!n.is_tappable?-1:0;let o=["magicx-aia-option"];n.is_tappable?o.push("magicx-aia-option--tappable"):o.push("magicx-aia-option--non-tappable"),t.className=o.join(" ");let i=document.createElement("div");i.className="magicx-aia-streaks",t.appendChild(i);let a=document.createElement("div");a.className="magicx-aia-streaks-vert",t.appendChild(a);let r=document.createElement("span");if(r.className="magicx-aia-option-content",r.textContent=n.icon?`${n.icon} ${n.text}`:n.text,n.tag){let s=document.createElement("span");s.className="magicx-aia-option-tag",s.textContent=n.tag,r.appendChild(s)}return t.appendChild(r),t}function Rt(n,e){let t=qe(e.listboxId);return n.appendChild(t),{dropdown:t}}function rt(n,e,t){Ge(n.dropdown,{suggestions:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,onSelect:t.selectOption,onHighlight:o=>t.store.set({activeDropdownIndex:o}),onPillClick:t.setActivePill})}function Qe(n){let{input:e,segments:t,newParamId:o,editingParamId:i,placeholderText:a,isFocused:r}=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(f=>`${f.type}:${f.value}`).join("\0"),d=e.dataset.segKey??"",u=e.dataset.newParamId??"",p=e.dataset.editingParamId??"";if(l===d&&(o??"")===u&&(i??"")===p)return;let m=r?$(e):null;e.dataset.segKey=l,e.dataset.newParamId=o??"",e.dataset.editingParamId=i??"";let v=e.ownerDocument??document,g=v.createDocumentFragment(),b=0;for(let f of t)if(b+=f.value.length,f.type==="completed"){let c=v.createElement("strong");c.dataset.seg="completed",c.dataset.paramId=f.param.id;let h=f.param.id===o,x=f.param.id===i,S=["magicx-aia-segment","magicx-aia-segment--completed"];h&&S.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),x&&S.push("magicx-aia-segment--editing"),c.className=S.join(" "),c.textContent=f.value,g.appendChild(c)}else g.appendChild(v.createTextNode(f.value));e.replaceChildren(g),e.dataset.aiaTextLength=String(b),m!=null&&M(e,Math.max(0,Math.min(m,b)))}var En='<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 Nt(n,e){let{listboxId:t}=e,o=qe(t);n.appendChild(o);let i=document.createElement("div");i.className="magicx-aia-input-wrapper",n.appendChild(i);let a=document.createElement("div");a.className="magicx-aia-editor",a.setAttribute("data-aia-editor",""),i.appendChild(a);let r=document.createElement("div");r.className="magicx-aia-input",r.setAttribute("data-aia-input",""),r.setAttribute("contenteditable",Tn()?"plaintext-only":"true"),r.setAttribute("role","combobox"),r.setAttribute("aria-autocomplete","list"),r.setAttribute("aria-haspopup","listbox"),r.setAttribute("aria-controls",t),r.setAttribute("aria-expanded","false"),r.setAttribute("spellcheck","true"),r.setAttribute("enterkeyhint","send"),a.appendChild(r);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=En,i.appendChild(l),d=l):e.submitButton!==null&&(d=e.submitButton,d.hasAttribute("data-aia-submit")||d.setAttribute("data-aia-submit",""),i.appendChild(d));let u=new AbortController,{signal:p}=u,m=!1,v=0,g=()=>{let c=me(r),x=c.length>0&&c[0]!==c[0].toUpperCase()?c[0].toUpperCase()+c.slice(1):c;e.handleChange(x)},b=()=>{let c=(r.ownerDocument??document).getSelection();if(!c||c.rangeCount===0)return null;let h=c.anchorNode;return!h||!r.contains(h)?null:(h.nodeType===Node.ELEMENT_NODE?h:h.parentElement)?.closest('strong[data-seg="completed"][data-param-id]')?.dataset.paramId??null};i.addEventListener("click",c=>{c.target?.closest("[data-aia-pill]")||r.focus()},{signal:p}),r.addEventListener("input",()=>{m||(v=performance.now(),g(),e.handleCaretAfterInput($(r)))},{signal:p});let f=r.ownerDocument??document;return f.addEventListener("selectionchange",()=>{let c=f.getSelection();if(!c||c.rangeCount===0||!r.contains(c.anchorNode))return;let h=b(),x=e.store.get().editingParam?.id??null;if(h&&h!==x){e.startEditingParam(h);return}performance.now()-v<50||e.handleCaretMove($(r))},{signal:p}),r.addEventListener("compositionstart",()=>{m=!0},{signal:p}),r.addEventListener("compositionend",()=>{m=!1,g()},{signal:p}),r.addEventListener("beforeinput",c=>{let h=c,x=h.inputType;if(x==="insertParagraph"||x==="insertLineBreak"||x==="insertFromDrop"){c.preventDefault();return}if(x.startsWith("insert")||x.startsWith("delete")){let S=x.startsWith("delete")?"":h.data??"";e.replaceEditingRange(S)&&c.preventDefault()}},{signal:p}),r.addEventListener("paste",c=>{c.preventDefault();let h=(c.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!h)return;let x=r.ownerDocument??document,S=x.getSelection();if(!S||S.rangeCount===0)return;let R=S.getRangeAt(0);if(!r.contains(R.startContainer))return;R.deleteContents();let K=x.createTextNode(h);R.insertNode(K),R.setStartAfter(K),R.collapse(!0),S.removeAllRanges(),S.addRange(R),g()},{signal:p}),r.addEventListener("keydown",c=>e.handleKeyDown(c),{signal:p}),r.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:p}),r.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:p}),d&&d.addEventListener("click",c=>{let h=e.store.get();if(!(!!h.text||h.completedParams.length>0)||!e.onSubmit)return;c.stopPropagation();let{rawQuery:S,completedParams:R}=F(h.text,h.completedParams);e.onSubmit({query:h.text.trim(),raw_query:S,completed_params:R}),e.afterSubmit?.()},{signal:p}),e.autoFocus!==!1&&r.focus(),{input:r,inlinePillContainer:s,dropdown:o,submitButton:l,abort:u}}function at(n,e,t){let{input:o,inlinePillContainer:i,dropdown:a,submitButton:r}=n,{pillPlacement:s,setActivePill:l,selectOption:d,store:u}=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"),r){let f=!!e.text||e.completedParams.length>0;r.disabled=!f}let m=o.dataset.newParamId??"",v=e.newParamId!==null&&e.newParamId!==m;if(Qe({input:o,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused}),s==="inline"){let f=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;f||e.actionableSuggestions.length>0?Ue(i,e.actionableSuggestions,0,l,!1,f):it(i)}else it(i);v?(o.focus(),M(o,e.caretOffset??e.text.length)):e.isFocused&&me(o)!==e.text&&M(o,e.text.length);let g=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:null,b=g??e.actionableSuggestions[0];Ge(a,{suggestions:b?[{...b,options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation,listboxId:t.listboxId,pills:g?[g]:e.actionableSuggestions,showPills:s==="dropdown",onSelect:d,onHighlight:f=>u.set({activeDropdownIndex:f}),onPillClick:l})}function Ht(n,e){let t=n.actionableSuggestions[0];if(!t)return null;let o=n.filterBase,i=n.text.slice(0,o),a=i.length===0&&n.text.length===0,r=i.length===0&&n.text.length>0&&n.placeholderText.length>0&&n.placeholderText.toLowerCase().startsWith(n.text.toLowerCase());(a||r)&&n.placeholderText&&(i=`${n.placeholderText} `);let s=yt(i,e.text);s>0&&(i=i.slice(0,i.length-s));let l=i.length>0&&i[i.length-1]!==" ",d=`${i}${l?" ":""}${e.text} `,u=(a||r)&&d.length>0?d[0].toUpperCase()+d.slice(1):d,p=u.toLowerCase().lastIndexOf(e.text.toLowerCase()),m=p>=0?u.slice(p,p+e.text.length):e.text,v={id:crypto.randomUUID(),placeholder:"",type:t.type,text:m,kind:e.kind,suggestionType:t.type,suggestionPlaceholder:t.text,options:t.options??[],metadata:e.metadata},g=n.actionableSuggestions.length-1;return{patch:{text:u,filterBase:u.length,completedParams:[...n.completedParams,v],newParamId:v.id,caretOffset:u.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:g>0,inSelectionAnimation:!0},telemetry:{selectedOption:e.text,otherOptions:n.filteredOptions.filter(b=>b.text!==e.text).map(b=>b.text)},consumedSuggestion:t,remainingActionable:g}}function Ft(n){let e=n,t=new Set;return{get:()=>e,set:o=>{let i=typeof o=="function"?o(e):o,a={...e,...i},r=e;e=a;for(let s of t)s(a,r)},subscribe:o=>(t.add(o),()=>{t.delete(o)})}}function Bt(n,e){let t,o,i=a=>(a!==t&&(t=a,o=e(a)),o);return{get:()=>{let a=n.get();return{...a,...i(a)}},set:a=>{typeof a=="function"?n.set(r=>{let s={...r,...i(r)};return a(s)}):n.set(a)},subscribe:a=>n.subscribe((r,s)=>{let l={...s,...i(s)},d={...r,...i(r)};a(d,l)})}}var st=!1;function Kt(){if(st||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){st=!0;return}st=!0;let n=document.createElement("style");n.setAttribute("data-magicx-aia",""),n.textContent=_n,document.head.appendChild(n)}var _n="";var Ve=class{constructor(){this.listeners={}}on(e,t){let o=(...a)=>t(...a),i=this.listeners[e];return i||(i=new Set,this.listeners[e]=i),i.add(o),()=>{this.listeners[e]?.delete(o)}}emit(e,...t){let o=this.listeners[e];if(o)for(let i of o)i(...t)}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var je=class{constructor(){this.timers=new Map}schedule(e,t,o){this.clear(e);let i=setTimeout(()=>{this.timers.delete(e),t()},o);this.timers.set(e,i)}clear(e){let t=this.timers.get(e);t!==void 0&&(clearTimeout(t),this.timers.delete(e))}clearAll(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};var kn="newParam",zt="suggestionRemoval",On="selectionAnimation",Dn=650,Ln=0;function Mn(){return`:ac-${++Ln}:`}var Wt=500;function $t(){return{text:"",completedParams:[],suggestions:[],activeDropdownIndex:-1,newParamId:null,isLoading:!1,isReady:!1,error:null,filterBase:0,filterInProgress:!1,pillTapped:!1,skipNextFetch:!1,lastRawQuery:"",isFocused:!1,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:null,inSelectionAnimation:!1}}var Xe=class{constructor(e,t={}){this.inputStore=Ft($t());this._listboxId=Mn();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new je;this.emitter=new Ve;this.sessionId=crypto.randomUUID();this.emitSubmit=e=>this.emitter.emit("submit",e);this.emitError=e=>this.emitter.emit("error",e);this.container=e,this.opts=t,this.renderMode=t.renderMode??"full",this.store=Bt(this.inputStore,o=>Ot(o,this.opts)),t.onSubmit&&this.emitter.on("submit",t.onSubmit),t.onError&&this.emitter.on("error",t.onError),t.onChange&&this.emitter.on("change",t.onChange),t.onParamsChange&&this.emitter.on("paramsChange",t.onParamsChange),t.onStateChange&&this.emitter.on("stateChange",t.onStateChange),t.onFocus&&this.emitter.on("focus",t.onFocus),t.onBlur&&this.emitter.on("blur",t.onBlur),t.value!==void 0&&this.store.set({text:t.value}),t.completedParams!==void 0&&this.store.set({completedParams:t.completedParams}),this.pillsController=new Ke(this.store,{onPillSelected:({rawQuery:o,selectedPill:i,otherPills:a})=>{this.fireTelemetry("pill",{raw_query:o,selected_pill:i,other_pills:a})}}),this.reEdit=new We({store:this.store,scheduleSetCursor:o=>this.scheduleSetCursor(o),fireTelemetry:(o,i)=>this.fireTelemetry(o,i),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer()}),this.fetchController=new Fe(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.emitter.hasListeners("error")?this.emitError:void 0,()=>this.sessionId,{onAutoMatch:({active:o,matched:i,rawQuery:a})=>{this.fireTelemetry("option",{raw_query:a,selected_option:i.text,other_options:(o.options??[]).filter(r=>r.text!==i.text).map(r=>r.text)})}}),this.keyboardController=new Be(this.store,{columns:t.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.emitter.hasListeners("submit")?this.emitSubmit:void 0,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,i)=>{o.text!==i.text&&this.emitter.emit("change",o.text),o.completedParams!==i.completedParams&&this.emitter.emit("paramsChange",o.completedParams),o.isFocused!==i.isFocused&&(o.isFocused?this.emitter.emit("focus"):this.emitter.emit("blur")),this.emitter.emit("stateChange",o)})),this.unsubscribers.push(this.store.subscribe(()=>this.maybeExitReEditOnNoMatch())),this.renderMode!=="headless"&&(Kt(),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({...$t(),skipNextFetch:!0}),this.sessionId=crypto.randomUUID(),this.fetchController.doFetch("",[])}destroy(){this.fetchController.dispose(),this.modeController?.destroy(),this.timers.clearAll(),this.emitter.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);let t=this.store.get().text.length;this.store.set({caretOffset:t,isFocused:!0}),this.scheduleSetCursor(t)}removeLastParam(){this.pillsController.removeLastParam()}removeParamAtCaret(e){let t=this.store.get(),{text:o,completedParams:i}=t,a=0;for(let r=0;r<i.length;r++){let s=i[r],l=o.indexOf(s.text,a);if(l===-1)continue;let d=l,u=l+s.text.length;if(e>d&&e<=u){let p=vt(o,e),m=o.slice(0,p)+o.slice(e),v=i.filter((g,b)=>b!==r);return this.store.set(g=>({text:m,filterBase:Math.min(g.filterBase,m.length),completedParams:v,pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(p),!0}a=u}return!1}scheduleSetCursor(e){queueMicrotask(()=>{let t=this.domRefs;t?(t.input.focus(),M(t.input,e)):this.opts.setCursor?.(e)})}clearNewParamId(){this.store.set({newParamId:null})}startEditingParam(e){this.reEdit.start(e)}replaceEditingRange(e){return this.reEdit.replaceRange(e)}exitEditMode(){this.reEdit.exit()}handleCaretAfterInput(e){this.reEdit.caretAfterInput(e)}handleCaretMove(e){this.reEdit.caretMove(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.store.subscribe(t=>e(t))}getState(){return this.store.get()}get listboxId(){return this._listboxId}get isReady(){return this.store.get().isReady}on(e,t){return this.emitter.on(e,t)}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||e.showNonTappableOptions!==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.reEdit.selectOption(e);return}let o=Ht(t,e);if(o&&(this.fireTelemetry("option",{raw_query:F(t.text,t.completedParams).rawQuery,selected_option:o.telemetry.selectedOption,other_options:o.telemetry.otherOptions}),this.store.set(o.patch),this.startSelectionAnimationTimer(),this.timers.clear(zt),o.remainingActionable>0)){let i=o.consumedSuggestion;this.timers.schedule(zt,()=>{this.store.set(a=>({suggestions:a.suggestions.filter(r=>r!==i)}))},Wt)}}startSelectionAnimationTimer(){this.timers.schedule(On,()=>this.store.set({inSelectionAnimation:!1}),Wt)}fireTelemetry(e,t){let o=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");It({source:o,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}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 he(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.emitter.hasListeners("submit")?e.emitSubmit:void 0},afterSubmit:()=>e.reset(),submitButton:this.opts.submitButton,autoFocus:this.opts.autoFocus??!0,selectOption:o=>this.selectOption(o),setActivePill:o=>this.pillsController.setActivePill(o),handleKeyDown:o=>this.keyboardController.handleKeyDown(o),handleChange:o=>this.handleChange(o),startEditingParam:o=>this.startEditingParam(o),handleCaretAfterInput:o=>this.handleCaretAfterInput(o),handleCaretMove:o=>this.handleCaretMove(o),replaceEditingRange:o=>this.replaceEditingRange(o)};this.domRefs=Nt(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&at(this.domRefs,this.store.get(),t)}),at(this.domRefs,this.store.get(),t),this.subscribeNewParamTimer()}buildAndRenderDropdown(){let e={store:this.store,listboxId:this.listboxId,selectOption:t=>this.selectOption(t),setActivePill:t=>this.pillsController.setActivePill(t)};this.dropdownRefs=Rt(this.container,e),this.subscribeBatchedRender(()=>{this.dropdownRefs&&rt(this.dropdownRefs,this.store.get(),e)}),rt(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.timers.schedule(kn,()=>this.store.set({newParamId:null}),Dn)}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:o,invalid:i}=St(e,t.completedParams);i.length>0&&this.store.set({completedParams:o}),this.maybePromoteExactMatch(e)}maybeExitReEditOnNoMatch(){let e=this.store.get();if(!e.editingParam||e.editingAnchor==null||e.completedParams.some(s=>s.id===e.editingParam?.id))return;let t=e.caretOffset??e.editingAnchor,o=e.text.slice(e.editingAnchor,t);if(le(e.editingParam.options,o).some(s=>s.is_tappable))return;this.reEdit.exit();let{rawQuery:a,completedParams:r}=F(e.text,e.completedParams);this.fetchController.doFetch(a,r)}maybePromoteExactMatch(e){let t=this.store.get(),o=ze({mode:"fresh",text:e,completedParams:t.completedParams,suggestions:t.suggestions,filterBase:t.filterBase,filterInProgress:t.filterInProgress});o&&this.store.set(o.patch)}};var Rn={text:"",completedParams:[],suggestions:[],activeDropdownIndex:-1,newParamId:null,isLoading:!0,isReady:!1,error:null,segments:[],actionableSuggestions:[],filteredOptions:[],placeholderText:"",isDropdownOpen:!1,filterBase:0,filterInProgress:!1,pillTapped:!1,skipNextFetch:!1,lastRawQuery:"",isFocused:!1,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:null,inSelectionAnimation:!1};function Je({onSubmit:n,onError:e,optionOverrides:t,maskCompletedText:o,apiConfig:i,columns:a=2,dropdownTrigger:r,closeDropdownOnBlur:s,showNonTappableOptions:l,onFocus:d,onBlur:u,value:p,completedParams:m,onChange:v,onParamsChange:g,source:b,setCursor:f}){let c=(0,k.useRef)(null),[h,x]=(0,k.useState)(null),S=(0,k.useRef)(n);S.current=n;let R=(0,k.useRef)(e);R.current=e;let K=(0,k.useRef)(v);K.current=v;let ne=(0,k.useRef)(g);ne.current=g;let J=(0,k.useRef)(d);J.current=d;let z=(0,k.useRef)(u);z.current=u;let oe=(0,k.useRef)(f);oe.current=f,(0,k.useEffect)(()=>{if(typeof document>"u")return;let y=new Xe(document.createElement("div"),{renderMode:"headless",apiConfig:i,optionOverrides:t,maskCompletedText:o,columns:a,dropdownTrigger:r,closeDropdownOnBlur:s,showNonTappableOptions:l,source:b,value:p,completedParams:m,onSubmit:(...N)=>S.current?.(...N),onError:(...N)=>R.current?.(...N),onChange:(...N)=>K.current?.(...N),onParamsChange:(...N)=>ne.current?.(...N),onFocus:()=>J.current?.(),onBlur:()=>z.current?.(),setCursor:N=>oe.current?.(N)});c.current=y,x(y.getState());let H=y.subscribe(N=>x(N));return()=>{H(),y.destroy(),c.current===y&&(c.current=null)}},[]),(0,k.useEffect)(()=>{p!==void 0&&c.current?.setValue(p)},[p]),(0,k.useEffect)(()=>{m!==void 0&&c.current?.setCompletedParams(m)},[m]);let U=JSON.stringify(i??null),Y=(0,k.useRef)(t),de=(0,k.useRef)(0);if(t!==Y.current){let y=Y.current,H=t,N=Object.keys(y??{}),ce=Object.keys(H??{});(N.length!==ce.length||ce.some(ve=>!y?.[ve]||H[ve]!==y[ve]))&&de.current++,Y.current=t}(0,k.useEffect)(()=>{c.current?.update({apiConfig:i,optionOverrides:t,dropdownTrigger:r,closeDropdownOnBlur:s,showNonTappableOptions:l})},[U,de.current,r,s,l]);let V=(0,k.useRef)(null);V.current===null&&(V.current={handleTextChange:y=>c.current?.handleTextChange(y),handleKeyDown:y=>{let H="nativeEvent"in y?y.nativeEvent:y;c.current?.handleKeyDown(H)},setFocused:y=>c.current?.setFocused(y),startEditingParam:y=>c.current?.startEditingParam(y),exitEditMode:()=>c.current?.exitEditMode(),handleCaretAfterInput:y=>c.current?.handleCaretAfterInput(y),handleCaretMove:y=>c.current?.handleCaretMove(y),replaceEditingRange:y=>c.current?.replaceEditingRange(y)??!1,setActivePill:y=>c.current?.setActivePill(y),removeLastParam:()=>c.current?.removeLastParam(),clearNewParamId:()=>c.current?.clearNewParamId(),reset:()=>c.current?.reset(),selectOption:y=>c.current?.selectOption(y),setActiveDropdownIndex:y=>c.current?.setActiveDropdownIndex(y),handleFocus:()=>c.current?.setFocused(!0),handleBlur:()=>c.current?.setFocused(!1)});let T=V.current,be=(0,k.useCallback)(y=>{let H=y.target.value,ce=H.length>0&&!y.nativeEvent?.isComposing&&H[0]!==H[0].toUpperCase()?H[0].toUpperCase()+H.slice(1):H;c.current?.handleTextChange(ce)},[]),ie=(0,k.useCallback)(y=>{c.current?.handleKeyDown(y.nativeEvent)},[]),j=c.current,I=h??Rn,xe=p!==void 0?p:I.text,w=m!==void 0?m:I.completedParams,P=I.actionableSuggestions,E=P[0],_=j?.listboxId??"",O=I.activeDropdownIndex>=0&&j?`${_}-option-${I.activeDropdownIndex}`:void 0,L=I.editingParam,X=L?{type:L.suggestionType,text:L.suggestionPlaceholder,required:!0,options:L.options}:null,Z=X??E,Ze=X?[X]:P,Pe=!j||I.isLoading&&!I.editingParam&&!I.inSelectionAnimation;return{completedParams:w,suggestionPills:P,setActivePill:T.setActivePill,removeLastParam:T.removeLastParam,segments:I.segments,newParamId:I.newParamId,clearNewParamId:T.clearNewParamId,suggestions:I.suggestions,activeIndex:I.activeDropdownIndex,isReady:I.isReady,isLoading:Pe,isFocused:I.isFocused,isDropdownOpen:I.isDropdownOpen,placeholderText:I.placeholderText,listboxId:_,error:I.error,handleTextChange:T.handleTextChange,handleKeyDown:T.handleKeyDown,setFocused:T.setFocused,editingParam:L,editingAnchor:I.editingAnchor,caretOffset:I.caretOffset,startEditingParam:T.startEditingParam,exitEditMode:T.exitEditMode,handleCaretAfterInput:T.handleCaretAfterInput,handleCaretMove:T.handleCaretMove,replaceEditingRange:T.replaceEditingRange,inputProps:{value:xe,placeholder:I.placeholderText||void 0,onChange:be,onKeyDown:ie,onFocus:T.handleFocus,onBlur:T.handleBlur,role:"combobox","aria-expanded":I.isDropdownOpen,"aria-activedescendant":O,"aria-autocomplete":"list","aria-controls":_},reset:T.reset,dropdownProps:{suggestions:Z?[{...Z,options:I.filteredOptions}]:[],activeIndex:I.activeDropdownIndex,onSelect:T.selectOption,onHighlight:T.setActiveDropdownIndex,isOpen:I.isDropdownOpen,id:_,pills:Ze,onPillClick:T.setActivePill,isLoading:Pe}}}var C=require("react");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}function Ut(n){let{segments:e,newParamId:t,editingParam:o,editingAnchor:i,caretOffset:a,placeholderText:r,isFocused:s,isDropdownOpen:l,listboxId:d,activeDescendantId:u,autoFocus:p,handleTextChange:m,handleKeyDown:v,handleCaretAfterInput:g,handleCaretMove:b,startEditingParam:f,replaceEditingRange:c,setFocused:h}=n,x=(0,C.useRef)(null),S=(0,C.useRef)(!1),R=(0,C.useRef)(""),K=(0,C.useRef)(""),ne=(0,C.useRef)(null),J=(0,C.useRef)(0);ne.current=a,(0,C.useEffect)(()=>{if(!p)return;let w=x.current;w&&(document.activeElement===w?h(!0):w.focus())},[p,h]),(0,C.useEffect)(()=>{let w=x.current;if(!w)return;let P=w.ownerDocument??document,E=()=>{let _=P.getSelection();if(!_||_.rangeCount===0||!_.anchorNode||!w.contains(_.anchorNode))return;let O=_.anchorNode,Z=(O.nodeType===Node.ELEMENT_NODE?O:O.parentElement)?.closest('strong[data-seg="completed"][data-param-id]')?.dataset.paramId??null;if(Z&&Z!==o?.id){f(Z);return}performance.now()-J.current<50||b($(w))};return P.addEventListener("selectionchange",E),()=>P.removeEventListener("selectionchange",E)},[o,f,b]),(0,C.useLayoutEffect)(()=>{let w=x.current;w&&Qe({input:w,segments:e,newParamId:t,editingParamId:o?.id??null,placeholderText:r??"",isFocused:s})},[e,t,o,r,s]),(0,C.useLayoutEffect)(()=>{let w=R.current,P=t??"";if(R.current=P,!P||P===w)return;let E=x.current;if(!E)return;E.focus();let _=ne.current??De(E);M(E,_)},[t]),(0,C.useLayoutEffect)(()=>{let w=K.current,P=o?.id??"";if(K.current=P,!P||P===w||i==null)return;let E=x.current;E&&M(E,i)},[o,i]);let z=(0,C.useCallback)(()=>{if(S.current)return;let w=x.current;if(!w)return;let P=me(w),_=P.length>0&&P[0]!==P[0].toUpperCase()?P[0].toUpperCase()+P.slice(1):P;m(_)},[m]),oe=(0,C.useCallback)(()=>{J.current=performance.now(),z();let w=x.current;w&&g($(w))},[z,g]);(0,C.useEffect)(()=>{let w=x.current;if(!w)return;let P=E=>{let _=E,O=_.inputType;if(O==="insertParagraph"||O==="insertLineBreak"||O==="insertFromDrop"){E.preventDefault();return}if(O.startsWith("insert")||O.startsWith("delete")){let L=O.startsWith("delete")?"":_.data??"";c(L)&&E.preventDefault()}};return w.addEventListener("beforeinput",P),()=>w.removeEventListener("beforeinput",P)},[c]);let U=(0,C.useCallback)(()=>{S.current=!0},[]),Y=(0,C.useCallback)(()=>{S.current=!1,z()},[z]),de=(0,C.useCallback)(w=>{w.preventDefault();let P=x.current;if(!P)return;let E=(w.clipboardData.getData("text/plain")??"").replace(/\r?\n/g," ");if(!E)return;let _=P.ownerDocument??document,O=_.getSelection();if(!O||O.rangeCount===0)return;let L=O.getRangeAt(0);if(!P.contains(L.startContainer))return;L.deleteContents();let X=_.createTextNode(E);L.insertNode(X),L.setStartAfter(X),L.collapse(!0),O.removeAllRanges(),O.addRange(L),z()},[z]),V=(0,C.useCallback)(w=>v(w),[v]),T=(0,C.useCallback)(()=>h(!0),[h]),be=(0,C.useCallback)(()=>h(!1),[h]),ie=(0,C.useCallback)(()=>x.current?.focus(),[]),j=(0,C.useCallback)(()=>x.current?.blur(),[]),I=(0,C.useCallback)(()=>{let w=x.current;return w?me(w):""},[]),xe=Nn()?"plaintext-only":"true";return{inputRef:x,editorProps:{ref:x,contentEditable:xe,suppressContentEditableWarning:!0,tabIndex:0,role:"combobox","aria-autocomplete":"list","aria-haspopup":"listbox","aria-controls":d,"aria-expanded":l,"aria-activedescendant":u,spellCheck:!0,enterKeyHint:"send",onInput:oe,onKeyDown:V,onCompositionStart:U,onCompositionEnd:Y,onPaste:de,onFocus:T,onBlur:be},getPlainText:I,focus:ie,blur:j}}var B=require("react/jsx-runtime");function Hn(n){return n!=="auto"?n:typeof window>"u"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}var qt=(0,D.forwardRef)(function({onSubmit:e,onError:t,optionOverrides:o,maskCompletedText:i,className:a,apiConfig:r,columns:s,pillPlacement:l="inline",mode:d="auto",optionsPosition:u="below",animations:p=!0,dropdownTrigger:m,closeDropdownOnBlur:v,showNonTappableOptions:g,autoFocus:b=!0,onFocus:f,onBlur:c,value:h,completedParams:x,onChange:S,onParamsChange:R,submitButton:K},ne){let J=(0,D.useRef)(null),z=(0,D.useRef)(null),oe=(0,D.useRef)(()=>{}),U=(0,D.useRef)(null),Y=(0,D.useRef)(null);(0,D.useEffect)(()=>{let A=J.current;if(A)return U.current?U.current.setMode(d):U.current=new he(A,d),()=>{U.current?.destroy(),U.current=null}},[d]);let de=(0,D.useCallback)(A=>{let W=Y.current?.current;W&&(W.focus(),M(W,A))},[]),{completedParams:V,suggestionPills:T,setActivePill:be,segments:ie,newParamId:j,clearNewParamId:I,placeholderText:xe,isFocused:w,isDropdownOpen:P,isLoading:E,activeIndex:_,listboxId:O,handleTextChange:L,handleKeyDown:X,setFocused:Z,editingParam:Ze,editingAnchor:Pe,caretOffset:y,startEditingParam:H,handleCaretAfterInput:N,handleCaretMove:ce,replaceEditingRange:ve,dropdownProps:Gt,reset:Ie}=Je({onSubmit:A=>oe.current(A),onError:t,optionOverrides:o,maskCompletedText:i,apiConfig:r,columns:s,dropdownTrigger:m,closeDropdownOnBlur:v,showNonTappableOptions:g,onFocus:f,onBlur:c,value:h,completedParams:x,onChange:S,onParamsChange:R,source:"full-sdk",setCursor:de});(0,D.useEffect)(()=>{if(!j)return;let A=window.setTimeout(()=>I(),650);return()=>window.clearTimeout(A)},[j,I]);let Qt=_>=0?`${O}-option-${_}`:void 0,{inputRef:et,editorProps:Vt,focus:Ce,blur:lt,getPlainText:dt}=Ut({segments:ie,newParamId:j,editingParam:Ze,editingAnchor:Pe,caretOffset:y,placeholderText:xe,isFocused:w,isDropdownOpen:P,listboxId:O,activeDescendantId:Qt,autoFocus:b,handleTextChange:L,handleKeyDown:X,handleCaretAfterInput:N,handleCaretMove:ce,startEditingParam:H,replaceEditingRange:ve,setFocused:Z});Y.current=et,(0,D.useLayoutEffect)(()=>{let A=z.current,W=et.current;if(!A||!W)return;let Ee=()=>{let pt=A.firstElementChild;if(!pt)return;if(W.dataset.aiaEmpty==="true"){A.setAttribute("data-aia-pill-wrapped","");return}let Yt=pt.getBoundingClientRect(),Zt=W.getBoundingClientRect();Yt.top>=Zt.bottom-2?A.setAttribute("data-aia-pill-wrapped",""):A.removeAttribute("data-aia-pill-wrapped")};Ee();let ct=new ResizeObserver(Ee);return ct.observe(W),()=>ct.disconnect()},[ie,T.length,E,et]),(0,D.useImperativeHandle)(ne,()=>({focus:Ce,blur:lt,reset:Ie,setMode:A=>U.current?.setMode(A)}),[Ce,lt,Ie]);let Ae=!!ie.length||V.length>0,tt=(0,D.useCallback)(()=>{if(!Ae)return;let A=dt(),{rawQuery:W,completedParams:Ee}=F(A,V);e({query:A.trim(),raw_query:W,completed_params:Ee}),Ie()},[Ae,V,e,Ie,dt]);oe.current=tt;let jt=(0,D.useCallback)(A=>{A.target?.closest("[data-aia-pill]")||Ce()},[Ce]),Xt=l==="inline",Jt=l==="dropdown";return(0,B.jsxs)("div",{ref:J,className:`magicx-aia ${ee.container} ${a??""}`,"data-pill-placement":l,"data-options-position":u,"data-animations":p?"on":"off","data-mode":Hn(d),children:[(0,B.jsx)(_e,{...Gt,showPills:Jt}),(0,B.jsxs)("div",{className:ee.inputWrapper,onClick:jt,children:[(0,B.jsxs)("div",{className:ee.editorArea,"data-aia-editor":"",children:[(0,B.jsx)("div",{...Vt,className:ee.input,"data-aia-input":""}),Xt&&(E||T.length>0)&&(0,B.jsx)("span",{ref:z,className:ee.pillListContainer,"data-aia-pill-list-container":"",children:(0,B.jsx)(we,{pills:T,activePillIndex:0,onSelectPill:be,loading:E})})]}),K===null?null:K===void 0?(0,B.jsx)("button",{type:"button","data-aia-submit":"",className:ee.submitButton,disabled:!Ae,onClick:A=>{A.stopPropagation(),tt()},"aria-label":"Submit",children:(0,B.jsx)("svg",{width:"18",height:"18",viewBox:"0 0 18 18",fill:"none",role:"img","aria-label":"Submit",children:(0,B.jsx)("path",{d:"M9 14V4M9 4L4 9M9 4L14 9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}):(0,B.jsx)("span",{"data-aia-submit":"",className:ee.submitSlot,onClick:A=>{Ae&&(A.stopPropagation(),tt())},children:K})]})]})});0&&(module.exports={AIAutocomplete,AIAutocompleteDropdown,useAIAutocomplete});
|
|
802
823
|
//# sourceMappingURL=index.js.map
|