@magicx-eng/ai-autocomplete-react 0.1.43 → 0.1.44
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +3 -69
- package/dist/index.d.ts +3 -69
- package/dist/index.js +7 -7
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +7 -7
- package/dist/index.mjs.map +1 -1
- package/package.json +17 -22
package/dist/index.d.mts
CHANGED
|
@@ -1,76 +1,15 @@
|
|
|
1
1
|
import * as react from 'react';
|
|
2
2
|
import { ReactNode, KeyboardEvent, ChangeEvent } from 'react';
|
|
3
|
+
import { AutocompleteResult, OptionOverrides, APIConfig, AppearanceMode, CompletedParamState, Suggestion, SuggestionOption, Segment } from '@magicx-eng/ai-autocomplete-vanilla';
|
|
4
|
+
export { APIConfig, APIKeyConfig, AccessTokenConfig, AccessTokenResult, AppearanceMode, AutocompleteResult, CompletedParam, CompletedParamState, OptionOverrides, Segment, Suggestion, SuggestionOption, TaskKind } from '@magicx-eng/ai-autocomplete-vanilla';
|
|
3
5
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
4
6
|
|
|
5
|
-
type TaskKind = "automation" | "email" | "insight";
|
|
6
|
-
interface CompletedParam {
|
|
7
|
-
placeholder: string;
|
|
8
|
-
type: string;
|
|
9
|
-
text?: string;
|
|
10
|
-
kind: TaskKind | null;
|
|
11
|
-
}
|
|
12
|
-
interface SuggestionOption {
|
|
13
|
-
text: string;
|
|
14
|
-
icon?: string;
|
|
15
|
-
tag?: string;
|
|
16
|
-
is_tappable: boolean;
|
|
17
|
-
kind: TaskKind | null;
|
|
18
|
-
metadata?: Record<string, unknown>;
|
|
19
|
-
}
|
|
20
|
-
interface Suggestion {
|
|
21
|
-
type: string;
|
|
22
|
-
text: string;
|
|
23
|
-
required: boolean;
|
|
24
|
-
options?: SuggestionOption[];
|
|
25
|
-
}
|
|
26
|
-
interface CompletedParamState extends CompletedParam {
|
|
27
|
-
id: string;
|
|
28
|
-
text: string;
|
|
29
|
-
/** Source suggestion's `type` — used by re-edit mode to render the dropdown pill. */
|
|
30
|
-
suggestionType: string;
|
|
31
|
-
/** Source suggestion's `text` — used by re-edit mode to render the dropdown pill. */
|
|
32
|
-
suggestionPlaceholder: string;
|
|
33
|
-
/** Cached options from the suggestion that produced this param — re-edit shows these. */
|
|
34
|
-
options: SuggestionOption[];
|
|
35
|
-
metadata?: Record<string, unknown>;
|
|
36
|
-
}
|
|
37
|
-
type Segment = {
|
|
38
|
-
type: "text";
|
|
39
|
-
value: string;
|
|
40
|
-
} | {
|
|
41
|
-
type: "completed";
|
|
42
|
-
value: string;
|
|
43
|
-
param: CompletedParamState;
|
|
44
|
-
};
|
|
45
|
-
type AppearanceMode = "light" | "dark" | "auto";
|
|
46
7
|
interface AIAutocompleteHandle {
|
|
47
8
|
focus: () => void;
|
|
48
9
|
blur: () => void;
|
|
49
10
|
reset: () => void;
|
|
50
11
|
setMode: (mode: AppearanceMode) => void;
|
|
51
12
|
}
|
|
52
|
-
interface APIConfigBase {
|
|
53
|
-
endpoint?: string;
|
|
54
|
-
appIdentifier?: string;
|
|
55
|
-
headers?: Record<string, string>;
|
|
56
|
-
}
|
|
57
|
-
interface APIKeyConfig extends APIConfigBase {
|
|
58
|
-
type?: "apiKey";
|
|
59
|
-
apiKey?: string;
|
|
60
|
-
authScheme?: "Bearer" | "Basic";
|
|
61
|
-
}
|
|
62
|
-
interface AccessTokenConfig extends APIConfigBase {
|
|
63
|
-
type: "accessToken";
|
|
64
|
-
accessToken?: string;
|
|
65
|
-
getAccessToken: () => Promise<AccessTokenResult>;
|
|
66
|
-
}
|
|
67
|
-
interface AccessTokenResult {
|
|
68
|
-
accessToken: string;
|
|
69
|
-
/** UNIX ms. If provided, SDK refreshes proactively 30s before expiry. */
|
|
70
|
-
expiresAt?: number;
|
|
71
|
-
}
|
|
72
|
-
type APIConfig = APIKeyConfig | AccessTokenConfig;
|
|
73
|
-
type OptionOverrides = Record<string, (query: string) => SuggestionOption[]>;
|
|
74
13
|
interface AIAutocompleteProps {
|
|
75
14
|
onSubmit: (result: AutocompleteResult) => void;
|
|
76
15
|
onError?: (error: Error) => void;
|
|
@@ -110,11 +49,6 @@ interface AIAutocompleteProps {
|
|
|
110
49
|
*/
|
|
111
50
|
submitButton?: ReactNode;
|
|
112
51
|
}
|
|
113
|
-
interface AutocompleteResult {
|
|
114
|
-
query: string;
|
|
115
|
-
raw_query: string;
|
|
116
|
-
completed_params: CompletedParam[];
|
|
117
|
-
}
|
|
118
52
|
interface UseAIAutocompleteOptions {
|
|
119
53
|
onSubmit?: (result: AutocompleteResult) => void;
|
|
120
54
|
onError?: (error: Error) => void;
|
|
@@ -231,4 +165,4 @@ declare function AIAutocompleteDropdown({ suggestions, activeIndex, onSelect, on
|
|
|
231
165
|
|
|
232
166
|
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;
|
|
233
167
|
|
|
234
|
-
export { AIAutocomplete, AIAutocompleteDropdown, type AIAutocompleteDropdownProps, type AIAutocompleteHandle, type AIAutocompleteProps, type
|
|
168
|
+
export { AIAutocomplete, AIAutocompleteDropdown, type AIAutocompleteDropdownProps, type AIAutocompleteHandle, type AIAutocompleteProps, type UseAIAutocompleteOptions, type UseAIAutocompleteReturn, useAIAutocomplete };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,76 +1,15 @@
|
|
|
1
1
|
import * as react from 'react';
|
|
2
2
|
import { ReactNode, KeyboardEvent, ChangeEvent } from 'react';
|
|
3
|
+
import { AutocompleteResult, OptionOverrides, APIConfig, AppearanceMode, CompletedParamState, Suggestion, SuggestionOption, Segment } from '@magicx-eng/ai-autocomplete-vanilla';
|
|
4
|
+
export { APIConfig, APIKeyConfig, AccessTokenConfig, AccessTokenResult, AppearanceMode, AutocompleteResult, CompletedParam, CompletedParamState, OptionOverrides, Segment, Suggestion, SuggestionOption, TaskKind } from '@magicx-eng/ai-autocomplete-vanilla';
|
|
3
5
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
4
6
|
|
|
5
|
-
type TaskKind = "automation" | "email" | "insight";
|
|
6
|
-
interface CompletedParam {
|
|
7
|
-
placeholder: string;
|
|
8
|
-
type: string;
|
|
9
|
-
text?: string;
|
|
10
|
-
kind: TaskKind | null;
|
|
11
|
-
}
|
|
12
|
-
interface SuggestionOption {
|
|
13
|
-
text: string;
|
|
14
|
-
icon?: string;
|
|
15
|
-
tag?: string;
|
|
16
|
-
is_tappable: boolean;
|
|
17
|
-
kind: TaskKind | null;
|
|
18
|
-
metadata?: Record<string, unknown>;
|
|
19
|
-
}
|
|
20
|
-
interface Suggestion {
|
|
21
|
-
type: string;
|
|
22
|
-
text: string;
|
|
23
|
-
required: boolean;
|
|
24
|
-
options?: SuggestionOption[];
|
|
25
|
-
}
|
|
26
|
-
interface CompletedParamState extends CompletedParam {
|
|
27
|
-
id: string;
|
|
28
|
-
text: string;
|
|
29
|
-
/** Source suggestion's `type` — used by re-edit mode to render the dropdown pill. */
|
|
30
|
-
suggestionType: string;
|
|
31
|
-
/** Source suggestion's `text` — used by re-edit mode to render the dropdown pill. */
|
|
32
|
-
suggestionPlaceholder: string;
|
|
33
|
-
/** Cached options from the suggestion that produced this param — re-edit shows these. */
|
|
34
|
-
options: SuggestionOption[];
|
|
35
|
-
metadata?: Record<string, unknown>;
|
|
36
|
-
}
|
|
37
|
-
type Segment = {
|
|
38
|
-
type: "text";
|
|
39
|
-
value: string;
|
|
40
|
-
} | {
|
|
41
|
-
type: "completed";
|
|
42
|
-
value: string;
|
|
43
|
-
param: CompletedParamState;
|
|
44
|
-
};
|
|
45
|
-
type AppearanceMode = "light" | "dark" | "auto";
|
|
46
7
|
interface AIAutocompleteHandle {
|
|
47
8
|
focus: () => void;
|
|
48
9
|
blur: () => void;
|
|
49
10
|
reset: () => void;
|
|
50
11
|
setMode: (mode: AppearanceMode) => void;
|
|
51
12
|
}
|
|
52
|
-
interface APIConfigBase {
|
|
53
|
-
endpoint?: string;
|
|
54
|
-
appIdentifier?: string;
|
|
55
|
-
headers?: Record<string, string>;
|
|
56
|
-
}
|
|
57
|
-
interface APIKeyConfig extends APIConfigBase {
|
|
58
|
-
type?: "apiKey";
|
|
59
|
-
apiKey?: string;
|
|
60
|
-
authScheme?: "Bearer" | "Basic";
|
|
61
|
-
}
|
|
62
|
-
interface AccessTokenConfig extends APIConfigBase {
|
|
63
|
-
type: "accessToken";
|
|
64
|
-
accessToken?: string;
|
|
65
|
-
getAccessToken: () => Promise<AccessTokenResult>;
|
|
66
|
-
}
|
|
67
|
-
interface AccessTokenResult {
|
|
68
|
-
accessToken: string;
|
|
69
|
-
/** UNIX ms. If provided, SDK refreshes proactively 30s before expiry. */
|
|
70
|
-
expiresAt?: number;
|
|
71
|
-
}
|
|
72
|
-
type APIConfig = APIKeyConfig | AccessTokenConfig;
|
|
73
|
-
type OptionOverrides = Record<string, (query: string) => SuggestionOption[]>;
|
|
74
13
|
interface AIAutocompleteProps {
|
|
75
14
|
onSubmit: (result: AutocompleteResult) => void;
|
|
76
15
|
onError?: (error: Error) => void;
|
|
@@ -110,11 +49,6 @@ interface AIAutocompleteProps {
|
|
|
110
49
|
*/
|
|
111
50
|
submitButton?: ReactNode;
|
|
112
51
|
}
|
|
113
|
-
interface AutocompleteResult {
|
|
114
|
-
query: string;
|
|
115
|
-
raw_query: string;
|
|
116
|
-
completed_params: CompletedParam[];
|
|
117
|
-
}
|
|
118
52
|
interface UseAIAutocompleteOptions {
|
|
119
53
|
onSubmit?: (result: AutocompleteResult) => void;
|
|
120
54
|
onError?: (error: Error) => void;
|
|
@@ -231,4 +165,4 @@ declare function AIAutocompleteDropdown({ suggestions, activeIndex, onSelect, on
|
|
|
231
165
|
|
|
232
166
|
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;
|
|
233
167
|
|
|
234
|
-
export { AIAutocomplete, AIAutocompleteDropdown, type AIAutocompleteDropdownProps, type AIAutocompleteHandle, type AIAutocompleteProps, type
|
|
168
|
+
export { AIAutocomplete, AIAutocompleteDropdown, type AIAutocompleteDropdownProps, type AIAutocompleteHandle, type AIAutocompleteProps, type UseAIAutocompleteOptions, type UseAIAutocompleteReturn, useAIAutocomplete };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var Se=Object.defineProperty;var $e=Object.getOwnPropertyDescriptor;var Ue=Object.getOwnPropertyNames;var je=Object.prototype.hasOwnProperty;var Xe=(e,l)=>{for(var p in l)Se(e,p,{get:l[p],enumerable:!0})},Qe=(e,l,p,v)=>{if(l&&typeof l=="object"||typeof l=="function")for(let s of Ue(l))!je.call(e,s)&&s!==p&&Se(e,s,{get:()=>l[s],enumerable:!(v=$e(l,s))||v.enumerable});return e};var Je=e=>Qe(Se({},"__esModule",{value:!0}),e);var at={};Xe(at,{AIAutocomplete:()=>Be,AIAutocompleteDropdown:()=>we,useAIAutocomplete:()=>_e});module.exports=Je(at);var A=require("react");if(typeof document<"u"&&!document.getElementById("ac-style-67791514")){let e=document.createElement("style");e.id="ac-style-67791514",e.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
|
|
@@ -166,7 +166,7 @@
|
|
|
166
166
|
background-position: -50% 0;
|
|
167
167
|
}
|
|
168
168
|
}
|
|
169
|
-
`,document.head.appendChild(
|
|
169
|
+
`,document.head.appendChild(e)}var J={container:"AIAutocomplete-module_container_KKjFU",inputWrapper:"AIAutocomplete-module_inputWrapper_FLq1b",editorArea:"AIAutocomplete-module_editorArea_7rBWq",input:"AIAutocomplete-module_input_IW-P-",pillListContainer:"AIAutocomplete-module_pillListContainer_h92IA",submitButton:"AIAutocomplete-module_submitButton_sl1Mi",submitSlot:"AIAutocomplete-module_submitSlot_GhuCM",textShimmer:"AIAutocomplete-module_textShimmer_eCLdq"};if(typeof document<"u"&&!document.getElementById("ac-style-3819c762")){let e=document.createElement("style");e.id="ac-style-3819c762",e.textContent=`.AIAutocompleteDropdown-module_dropdown_yz2KC {
|
|
170
170
|
position: absolute;
|
|
171
171
|
left: 0;
|
|
172
172
|
right: 0;
|
|
@@ -248,7 +248,7 @@
|
|
|
248
248
|
opacity: 0.25;
|
|
249
249
|
}
|
|
250
250
|
}
|
|
251
|
-
`,document.head.appendChild(
|
|
251
|
+
`,document.head.appendChild(e)}var ne={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-0fcb7940")){let e=document.createElement("style");e.id="ac-style-0fcb7940",e.textContent=`.PillList-module_list_qvLqO {
|
|
252
252
|
position: relative;
|
|
253
253
|
z-index: 1;
|
|
254
254
|
pointer-events: auto;
|
|
@@ -331,7 +331,7 @@
|
|
|
331
331
|
opacity: 0;
|
|
332
332
|
}
|
|
333
333
|
}
|
|
334
|
-
`,document.head.appendChild(
|
|
334
|
+
`,document.head.appendChild(e)}var H={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 ce=require("react/jsx-runtime"),Ye=[125,69];function Re(e){return e===0?.4:e===1?.3:.15}function me({pills:e,activePillIndex:l,onSelectPill:p,rounded:v,loading:s}){return s&&e.length===0?(0,ce.jsx)("span",{className:H.list,"data-aia-pill-list-loading":"",children:Ye.map((c,g)=>(0,ce.jsx)("span",{"data-aia-pill-skeleton":"",className:`${H.pill} ${v?H.rounded:""} ${H.skeleton}`,style:{width:c,opacity:Re(g)}},`skel-${c}`))}):(0,ce.jsx)("span",{className:H.list,"data-aia-pill-list-loading":s?"":void 0,children:e.map((c,g)=>(0,ce.jsx)("button",{type:"button","data-aia-pill":"","data-aia-loading":s?"":void 0,tabIndex:-1,contentEditable:!1,suppressContentEditableWarning:!0,className:`${H.pill} ${v?H.rounded:""} ${g===l&&!s?H.active:""} ${s?H.skeleton:""}`,style:{opacity:Re(g)},onMouseDown:f=>f.preventDefault(),onClick:s?void 0:()=>p(g),disabled:s,children:c.text},`${c.type}-${c.text}`))})}var Z=require("react");if(typeof document<"u"&&!document.getElementById("ac-style-ff33a0ab")){let e=document.createElement("style");e.id="ac-style-ff33a0ab",e.textContent=`.SuggestionGrid-module_scrollWrapper_MOqfw {
|
|
335
335
|
position: relative;
|
|
336
336
|
}
|
|
337
337
|
|
|
@@ -386,7 +386,7 @@
|
|
|
386
386
|
background: var(--aia-scrollbar-thumb, rgba(0, 0, 0, 0.3));
|
|
387
387
|
border-radius: 3px;
|
|
388
388
|
}
|
|
389
|
-
`,document.head.appendChild(
|
|
389
|
+
`,document.head.appendChild(e)}var Pe={scrollWrapper:"SuggestionGrid-module_scrollWrapper_MOqfw",grid:"SuggestionGrid-module_grid_jvaPb"};var se=require("react");if(typeof document<"u"&&!document.getElementById("ac-style-82820da7")){let e=document.createElement("style");e.id="ac-style-82820da7",e.textContent=`.SuggestionItem-module_item_d4vpD {
|
|
390
390
|
position: relative;
|
|
391
391
|
overflow: visible;
|
|
392
392
|
display: flex;
|
|
@@ -733,7 +733,7 @@
|
|
|
733
733
|
filter: brightness(0.55);
|
|
734
734
|
}
|
|
735
735
|
}
|
|
736
|
-
`,document.head.appendChild(
|
|
736
|
+
`,document.head.appendChild(e)}var M={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",text:"SuggestionItem-module_text_yqoh9"};var Y=require("react/jsx-runtime");function Te({option:e,isHighlighted:l,onSelect:p,onHighlight:v,id:s,loading:c}){let[g,f]=(0,se.useState)(!1),y=(0,se.useRef)(void 0);(0,se.useEffect)(()=>()=>clearTimeout(y.current),[]);let n=()=>{c||!e.is_tappable||g||(f(!0),p(e),clearTimeout(y.current),y.current=setTimeout(()=>f(!1),500))},b=[M.item,l&&!c?M.highlighted:"",e.is_tappable?M.tappable:M.nonTappable,g?M.pressed:""].filter(Boolean).join(" ");return(0,Y.jsxs)("div",{id:s,role:"option","data-aia-option":"","data-aia-loading":c?"":void 0,"aria-selected":l,className:b,tabIndex:c||!e.is_tappable?-1:0,onClick:n,onKeyDown:I=>{!c&&e.is_tappable&&(I.key==="Enter"||I.key===" ")&&(I.preventDefault(),n())},onMouseEnter:!c&&e.is_tappable?v:void 0,children:[(0,Y.jsx)("div",{className:M.streaks}),(0,Y.jsx)("div",{className:M.streaksVert}),(0,Y.jsxs)("span",{className:M.content,children:[(0,Y.jsx)("span",{className:M.text,children:e.icon?`${e.icon} ${e.text}`:e.text}),e.tag&&(0,Y.jsx)("span",{className:M.tag,children:e.tag})]})]})}var ve=require("react/jsx-runtime");function ze({options:e,activeIndex:l,onSelect:p,onHighlight:v,listboxId:s,loading:c}){let g=(0,Z.useRef)(null),[f,y]=(0,Z.useState)(!1);return(0,Z.useEffect)(()=>{let n=g.current;if(!n)return;let b=()=>{y(n.scrollHeight-n.scrollTop-n.clientHeight>1)};n.addEventListener("scroll",b,{passive:!0});let I=new ResizeObserver(b);return I.observe(n),()=>{n.removeEventListener("scroll",b),I.disconnect()}},[]),(0,Z.useLayoutEffect)(()=>{let n=g.current;n&&y(n.scrollHeight-n.scrollTop-n.clientHeight>1)},[e]),(0,ve.jsx)("div",{className:Pe.scrollWrapper,"data-fade":f?"":void 0,children:(0,ve.jsx)("div",{ref:g,className:Pe.grid,children:e.map((n,b)=>(0,ve.jsx)(Te,{option:n,isHighlighted:b===l,onSelect:p,onHighlight:()=>v(b),id:`${s}-option-${b}`,loading:c},n.text))})})}var K=require("react/jsx-runtime"),Ze=[159,119,164];function we({suggestions:e,activeIndex:l,onSelect:p,onHighlight:v,isOpen:s,id:c,className:g,pills:f,onPillClick:y,showPills:n=!0,isLoading:b=!1}){let C=e[0]?.options??[],F=n&&f&&f.length>0&&y,T=C.length>0,$=b&&!T,W=s&&(T||F||b);return(0,K.jsxs)("div",{id:c,role:"listbox","data-aia-dropdown":"","data-aia-loading":b?"":void 0,className:`${ne.dropdown} ${W?ne.visible:""} ${g??""}`,onMouseDown:a=>a.preventDefault(),children:[n&&f&&f.length>0&&y&&(0,K.jsx)("div",{className:ne.pillBar,"data-aia-pillbar":"",children:(0,K.jsx)(me,{pills:f,activePillIndex:0,onSelectPill:y,rounded:!0,loading:b})}),n&&(!f||f.length===0)&&b&&(0,K.jsx)("div",{className:ne.pillBar,"data-aia-pillbar":"",children:(0,K.jsx)(me,{pills:[],activePillIndex:0,onSelectPill:()=>{},rounded:!0,loading:!0})}),T&&(0,K.jsx)(ze,{options:C,activeIndex:l,onSelect:p,onHighlight:v,listboxId:c,loading:b}),$&&(0,K.jsx)("div",{className:ne.skeletonBars,"data-aia-skeleton-bars":"",children:Ze.map(a=>(0,K.jsx)("span",{className:ne.skeletonBar,style:{width:a}},`bar-${a}`))})]})}if(typeof document<"u"&&!document.getElementById("ac-style-0ae03977")){let e=document.createElement("style");e.id="ac-style-0ae03977",e.textContent=`/*
|
|
737
737
|
* Built-in appearance defaults \u2014 zero specificity via :where().
|
|
738
738
|
* Consumer CSS always wins without !important.
|
|
739
739
|
*
|
|
@@ -828,5 +828,5 @@
|
|
|
828
828
|
animation-duration: 0s !important;
|
|
829
829
|
transition-duration: 0s !important;
|
|
830
830
|
}
|
|
831
|
-
`,document.head.appendChild(n)}var ht='[contenteditable="false"]',ue;function cn(){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 U(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=U(n);return e==null?!1:e>=De(n)}function vt(n,e){if(e<=0)return 0;let t=cn();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 pn="https://api.ai-autocomplete.com",Me=`${pn}/api/suggest`,Pt=new WeakMap;function Se(n){return n?.type==="accessToken"}function un(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=un(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}function mn(n){return(n??Me).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function gn(n){return Se(n)?`Bearer ${await Re(n).getToken()}`:He(n)}async function It(n){try{let e=mn(n.apiConfig?.endpoint),t=Ne(n.apiConfig),o=await gn(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 fn="0.1.43",At=!1;function hn(){return crypto.randomUUID()}function bn(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.text},kind:n.kind}}function xn(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=>bn(r,t)),...a!=null&&{contact_account_count:a}},meta:{request_id:hn(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:fn,session_id:o}}}async function Ct(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=xn(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 Ct(s,r,m,l,t.signal);if(v.status===401){let g=await p.getToken(!0);v=await Ct(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&&!At&&(At=!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 vn=100,yn=300,wn=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(wn)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},vn),this.slowDebounceTimer=setTimeout(()=>t(1),yn)}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 Sn(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?U(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);if(!((e.shiftKey||e.metaKey)&&(e.key==="ArrowDown"||e.key==="ArrowUp"||e.key==="ArrowLeft"||e.key==="ArrowRight")))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=Sn(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"?Pn(n):In(n)}function Pn(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 In(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 An=[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 An){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=>En(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 En(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");r.className="magicx-aia-option-content";let s=document.createElement("span");if(s.className="magicx-aia-option-text",s.textContent=n.icon?`${n.icon} ${n.text}`:n.text,r.appendChild(s),n.tag){let l=document.createElement("span");l.className="magicx-aia-option-tag",l.textContent=n.tag,r.appendChild(l)}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?U(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 Tn='<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 _n(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function Nt(n,e){let t=e.firstElementChild;if(!t){e.removeAttribute("data-aia-pill-wrapped");return}if(n.dataset.aiaEmpty==="true"){e.setAttribute("data-aia-pill-wrapped","");return}let o=t.getBoundingClientRect(),i=n.getBoundingClientRect();o.top>=i.bottom-2?e.setAttribute("data-aia-pill-wrapped",""):e.removeAttribute("data-aia-pill-wrapped")}function Ht(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",_n()?"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=Tn,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(U(r)))},{signal:p});let f=r.ownerDocument??document;if(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(U(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(),typeof ResizeObserver<"u"){let c=new ResizeObserver(()=>Nt(r,s));c.observe(r),u.signal.addEventListener("abort",()=>c.disconnect(),{once:!0})}return{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);Nt(o,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 Ft(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 Bt(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 Kt(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 zt(){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=kn,document.head.appendChild(n)}var kn="";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 On="newParam",Wt="suggestionRemoval",Dn="selectionAnimation",Ln=650,Mn=0;function Rn(){return`:ac-${++Mn}:`}var $t=500;function Ut(){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=Bt(Ut());this._listboxId=Rn();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=Kt(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"&&(zt(),this.setupContainer()),this.renderMode==="full"?this.buildAndRenderFull():this.renderMode==="dropdown"&&this.buildAndRenderDropdown(),this.fetchController.start()}focus(){this.domRefs?.input.focus()}blur(){this.domRefs?.input.blur()}reset(){this.store.set({...Ut(),skipNextFetch:!0}),this.sessionId=crypto.randomUUID(),this.fetchController.doFetch("",[])}destroy(){this.fetchController.dispose(),this.modeController?.destroy(),this.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=Ft(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(Wt),o.remainingActionable>0)){let i=o.consumedSuggestion;this.timers.schedule(Wt,()=>{this.store.set(a=>({suggestions:a.suggestions.filter(r=>r!==i)}))},$t)}}startSelectionAnimationTimer(){this.timers.schedule(Dn,()=>this.store.set({inSelectionAnimation:!1}),$t)}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=Ht(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(On,()=>this.store.set({newParamId:null}),Ln)}))}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 Nn={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 oe=(0,k.useRef)(g);oe.current=g;let J=(0,k.useRef)(d);J.current=d;let z=(0,k.useRef)(u);z.current=u;let ie=(0,k.useRef)(f);ie.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)=>oe.current?.(...N),onFocus:()=>J.current?.(),onBlur:()=>z.current?.(),setCursor:N=>ie.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 q=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})},[q,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)},[]),re=(0,k.useCallback)(y=>{c.current?.handleKeyDown(y.nativeEvent)},[]),j=c.current,I=h??Nn,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:re,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 A=require("react");var Ye;function Hn(){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 qt(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,A.useRef)(null),S=(0,A.useRef)(!1),R=(0,A.useRef)(""),K=(0,A.useRef)(""),oe=(0,A.useRef)(null),J=(0,A.useRef)(0);oe.current=a,(0,A.useEffect)(()=>{if(!p)return;let w=x.current;w&&(document.activeElement===w?h(!0):w.focus())},[p,h]),(0,A.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(U(w))};return P.addEventListener("selectionchange",E),()=>P.removeEventListener("selectionchange",E)},[o,f,b]),(0,A.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,A.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 _=oe.current??De(E);M(E,_)},[t]),(0,A.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,A.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]),ie=(0,A.useCallback)(()=>{J.current=performance.now(),z();let w=x.current;w&&g(U(w))},[z,g]);(0,A.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 q=(0,A.useCallback)(()=>{S.current=!0},[]),Y=(0,A.useCallback)(()=>{S.current=!1,z()},[z]),de=(0,A.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,A.useCallback)(w=>v(w),[v]),T=(0,A.useCallback)(()=>h(!0),[h]),be=(0,A.useCallback)(()=>h(!1),[h]),re=(0,A.useCallback)(()=>x.current?.focus(),[]),j=(0,A.useCallback)(()=>x.current?.blur(),[]),I=(0,A.useCallback)(()=>{let w=x.current;return w?me(w):""},[]),xe=Hn()?"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:ie,onKeyDown:V,onCompositionStart:q,onCompositionEnd:Y,onPaste:de,onFocus:T,onBlur:be},getPlainText:I,focus:re,blur:j}}var B=require("react/jsx-runtime");function Fn(n){return n!=="auto"?n:typeof window>"u"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}var Gt=(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},oe){let J=(0,D.useRef)(null),z=(0,D.useRef)(null),ie=(0,D.useRef)(()=>{}),q=(0,D.useRef)(null),Y=(0,D.useRef)(null);(0,D.useEffect)(()=>{let C=J.current;if(C)return q.current?q.current.setMode(d):q.current=new he(C,d),()=>{q.current?.destroy(),q.current=null}},[d]);let de=(0,D.useCallback)(C=>{let W=Y.current?.current;W&&(W.focus(),M(W,C))},[]),{completedParams:V,suggestionPills:T,setActivePill:be,segments:re,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:Qt,reset:Ie}=Je({onSubmit:C=>ie.current(C),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 C=window.setTimeout(()=>I(),650);return()=>window.clearTimeout(C)},[j,I]);let Vt=_>=0?`${O}-option-${_}`:void 0,{inputRef:et,editorProps:jt,focus:Ae,blur:lt,getPlainText:dt}=qt({segments:re,newParamId:j,editingParam:Ze,editingAnchor:Pe,caretOffset:y,placeholderText:xe,isFocused:w,isDropdownOpen:P,listboxId:O,activeDescendantId:Vt,autoFocus:b,handleTextChange:L,handleKeyDown:X,handleCaretAfterInput:N,handleCaretMove:ce,startEditingParam:H,replaceEditingRange:ve,setFocused:Z});Y.current=et,(0,D.useLayoutEffect)(()=>{let C=z.current,W=et.current;if(!C||!W)return;let Ee=()=>{let pt=C.firstElementChild;if(!pt)return;if(W.dataset.aiaEmpty==="true"){C.setAttribute("data-aia-pill-wrapped","");return}let Zt=pt.getBoundingClientRect(),en=W.getBoundingClientRect();Zt.top>=en.bottom-2?C.setAttribute("data-aia-pill-wrapped",""):C.removeAttribute("data-aia-pill-wrapped")};Ee();let ct=new ResizeObserver(Ee);return ct.observe(W),()=>ct.disconnect()},[re,T.length,E,et]),(0,D.useImperativeHandle)(oe,()=>({focus:Ae,blur:lt,reset:Ie,setMode:C=>q.current?.setMode(C)}),[Ae,lt,Ie]);let Ce=!!re.length||V.length>0,tt=(0,D.useCallback)(()=>{if(!Ce)return;let C=dt(),{rawQuery:W,completedParams:Ee}=F(C,V);e({query:C.trim(),raw_query:W,completed_params:Ee}),Ie()},[Ce,V,e,Ie,dt]);ie.current=tt;let Xt=(0,D.useCallback)(C=>{C.target?.closest("[data-aia-pill]")||Ae()},[Ae]),Jt=l==="inline",Yt=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":Fn(d),children:[(0,B.jsx)(_e,{...Qt,showPills:Yt}),(0,B.jsxs)("div",{className:ee.inputWrapper,onClick:Xt,children:[(0,B.jsxs)("div",{className:ee.editorArea,"data-aia-editor":"",children:[(0,B.jsx)("div",{...jt,className:ee.input,"data-aia-input":""}),Jt&&(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:!Ce,onClick:C=>{C.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:C=>{Ce&&(C.stopPropagation(),tt())},children:K})]})]})});0&&(module.exports={AIAutocomplete,AIAutocompleteDropdown,useAIAutocomplete});
|
|
831
|
+
`,document.head.appendChild(e)}var le=require("@magicx-eng/ai-autocomplete-vanilla");var Me=require("@magicx-eng/ai-autocomplete-vanilla"),w=require("react"),et={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 _e({onSubmit:e,onError:l,optionOverrides:p,maskCompletedText:v,apiConfig:s,columns:c=2,dropdownTrigger:g,closeDropdownOnBlur:f,showNonTappableOptions:y,onFocus:n,onBlur:b,value:I,completedParams:C,onChange:F,onParamsChange:T,source:$,setCursor:W}){let a=(0,w.useRef)(null),[O,k]=(0,w.useState)(null),U=(0,w.useRef)(e);U.current=e;let ee=(0,w.useRef)(l);ee.current=l;let N=(0,w.useRef)(F);N.current=F;let te=(0,w.useRef)(T);te.current=T;let j=(0,w.useRef)(n);j.current=n;let R=(0,w.useRef)(b);R.current=b;let oe=(0,w.useRef)(W);oe.current=W,(0,w.useEffect)(()=>{if(typeof document>"u")return;let t=new Me.AIAutocomplete(document.createElement("div"),{renderMode:"headless",apiConfig:s,optionOverrides:p,maskCompletedText:v,columns:c,dropdownTrigger:g,closeDropdownOnBlur:f,showNonTappableOptions:y,source:$,value:I,completedParams:C,onSubmit:(...P)=>U.current?.(...P),onError:(...P)=>ee.current?.(...P),onChange:(...P)=>N.current?.(...P),onParamsChange:(...P)=>te.current?.(...P),onFocus:()=>j.current?.(),onBlur:()=>R.current?.(),setCursor:P=>oe.current?.(P)});a.current=t,k(t.getState());let E=t.subscribe(P=>k(P));return()=>{E(),t.destroy(),a.current===t&&(a.current=null)}},[]),(0,w.useEffect)(()=>{I!==void 0&&a.current?.setValue(I)},[I]),(0,w.useEffect)(()=>{C!==void 0&&a.current?.setCompletedParams(C)},[C]);let B=JSON.stringify(s??null),X=(0,w.useRef)(p),re=(0,w.useRef)(0);if(p!==X.current){let t=X.current,E=p,P=Object.keys(t??{}),ie=Object.keys(E??{});(P.length!==ie.length||ie.some(ue=>!t?.[ue]||E[ue]!==t[ue]))&&re.current++,X.current=p}(0,w.useEffect)(()=>{a.current?.update({apiConfig:s,optionOverrides:p,dropdownTrigger:g,closeDropdownOnBlur:f,showNonTappableOptions:y})},[B,re.current,g,f,y]);let G=(0,w.useRef)(null);G.current===null&&(G.current={handleTextChange:t=>a.current?.handleTextChange(t),handleKeyDown:t=>{let E="nativeEvent"in t?t.nativeEvent:t;a.current?.handleKeyDown(E)},setFocused:t=>a.current?.setFocused(t),startEditingParam:t=>a.current?.startEditingParam(t),exitEditMode:()=>a.current?.exitEditMode(),handleCaretAfterInput:t=>a.current?.handleCaretAfterInput(t),handleCaretMove:t=>a.current?.handleCaretMove(t),replaceEditingRange:t=>a.current?.replaceEditingRange(t)??!1,setActivePill:t=>a.current?.setActivePill(t),removeLastParam:()=>a.current?.removeLastParam(),clearNewParamId:()=>a.current?.clearNewParamId(),reset:()=>a.current?.reset(),selectOption:t=>a.current?.selectOption(t),setActiveDropdownIndex:t=>a.current?.setActiveDropdownIndex(t),handleFocus:()=>a.current?.setFocused(!0),handleBlur:()=>a.current?.setFocused(!1)});let h=G.current,de=(0,w.useCallback)(t=>{let E=t.target.value,ie=E.length>0&&!t.nativeEvent?.isComposing&&E[0]!==E[0].toUpperCase()?E[0].toUpperCase()+E.slice(1):E;a.current?.handleTextChange(ie)},[]),ae=(0,w.useCallback)(t=>{a.current?.handleKeyDown(t.nativeEvent)},[]),V=a.current,i=O??et,pe=I!==void 0?I:i.text,o=C!==void 0?C:i.completedParams,r=i.actionableSuggestions,m=r[0],x=V?.listboxId??"",_=i.activeDropdownIndex>=0&&V?`${x}-option-${i.activeDropdownIndex}`:void 0,S=i.editingParam,q=S?{type:S.suggestionType,text:S.suggestionPlaceholder,required:!0,options:S.options}:null,Q=q??m,Ie=q?[q]:r,ge=!V||i.isLoading&&!i.editingParam&&!i.inSelectionAnimation;return{completedParams:o,suggestionPills:r,setActivePill:h.setActivePill,removeLastParam:h.removeLastParam,segments:i.segments,newParamId:i.newParamId,clearNewParamId:h.clearNewParamId,suggestions:i.suggestions,activeIndex:i.activeDropdownIndex,isReady:i.isReady,isLoading:ge,isFocused:i.isFocused,isDropdownOpen:i.isDropdownOpen,placeholderText:i.placeholderText,listboxId:x,error:i.error,handleTextChange:h.handleTextChange,handleKeyDown:h.handleKeyDown,setFocused:h.setFocused,editingParam:S,editingAnchor:i.editingAnchor,caretOffset:i.caretOffset,startEditingParam:h.startEditingParam,exitEditMode:h.exitEditMode,handleCaretAfterInput:h.handleCaretAfterInput,handleCaretMove:h.handleCaretMove,replaceEditingRange:h.replaceEditingRange,inputProps:{value:pe,placeholder:i.placeholderText||void 0,onChange:de,onKeyDown:ae,onFocus:h.handleFocus,onBlur:h.handleBlur,role:"combobox","aria-expanded":i.isDropdownOpen,"aria-activedescendant":_,"aria-autocomplete":"list","aria-controls":x},reset:h.reset,dropdownProps:{suggestions:Q?[{...Q,options:i.filteredOptions}]:[],activeIndex:i.activeDropdownIndex,onSelect:h.selectOption,onHighlight:h.setActiveDropdownIndex,isOpen:i.isDropdownOpen,id:x,pills:Ie,onPillClick:h.setActivePill,isLoading:ge}}}var D=require("@magicx-eng/ai-autocomplete-vanilla"),d=require("react"),ye;function tt(){if(ye!==void 0)return ye;if(typeof document>"u")return!1;let e=document.createElement("div");return e.setAttribute("contenteditable","plaintext-only"),ye=e.contentEditable==="plaintext-only",ye}function Oe(e){let{segments:l,newParamId:p,editingParam:v,editingAnchor:s,caretOffset:c,placeholderText:g,isFocused:f,isDropdownOpen:y,listboxId:n,activeDescendantId:b,autoFocus:I,handleTextChange:C,handleKeyDown:F,handleCaretAfterInput:T,handleCaretMove:$,startEditingParam:W,replaceEditingRange:a,setFocused:O}=e,k=(0,d.useRef)(null),U=(0,d.useRef)(!1),ee=(0,d.useRef)(""),N=(0,d.useRef)(""),te=(0,d.useRef)(null),j=(0,d.useRef)(0);te.current=c,(0,d.useEffect)(()=>{if(!I)return;let o=k.current;o&&(document.activeElement===o?O(!0):o.focus())},[I,O]),(0,d.useEffect)(()=>{let o=k.current;if(!o)return;let r=o.ownerDocument??document,m=()=>{let x=r.getSelection();if(!x||x.rangeCount===0||!x.anchorNode||!o.contains(x.anchorNode))return;let _=x.anchorNode,Q=(_.nodeType===Node.ELEMENT_NODE?_:_.parentElement)?.closest('strong[data-seg="completed"][data-param-id]')?.dataset.paramId??null;if(Q&&Q!==v?.id){W(Q);return}performance.now()-j.current<50||$((0,D.getCursorOffset)(o))};return r.addEventListener("selectionchange",m),()=>r.removeEventListener("selectionchange",m)},[v,W,$]),(0,d.useLayoutEffect)(()=>{let o=k.current;o&&(0,D.renderEditableContent)({input:o,segments:l,newParamId:p,editingParamId:v?.id??null,placeholderText:g??"",isFocused:f})},[l,p,v,g,f]),(0,d.useLayoutEffect)(()=>{let o=ee.current,r=p??"";if(ee.current=r,!r||r===o)return;let m=k.current;if(!m)return;m.focus();let x=te.current??(0,D.plainTextLength)(m);(0,D.setCursorOffset)(m,x)},[p]),(0,d.useLayoutEffect)(()=>{let o=N.current,r=v?.id??"";if(N.current=r,!r||r===o||s==null)return;let m=k.current;m&&(0,D.setCursorOffset)(m,s)},[v,s]);let R=(0,d.useCallback)(()=>{if(U.current)return;let o=k.current;if(!o)return;let r=(0,D.extractPlainText)(o),x=r.length>0&&r[0]!==r[0].toUpperCase()?r[0].toUpperCase()+r.slice(1):r;C(x)},[C]),oe=(0,d.useCallback)(()=>{j.current=performance.now(),R();let o=k.current;o&&T((0,D.getCursorOffset)(o))},[R,T]);(0,d.useEffect)(()=>{let o=k.current;if(!o)return;let r=m=>{let x=m,_=x.inputType;if(_==="insertParagraph"||_==="insertLineBreak"||_==="insertFromDrop"){m.preventDefault();return}if(_.startsWith("insert")||_.startsWith("delete")){let S=_.startsWith("delete")?"":x.data??"";a(S)&&m.preventDefault()}};return o.addEventListener("beforeinput",r),()=>o.removeEventListener("beforeinput",r)},[a]);let B=(0,d.useCallback)(()=>{U.current=!0},[]),X=(0,d.useCallback)(()=>{U.current=!1,R()},[R]),re=(0,d.useCallback)(o=>{o.preventDefault();let r=k.current;if(!r)return;let m=(o.clipboardData.getData("text/plain")??"").replace(/\r?\n/g," ");if(!m)return;let x=r.ownerDocument??document,_=x.getSelection();if(!_||_.rangeCount===0)return;let S=_.getRangeAt(0);if(!r.contains(S.startContainer))return;S.deleteContents();let q=x.createTextNode(m);S.insertNode(q),S.setStartAfter(q),S.collapse(!0),_.removeAllRanges(),_.addRange(S),R()},[R]),G=(0,d.useCallback)(o=>F(o),[F]),h=(0,d.useCallback)(()=>O(!0),[O]),de=(0,d.useCallback)(()=>O(!1),[O]),ae=(0,d.useCallback)(()=>k.current?.focus(),[]),V=(0,d.useCallback)(()=>k.current?.blur(),[]),i=(0,d.useCallback)(()=>{let o=k.current;return o?(0,D.extractPlainText)(o):""},[]),pe=tt()?"plaintext-only":"true";return{inputRef:k,editorProps:{ref:k,contentEditable:pe,suppressContentEditableWarning:!0,tabIndex:0,role:"combobox","aria-autocomplete":"list","aria-haspopup":"listbox","aria-controls":n,"aria-expanded":y,"aria-activedescendant":b,spellCheck:!0,enterKeyHint:"send",onInput:oe,onKeyDown:G,onCompositionStart:B,onCompositionEnd:X,onPaste:re,onFocus:h,onBlur:de},getPlainText:i,focus:ae,blur:V}}var L=require("react/jsx-runtime");function ot(e){return e!=="auto"?e:typeof window>"u"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}var Be=(0,A.forwardRef)(function({onSubmit:l,onError:p,optionOverrides:v,maskCompletedText:s,className:c,apiConfig:g,columns:f,pillPlacement:y="inline",mode:n="auto",optionsPosition:b="below",animations:I=!0,dropdownTrigger:C,closeDropdownOnBlur:F,showNonTappableOptions:T,autoFocus:$=!0,onFocus:W,onBlur:a,value:O,completedParams:k,onChange:U,onParamsChange:ee,submitButton:N},te){let j=(0,A.useRef)(null),R=(0,A.useRef)(null),oe=(0,A.useRef)(()=>{}),B=(0,A.useRef)(null),X=(0,A.useRef)(null);(0,A.useEffect)(()=>{let u=j.current;if(u)return B.current?B.current.setMode(n):B.current=new le.ModeController(u,n),()=>{B.current?.destroy(),B.current=null}},[n]);let re=(0,A.useCallback)(u=>{let z=X.current?.current;z&&(z.focus(),(0,le.setCursorOffset)(z,u))},[]),{completedParams:G,suggestionPills:h,setActivePill:de,segments:ae,newParamId:V,clearNewParamId:i,placeholderText:pe,isFocused:o,isDropdownOpen:r,isLoading:m,activeIndex:x,listboxId:_,handleTextChange:S,handleKeyDown:q,setFocused:Q,editingParam:Ie,editingAnchor:ge,caretOffset:t,startEditingParam:E,handleCaretAfterInput:P,handleCaretMove:ie,replaceEditingRange:ue,dropdownProps:He,reset:fe}=_e({onSubmit:u=>oe.current(u),onError:p,optionOverrides:v,maskCompletedText:s,apiConfig:g,columns:f,dropdownTrigger:C,closeDropdownOnBlur:F,showNonTappableOptions:T,onFocus:W,onBlur:a,value:O,completedParams:k,onChange:U,onParamsChange:ee,source:"full-sdk",setCursor:re});(0,A.useEffect)(()=>{if(!V)return;let u=window.setTimeout(()=>i(),650);return()=>window.clearTimeout(u)},[V,i]);let Ke=x>=0?`${_}-option-${x}`:void 0,{inputRef:ke,editorProps:Fe,focus:be,blur:Ee,getPlainText:Ce}=Oe({segments:ae,newParamId:V,editingParam:Ie,editingAnchor:ge,caretOffset:t,placeholderText:pe,isFocused:o,isDropdownOpen:r,listboxId:_,activeDescendantId:Ke,autoFocus:$,handleTextChange:S,handleKeyDown:q,handleCaretAfterInput:P,handleCaretMove:ie,startEditingParam:E,replaceEditingRange:ue,setFocused:Q});X.current=ke,(0,A.useLayoutEffect)(()=>{let u=R.current,z=ke.current;if(!u||!z)return;let xe=()=>{let Le=u.firstElementChild;if(!Le)return;if(z.dataset.aiaEmpty==="true"){u.setAttribute("data-aia-pill-wrapped","");return}let Ve=Le.getBoundingClientRect(),qe=z.getBoundingClientRect();Ve.top>=qe.bottom-2?u.setAttribute("data-aia-pill-wrapped",""):u.removeAttribute("data-aia-pill-wrapped")};xe();let De=new ResizeObserver(xe);return De.observe(z),()=>De.disconnect()},[ae,h.length,m,ke]),(0,A.useImperativeHandle)(te,()=>({focus:be,blur:Ee,reset:fe,setMode:u=>B.current?.setMode(u)}),[be,Ee,fe]);let he=!!ae.length||G.length>0,Ae=(0,A.useCallback)(()=>{if(!he)return;let u=Ce(),{rawQuery:z,completedParams:xe}=(0,le.buildQuery)(u,G);l({query:u.trim(),raw_query:z,completed_params:xe}),fe()},[he,G,l,fe,Ce]);oe.current=Ae;let We=(0,A.useCallback)(u=>{u.target?.closest("[data-aia-pill]")||be()},[be]),Ne=y==="inline",Ge=y==="dropdown";return(0,L.jsxs)("div",{ref:j,className:`magicx-aia ${J.container} ${c??""}`,"data-pill-placement":y,"data-options-position":b,"data-animations":I?"on":"off","data-mode":ot(n),children:[(0,L.jsx)(we,{...He,showPills:Ge}),(0,L.jsxs)("div",{className:J.inputWrapper,onClick:We,children:[(0,L.jsxs)("div",{className:J.editorArea,"data-aia-editor":"",children:[(0,L.jsx)("div",{...Fe,className:J.input,"data-aia-input":""}),Ne&&(m||h.length>0)&&(0,L.jsx)("span",{ref:R,className:J.pillListContainer,"data-aia-pill-list-container":"",children:(0,L.jsx)(me,{pills:h,activePillIndex:0,onSelectPill:de,loading:m})})]}),N===null?null:N===void 0?(0,L.jsx)("button",{type:"button","data-aia-submit":"",className:J.submitButton,disabled:!he,onClick:u=>{u.stopPropagation(),Ae()},"aria-label":"Submit",children:(0,L.jsx)("svg",{width:"18",height:"18",viewBox:"0 0 18 18",fill:"none",role:"img","aria-label":"Submit",children:(0,L.jsx)("path",{d:"M9 14V4M9 4L4 9M9 4L14 9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}):(0,L.jsx)("span",{"data-aia-submit":"",className:J.submitSlot,onClick:u=>{he&&(u.stopPropagation(),Ae())},children:N})]})]})});0&&(module.exports={AIAutocomplete,AIAutocompleteDropdown,useAIAutocomplete});
|
|
832
832
|
//# sourceMappingURL=index.js.map
|