@magicx-eng/ai-autocomplete-react 0.1.26 → 0.1.27
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 +21 -3
- package/dist/index.d.mts +16 -1
- package/dist/index.d.ts +16 -1
- 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 +18 -22
package/README.md
CHANGED
|
@@ -13,7 +13,7 @@ A React/TypeScript SDK that provides a guided AI-powered autocomplete experience
|
|
|
13
13
|
- **Client-side filtering** — instant substring filtering on every keystroke
|
|
14
14
|
- **Option overrides** — inject or dynamically generate client-side options per suggestion type
|
|
15
15
|
- **Controlled & uncontrolled** — works out of the box or integrates with external state
|
|
16
|
-
- **Ref forwarding** — imperative `focus()`, `reset()`, and `setMode()` via ref
|
|
16
|
+
- **Ref forwarding** — imperative `focus()`, `blur()`, `reset()`, and `setMode()` via ref
|
|
17
17
|
- **Accessible** — ARIA combobox pattern with `role="listbox"`, `aria-activedescendant`
|
|
18
18
|
- **Animations** — option selection streak animation, text shimmer on newly added params
|
|
19
19
|
- **Lightweight** — styles auto-injected at runtime
|
|
@@ -87,12 +87,26 @@ import { AIAutocomplete, type AIAutocompleteHandle } from "@magicx-eng/ai-autoco
|
|
|
87
87
|
|
|
88
88
|
const ref = useRef<AIAutocompleteHandle>(null);
|
|
89
89
|
// ref.current?.focus()
|
|
90
|
+
// ref.current?.blur()
|
|
90
91
|
// ref.current?.reset()
|
|
91
92
|
// ref.current?.setMode("dark")
|
|
92
93
|
|
|
93
94
|
<AIAutocomplete ref={ref} onSubmit={handleSubmit} />
|
|
94
95
|
```
|
|
95
96
|
|
|
97
|
+
### Focus Control
|
|
98
|
+
|
|
99
|
+
The component auto-focuses the input on mount. To opt out, pass `autoFocus={false}`. Listen to focus changes with `onFocus` / `onBlur`:
|
|
100
|
+
|
|
101
|
+
```tsx
|
|
102
|
+
<AIAutocomplete
|
|
103
|
+
autoFocus={false}
|
|
104
|
+
onFocus={() => setIsActive(true)}
|
|
105
|
+
onBlur={() => setIsActive(false)}
|
|
106
|
+
onSubmit={handleSubmit}
|
|
107
|
+
/>
|
|
108
|
+
```
|
|
109
|
+
|
|
96
110
|
---
|
|
97
111
|
|
|
98
112
|
## Tier 2: Headless
|
|
@@ -146,11 +160,15 @@ function App() {
|
|
|
146
160
|
| `optionsPosition?` | `"above" \| "below"` | `"below"` | Where the dropdown opens relative to the input. |
|
|
147
161
|
| `animations?` | `boolean` | `true` | Enable/disable all SDK animations (streak + shimmer). |
|
|
148
162
|
| `dropdownTrigger?` | `"auto" \| "manual" \| "hidden"` | `"auto"` | When the dropdown appears. `"auto"` = when options available. `"manual"` = only on pill tap, closes after selection. `"hidden"` = never shows. |
|
|
163
|
+
| `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. |
|
|
164
|
+
| `autoFocus?` | `boolean` | `true` | Focus the input on mount. Set to `false` to leave focus to the consumer. |
|
|
165
|
+
| `onFocus?` | `() => void` | — | Called when the input gains focus. |
|
|
166
|
+
| `onBlur?` | `() => void` | — | Called when the input loses focus. |
|
|
149
167
|
| `value?` | `string` | — | Controlled text value. |
|
|
150
168
|
| `completedParams?` | `CompletedParamState[]` | — | Controlled completed params. |
|
|
151
169
|
| `onChange?` | `(value: string) => void` | — | Called when text changes (controlled mode). |
|
|
152
170
|
| `onParamsChange?` | `(params: CompletedParamState[]) => void` | — | Called when params change (controlled mode). |
|
|
153
|
-
| `ref?` | `Ref<AIAutocompleteHandle>` | — | Imperative handle with `focus()`, `reset()`, and `setMode()`. |
|
|
171
|
+
| `ref?` | `Ref<AIAutocompleteHandle>` | — | Imperative handle with `focus()`, `blur()`, `reset()`, and `setMode()`. |
|
|
154
172
|
|
|
155
173
|
### `APIConfig`
|
|
156
174
|
|
|
@@ -200,7 +218,7 @@ The SDK handles token refresh transparently: 401 → `getAccessToken` → retry
|
|
|
200
218
|
|
|
201
219
|
### `useAIAutocomplete(options)`
|
|
202
220
|
|
|
203
|
-
The headless hook for Tier 2. Accepts the same props as `<AIAutocomplete />` except for the rendering-only ones: `className`, `ref`, `pillPlacement`, `mode`, `optionsPosition`, and `
|
|
221
|
+
The headless hook for Tier 2. Accepts the same props as `<AIAutocomplete />` except for the rendering-only ones: `className`, `ref`, `pillPlacement`, `mode`, `optionsPosition`, `animations`, and `autoFocus` (those belong to the wrapping component — the hook doesn't own the input element). `onFocus` and `onBlur` are forwarded and fire whenever the consumer-owned textarea's focus changes (they're driven by `inputProps.onFocus` / `inputProps.onBlur`).
|
|
204
222
|
|
|
205
223
|
#### Return Value
|
|
206
224
|
|
package/dist/index.d.mts
CHANGED
|
@@ -42,6 +42,7 @@ type Segment = {
|
|
|
42
42
|
type AppearanceMode = "light" | "dark" | "auto";
|
|
43
43
|
interface AIAutocompleteHandle {
|
|
44
44
|
focus: () => void;
|
|
45
|
+
blur: () => void;
|
|
45
46
|
reset: () => void;
|
|
46
47
|
setMode: (mode: AppearanceMode) => void;
|
|
47
48
|
}
|
|
@@ -85,6 +86,14 @@ interface AIAutocompleteProps {
|
|
|
85
86
|
animations?: boolean;
|
|
86
87
|
/** When the dropdown appears. "auto" (default) = shows when options available. "manual" = only on pill tap, closes after selection. "hidden" = never shows. */
|
|
87
88
|
dropdownTrigger?: "auto" | "manual" | "hidden";
|
|
89
|
+
/** 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. */
|
|
90
|
+
closeDropdownOnBlur?: boolean;
|
|
91
|
+
/** Focus the input on mount. Default: true. */
|
|
92
|
+
autoFocus?: boolean;
|
|
93
|
+
/** Called when the input gains focus. */
|
|
94
|
+
onFocus?: () => void;
|
|
95
|
+
/** Called when the input loses focus. */
|
|
96
|
+
onBlur?: () => void;
|
|
88
97
|
value?: string;
|
|
89
98
|
completedParams?: CompletedParamState[];
|
|
90
99
|
onChange?: (value: string) => void;
|
|
@@ -104,6 +113,12 @@ interface UseAIAutocompleteOptions {
|
|
|
104
113
|
columns?: number;
|
|
105
114
|
/** When the dropdown appears. Default: "auto". */
|
|
106
115
|
dropdownTrigger?: "auto" | "manual" | "hidden";
|
|
116
|
+
/** When true (default), the dropdown closes when the input loses focus. Set to false to keep it open whenever options are available. */
|
|
117
|
+
closeDropdownOnBlur?: boolean;
|
|
118
|
+
/** Called when the input gains focus. */
|
|
119
|
+
onFocus?: () => void;
|
|
120
|
+
/** Called when the input loses focus. */
|
|
121
|
+
onBlur?: () => void;
|
|
107
122
|
value?: string;
|
|
108
123
|
completedParams?: CompletedParamState[];
|
|
109
124
|
onChange?: (value: string) => void;
|
|
@@ -158,6 +173,6 @@ declare const AIAutocomplete: react.ForwardRefExoticComponent<AIAutocompleteProp
|
|
|
158
173
|
|
|
159
174
|
declare function AIAutocompleteDropdown({ suggestions, activeIndex, onSelect, onHighlight, isOpen, id, className, pills, onPillClick, showPills, }: AIAutocompleteDropdownProps): react_jsx_runtime.JSX.Element;
|
|
160
175
|
|
|
161
|
-
declare function useAIAutocomplete({ onSubmit, onError, optionOverrides, maskCompletedText, apiConfig, columns, dropdownTrigger, value: controlledValue, completedParams: controlledParams, onChange: onChangeProp, onParamsChange, }: UseAIAutocompleteOptions): UseAIAutocompleteReturn;
|
|
176
|
+
declare function useAIAutocomplete({ onSubmit, onError, optionOverrides, maskCompletedText, apiConfig, columns, dropdownTrigger, closeDropdownOnBlur, onFocus, onBlur, value: controlledValue, completedParams: controlledParams, onChange: onChangeProp, onParamsChange, }: UseAIAutocompleteOptions): UseAIAutocompleteReturn;
|
|
162
177
|
|
|
163
178
|
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
|
@@ -42,6 +42,7 @@ type Segment = {
|
|
|
42
42
|
type AppearanceMode = "light" | "dark" | "auto";
|
|
43
43
|
interface AIAutocompleteHandle {
|
|
44
44
|
focus: () => void;
|
|
45
|
+
blur: () => void;
|
|
45
46
|
reset: () => void;
|
|
46
47
|
setMode: (mode: AppearanceMode) => void;
|
|
47
48
|
}
|
|
@@ -85,6 +86,14 @@ interface AIAutocompleteProps {
|
|
|
85
86
|
animations?: boolean;
|
|
86
87
|
/** When the dropdown appears. "auto" (default) = shows when options available. "manual" = only on pill tap, closes after selection. "hidden" = never shows. */
|
|
87
88
|
dropdownTrigger?: "auto" | "manual" | "hidden";
|
|
89
|
+
/** 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. */
|
|
90
|
+
closeDropdownOnBlur?: boolean;
|
|
91
|
+
/** Focus the input on mount. Default: true. */
|
|
92
|
+
autoFocus?: boolean;
|
|
93
|
+
/** Called when the input gains focus. */
|
|
94
|
+
onFocus?: () => void;
|
|
95
|
+
/** Called when the input loses focus. */
|
|
96
|
+
onBlur?: () => void;
|
|
88
97
|
value?: string;
|
|
89
98
|
completedParams?: CompletedParamState[];
|
|
90
99
|
onChange?: (value: string) => void;
|
|
@@ -104,6 +113,12 @@ interface UseAIAutocompleteOptions {
|
|
|
104
113
|
columns?: number;
|
|
105
114
|
/** When the dropdown appears. Default: "auto". */
|
|
106
115
|
dropdownTrigger?: "auto" | "manual" | "hidden";
|
|
116
|
+
/** When true (default), the dropdown closes when the input loses focus. Set to false to keep it open whenever options are available. */
|
|
117
|
+
closeDropdownOnBlur?: boolean;
|
|
118
|
+
/** Called when the input gains focus. */
|
|
119
|
+
onFocus?: () => void;
|
|
120
|
+
/** Called when the input loses focus. */
|
|
121
|
+
onBlur?: () => void;
|
|
107
122
|
value?: string;
|
|
108
123
|
completedParams?: CompletedParamState[];
|
|
109
124
|
onChange?: (value: string) => void;
|
|
@@ -158,6 +173,6 @@ declare const AIAutocomplete: react.ForwardRefExoticComponent<AIAutocompleteProp
|
|
|
158
173
|
|
|
159
174
|
declare function AIAutocompleteDropdown({ suggestions, activeIndex, onSelect, onHighlight, isOpen, id, className, pills, onPillClick, showPills, }: AIAutocompleteDropdownProps): react_jsx_runtime.JSX.Element;
|
|
160
175
|
|
|
161
|
-
declare function useAIAutocomplete({ onSubmit, onError, optionOverrides, maskCompletedText, apiConfig, columns, dropdownTrigger, value: controlledValue, completedParams: controlledParams, onChange: onChangeProp, onParamsChange, }: UseAIAutocompleteOptions): UseAIAutocompleteReturn;
|
|
176
|
+
declare function useAIAutocomplete({ onSubmit, onError, optionOverrides, maskCompletedText, apiConfig, columns, dropdownTrigger, closeDropdownOnBlur, onFocus, onBlur, value: controlledValue, completedParams: controlledParams, onChange: onChangeProp, onParamsChange, }: UseAIAutocompleteOptions): UseAIAutocompleteReturn;
|
|
162
177
|
|
|
163
178
|
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 Ie=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var Ge=Object.getOwnPropertyNames;var Xe=Object.prototype.hasOwnProperty;var Je=(o,e)=>{for(var t in e)Ie(o,t,{get:e[t],enumerable:!0})},Ye=(o,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ge(e))!Xe.call(o,r)&&r!==t&&Ie(o,r,{get:()=>e[r],enumerable:!(i=je(e,r))||i.enumerable});return o};var Ze=o=>Ye(Ie({},"__esModule",{value:!0}),o);var vt={};Je(vt,{AIAutocomplete:()=>We,AIAutocompleteDropdown:()=>re,useAIAutocomplete:()=>fe});module.exports=Ze(vt);var _=require("react");if(typeof document<"u"&&!document.getElementById("ac-style-cc65f4cc")){let o=document.createElement("style");o.id="ac-style-cc65f4cc",o.textContent=`.AIAutocomplete-module_container_KKjFU {
|
|
2
2
|
position: relative;
|
|
3
3
|
font-family: "IBM Plex Sans", sans-serif;
|
|
4
4
|
container-type: inline-size;
|
|
@@ -142,7 +142,7 @@
|
|
|
142
142
|
.AIAutocomplete-module_shimmerHidden_45-Pf {
|
|
143
143
|
color: transparent !important;
|
|
144
144
|
}
|
|
145
|
-
`,document.head.appendChild(o)}var
|
|
145
|
+
`,document.head.appendChild(o)}var k={container:"AIAutocomplete-module_container_KKjFU",inputWrapper:"AIAutocomplete-module_inputWrapper_FLq1b",editorArea:"AIAutocomplete-module_editorArea_7rBWq",sizerContent:"AIAutocomplete-module_sizerContent_DQgmV",sizerText:"AIAutocomplete-module_sizerText_iZIMK",sizerTextVisible:"AIAutocomplete-module_sizerTextVisible_HR-5h",textareaHidden:"AIAutocomplete-module_textareaHidden_UayJt",placeholderText:"AIAutocomplete-module_placeholderText_K3ayy",textarea:"AIAutocomplete-module_textarea_eyn6A",submitButton:"AIAutocomplete-module_submitButton_sl1Mi",shimmer:"AIAutocomplete-module_shimmer_13AnY",shimmerRevealed:"AIAutocomplete-module_shimmerRevealed_RR8dp",shimmerSweep:"AIAutocomplete-module_shimmerSweep_ARCon",textShimmer:"AIAutocomplete-module_textShimmer_eCLdq",shimmerHidden:"AIAutocomplete-module_shimmerHidden_45-Pf"};if(typeof document<"u"&&!document.getElementById("ac-style-2eef895d")){let o=document.createElement("style");o.id="ac-style-2eef895d",o.textContent=`.AIAutocompleteDropdown-module_dropdown_yz2KC {
|
|
146
146
|
position: absolute;
|
|
147
147
|
left: 0;
|
|
148
148
|
top: 100%;
|
|
@@ -178,7 +178,7 @@
|
|
|
178
178
|
.AIAutocompleteDropdown-module_pillBar_pwTXe {
|
|
179
179
|
padding: 27px 27px 0px 27px;
|
|
180
180
|
}
|
|
181
|
-
`,document.head.appendChild(o)}var
|
|
181
|
+
`,document.head.appendChild(o)}var oe={dropdown:"AIAutocompleteDropdown-module_dropdown_yz2KC",visible:"AIAutocompleteDropdown-module_visible_QCoXj",pillBar:"AIAutocompleteDropdown-module_pillBar_pwTXe"};if(typeof document<"u"&&!document.getElementById("ac-style-b745b4fb")){let o=document.createElement("style");o.id="ac-style-b745b4fb",o.textContent=`.PillList-module_list_qvLqO {
|
|
182
182
|
position: relative;
|
|
183
183
|
z-index: 1;
|
|
184
184
|
pointer-events: auto;
|
|
@@ -241,7 +241,7 @@
|
|
|
241
241
|
opacity: 0;
|
|
242
242
|
}
|
|
243
243
|
}
|
|
244
|
-
`,document.head.appendChild(o)}var
|
|
244
|
+
`,document.head.appendChild(o)}var W={list:"PillList-module_list_qvLqO",pill:"PillList-module_pill_osSyz",fadeIn:"PillList-module_fadeIn_Aezob",rounded:"PillList-module_rounded_WvXy4",active:"PillList-module_active_Oll--"};var _e=require("react/jsx-runtime");function et(o){return o===0?.4:o===1?.3:.15}function ie({pills:o,activePillIndex:e,onSelectPill:t,rounded:i}){return(0,_e.jsx)("span",{className:W.list,children:o.map((r,n)=>(0,_e.jsx)("button",{type:"button","data-aia-pill":"",className:`${W.pill} ${i?W.rounded:""} ${n===e?W.active:""}`,style:{opacity:et(n)},onClick:()=>t(n),children:r.text},`${r.type}-${r.text}`))})}var L=require("react");if(typeof document<"u"&&!document.getElementById("ac-style-d91f2b06")){let o=document.createElement("style");o.id="ac-style-d91f2b06",o.textContent=`.SuggestionGrid-module_scrollWrapper_MOqfw {
|
|
245
245
|
position: relative;
|
|
246
246
|
}
|
|
247
247
|
|
|
@@ -293,7 +293,7 @@
|
|
|
293
293
|
background: var(--aia-scrollbar-thumb, rgba(0, 0, 0, 0.3));
|
|
294
294
|
border-radius: 3px;
|
|
295
295
|
}
|
|
296
|
-
`,document.head.appendChild(o)}var
|
|
296
|
+
`,document.head.appendChild(o)}var Ce={scrollWrapper:"SuggestionGrid-module_scrollWrapper_MOqfw",grid:"SuggestionGrid-module_grid_jvaPb"};var K=require("react");if(typeof document<"u"&&!document.getElementById("ac-style-f6bdc634")){let o=document.createElement("style");o.id="ac-style-f6bdc634",o.textContent=`.SuggestionItem-module_item_d4vpD {
|
|
297
297
|
position: relative;
|
|
298
298
|
overflow: visible;
|
|
299
299
|
display: flex;
|
|
@@ -604,7 +604,7 @@
|
|
|
604
604
|
box-shadow: 0 0 24px 10px rgba(var(--aia-streak-rgb, 255, 255, 255), 0.02);
|
|
605
605
|
}
|
|
606
606
|
}
|
|
607
|
-
`,document.head.appendChild(o)}var
|
|
607
|
+
`,document.head.appendChild(o)}var O={item:"SuggestionItem-module_item_d4vpD",fadeIn:"SuggestionItem-module_fadeIn_I8u35",content:"SuggestionItem-module_content_T-Qba",tappable:"SuggestionItem-module_tappable_70KcX",nonTappable:"SuggestionItem-module_nonTappable_xSZM-",highlighted:"SuggestionItem-module_highlighted_Hb0SU",tag:"SuggestionItem-module_tag_e3Fwe",pressed:"SuggestionItem-module_pressed_98o-r",glassFade:"SuggestionItem-module_glassFade_oyiSj",tapDown:"SuggestionItem-module_tapDown_G3WGz",streaks:"SuggestionItem-module_streaks_d9PEB",streaksVert:"SuggestionItem-module_streaksVert_ERlV1",streakHorizRight:"SuggestionItem-module_streakHorizRight_aboGz",streakHorizLeft:"SuggestionItem-module_streakHorizLeft_BreWJ",streakVertUp:"SuggestionItem-module_streakVertUp_to1GD",streakVertDown:"SuggestionItem-module_streakVertDown_OrcLh"};var z=require("react/jsx-runtime");function Oe({option:o,isHighlighted:e,onSelect:t,onHighlight:i,id:r}){let[n,a]=(0,K.useState)(!1),p=(0,K.useRef)(void 0);(0,K.useEffect)(()=>()=>clearTimeout(p.current),[]);let s=()=>{!o.is_tappable||n||(a(!0),t(o),clearTimeout(p.current),p.current=setTimeout(()=>a(!1),400))},l=[O.item,e?O.highlighted:"",o.is_tappable?O.tappable:O.nonTappable,n?O.pressed:""].filter(Boolean).join(" ");return(0,z.jsxs)("div",{id:r,role:"option","data-aia-option":"","aria-selected":e,className:l,tabIndex:o.is_tappable?0:-1,onClick:s,onKeyDown:d=>{o.is_tappable&&(d.key==="Enter"||d.key===" ")&&(d.preventDefault(),s())},onMouseEnter:o.is_tappable?i:void 0,children:[(0,z.jsx)("div",{className:O.streaks}),(0,z.jsx)("div",{className:O.streaksVert}),(0,z.jsxs)("span",{className:O.content,children:[o.icon?`${o.icon} ${o.text}`:o.text,o.tag&&(0,z.jsx)("span",{className:O.tag,children:o.tag})]})]})}var ne=require("react/jsx-runtime");function De({options:o,activeIndex:e,onSelect:t,onHighlight:i,listboxId:r}){let n=(0,L.useRef)(null),[a,p]=(0,L.useState)(!1);return(0,L.useEffect)(()=>{let s=n.current;if(!s)return;let l=()=>{p(s.scrollHeight-s.scrollTop-s.clientHeight>1)};s.addEventListener("scroll",l,{passive:!0});let d=new ResizeObserver(l);return d.observe(s),()=>{s.removeEventListener("scroll",l),d.disconnect()}},[]),(0,L.useLayoutEffect)(()=>{let s=n.current;s&&p(s.scrollHeight-s.scrollTop-s.clientHeight>1)},[o]),(0,ne.jsx)("div",{className:Ce.scrollWrapper,"data-fade":a?"":void 0,children:(0,ne.jsx)("div",{ref:n,className:Ce.grid,children:o.map((s,l)=>(0,ne.jsx)(Oe,{option:s,isHighlighted:l===e,onSelect:t,onHighlight:()=>i(l),id:`${r}-option-${l}`},s.text))})})}var $=require("react/jsx-runtime");function re({suggestions:o,activeIndex:e,onSelect:t,onHighlight:i,isOpen:r,id:n,className:a,pills:p,onPillClick:s,showPills:l=!0}){let c=o[0]?.options??[],m=l&&p&&p.length>0&&s,g=r&&c.length>0||r&&m;return(0,$.jsxs)("div",{id:n,role:"listbox","data-aia-dropdown":"",className:`${oe.dropdown} ${g?oe.visible:""} ${a??""}`,onMouseDown:w=>w.preventDefault(),children:[m&&(0,$.jsx)("div",{className:oe.pillBar,"data-aia-pillbar":"",children:(0,$.jsx)(ie,{pills:p,activePillIndex:0,onSelectPill:s,rounded:!0})}),c.length>0&&(0,$.jsx)(De,{options:c,activeIndex:e,onSelect:t,onHighlight:i,listboxId:n})]})}if(typeof document<"u"&&!document.getElementById("ac-style-dc8da745")){let o=document.createElement("style");o.id="ac-style-dc8da745",o.textContent=`/*
|
|
608
608
|
* Built-in appearance defaults \u2014 zero specificity via :where().
|
|
609
609
|
* Consumer CSS always wins without !important.
|
|
610
610
|
*
|
|
@@ -683,5 +683,5 @@
|
|
|
683
683
|
animation-duration: 0s !important;
|
|
684
684
|
transition-duration: 0s !important;
|
|
685
685
|
}
|
|
686
|
-
`,document.head.appendChild(o)}var b=require("react");function Q(o,e,t){let i=o.slice(e);if(t||e===0||o[e-1]===" ")return i;let r=i.indexOf(" ");return r===-1?"":i.slice(r+1)}function Ae(o,e){let t=o.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let i=t.split(" "),r=e.toLowerCase();for(let n=0;n<i.length;n++){let a=i.slice(n).join(" ");if(r.startsWith(a.toLowerCase())){let d=t.length-a.length;return o.length-d}}return 0}function te(o,e){if(!o)return[];let t=e.trimStart();if(!t)return o;let i=t.toLowerCase();return o.filter(r=>!r.is_tappable||r.text.toLowerCase().includes(i))}function we(o,e){if(!o)return null;let t=e.trim();if(!t)return null;let i=t.toLowerCase();return o.find(r=>r.is_tappable&&r.text.toLowerCase()===i)??null}var F=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 ke(o,e){let t=[],i=0;for(let n of e){let a=o.indexOf(n.text,i);a!==-1&&(a>i&&t.push({type:"text",value:o.slice(i,a)}),t.push({type:"completed",value:n.text,param:n}),i=a+n.text.length)}let r=o.slice(i);return r&&t.push({type:"text",value:r}),t}function Te(o,e){let t=[],i=[],r=0;for(let n of e){let a=o.indexOf(n.text,r);a===-1?i.push(n):(t.push(n),r=a+n.text.length)}return{valid:t,invalid:i}}var oe=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 Xe="0.1.26",Oe=!1;function Je(){return crypto.randomUUID()}function Ye(o,e){return{placeholder:o.placeholder,type:o.type,...e&&{text:o.text},kind:o.kind}}function Le(o){return o?.type==="accessToken"}function Ze(o){if(!(!o||Le(o)))return o}var De=new WeakMap;function et(o){let e=De.get(o.getAccessToken);return e||(e=new oe(o),De.set(o.getAccessToken,e)),e}function tt(o,e,t){let i=e.find(n=>n.type==="contact"&&n.metadata?.contact_account_count)?.metadata?.contact_account_count,r=typeof i=="number"?i:void 0;return{data:{raw_query:o,completed_params:e.map(n=>Ye(n,t)),...r!=null&&{contact_account_count:r}},meta:{request_id:Je(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:Xe}}}function ot(o){return{"Content-Type":"application/json",...o?.appIdentifier&&{"X-App-Identifier":o.appIdentifier},...o?.headers}}async function Ee(o,e,t,i,r){return fetch(o,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:r})}async function Re(o,e,t){let i=t?.apiConfig,r=!t?.maskCompletedText,n=tt(o,e,r),a=ot(i),d=i?.endpoint??"/ac/suggest",s=JSON.stringify(n);if(Le(i)){let m=et(i),h=await m.getToken(),g=await Ee(d,a,h,s,t?.signal);if(g.status===401){let _=await m.getToken(!0);g=await Ee(d,a,_,s,t?.signal)}if(!g.ok)throw new Error(`API error: ${g.status} ${g.statusText}`);return g.json()}let l=Ze(i),p=l?.apiKey??"";if(!p&&!Oe&&(Oe=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),p){let m=l?.authScheme??"Bearer";a.Authorization=m==="Basic"?`Basic ${btoa(p)}`:`Bearer ${p}`}let c=await fetch(d,{method:"POST",headers:a,body:s,signal:t?.signal});if(!c.ok)throw new Error(`API error: ${c.status} ${c.statusText}`);return c.json()}function E(o,e){let t=o,i={},r=[];for(let n of e){let a=(i[n.type]??0)+1;i[n.type]=a;let s=`{{${n.type.toUpperCase().replace(/\s+/g,"_")}_${a}}}`,l=t.indexOf(n.text);l!==-1&&(t=t.slice(0,l)+s+t.slice(l+n.text.length)),r.push({...n,placeholder:s})}return{rawQuery:t,completedParams:r}}function Me(o,e){return e?o.map(t=>{let i=e[t.type];if(!i)return t;let r=i("");if(r.length===0)return t;let n=new Set(r.map(d=>d.text)),a=(t.options??[]).filter(d=>!n.has(d.text));return{...t,options:[...r,...a]}}):o}var it=100,nt=300,rt=2,ie=class{constructor(e,t,i,r,n){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=r;this.getOnError=n;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null}start(){this.doFetch("",[]);let e=this.store.get().text,t=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(i=>{(i.text!==e||i.completedParams!==t)&&(e=i.text,t=i.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let i=new AbortController;this.abortController=i;let r=++this.fetchVersion,n=this.store.get(),a=n.text.length;n.suggestions.some(s=>s.type!=="placeholder")||this.store.set({isLoading:!0}),this.store.set({error:null});try{let s=await Re(e,t,{maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig()});if(r!==this.fetchVersion)return;let l=Me(s.data.suggestions??[],this.getOptionOverrides()),p=s.data.input??[],c=p[p.length-1],m=this.store.get().text,h,g;if(c?.state==="in_progress"){g=!0;let u=m.toLowerCase().lastIndexOf(c.text.toLowerCase());h=u!==-1?u:a}else g=!1,h=a;let x=l.filter(u=>u.type!=="placeholder")[0],P=null;if(x){let u=Q(m,h,g),y=we(x.options,u);y&&(P={id:crypto.randomUUID(),placeholder:"",type:x.type,text:y.text,kind:y.kind,suggestionType:x.type,suggestionPlaceholder:x.text,options:x.options??[],metadata:y.metadata},l=l.filter(M=>M!==x))}this.store.set(u=>({suggestions:l,isLoading:!1,isReady:s.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:h,filterInProgress:g,...P?{completedParams:[...u.completedParams,P]}:{}}))}catch(s){if(r===this.fetchVersion){let l=s instanceof Error?s:new Error(String(s));this.store.set({error:l,isLoading:!1}),this.getOnError()?.(l)}}}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}let t=i=>{let r=this.store.get();if(!r.text&&r.completedParams.length===0)return this.doFetch("",[]),!0;let n=Q(r.text,r.filterBase,r.filterInProgress),d=r.suggestions.filter(x=>x.type!=="placeholder")[0],l=(d?te(d.options,n):[]).filter(x=>x.is_tappable),p=d?we(d.options,n)!==null:!1,c=n.trim().length>0;if(l.length>0&&!p&&c)return!1;if(r.completedParams.length===0&&r.text.length>0){let x=r.suggestions.filter(P=>P.type==="placeholder").map(P=>P.text).join(" ");if(x.length>0&&x.toLowerCase().startsWith(r.text.toLowerCase()))return!1}let{rawQuery:m,completedParams:h}=E(r.text,r.completedParams),g=m.length<r.lastRawQuery.length,_=Math.abs(m.length-r.lastRawQuery.length);return g||_>=i?(this.doFetch(m,h),!0):!1};this.debounceTimer=setTimeout(()=>{t(rt)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},it),this.slowDebounceTimer=setTimeout(()=>t(1),nt)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var ne=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:r}=this.ctx,n=this.getEffectiveColumns(),a=r(),d=this.getTappableIndices(n);switch(e.key){case"ArrowDown":{let s=e.target;if(!(s.selectionStart!=null&&s.selectionStart===s.value.length)&&t.activeDropdownIndex<0)break;if(e.preventDefault(),!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:d[0]??0});break}if(d.length===0)return;let p=d.indexOf(t.activeDropdownIndex),c=p<d.length-1?p+1:0;this.store.set({activeDropdownIndex:d[c]});break}case"ArrowUp":{if(d.length===0||t.activeDropdownIndex<0)break;if(e.preventDefault(),t.activeDropdownIndex<n){this.store.set({activeDropdownIndex:-1});break}let s=d.indexOf(t.activeDropdownIndex),l=s>0?s-1:d.length-1;this.store.set({activeDropdownIndex:d[l]});break}case"ArrowRight":{if(t.activeDropdownIndex<0){let l=e.target;l.selectionStart!=null&&l.selectionStart===l.value.length&&t.actionableSuggestions.length>1&&(e.preventDefault(),this.pillsSetActivePill(1));break}if(t.activeDropdownIndex%n<n-1){let l=t.activeDropdownIndex+1;l<t.filteredOptions.length&&t.filteredOptions[l]?.is_tappable&&(e.preventDefault(),this.store.set({activeDropdownIndex:l}))}break}case"ArrowLeft":{if(t.activeDropdownIndex<0)break;if(t.activeDropdownIndex%n>0){let s=t.activeDropdownIndex-1;s>=0&&t.filteredOptions[s]?.is_tappable&&(e.preventDefault(),this.store.set({activeDropdownIndex:s}))}break}case"Enter":{if(e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable)this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i);else if(a){let{rawQuery:s,completedParams:l}=E(t.text,t.completedParams);a({query:t.text.trim(),raw_query:s,completed_params:l})}break}case"Tab":{let s=!t.text&&!!t.placeholderText,l=t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable;if(s&&!l){e.preventDefault();let p=t.suggestions.find(c=>c.type==="placeholder");p?this.store.set(c=>({text:t.placeholderText,filterBase:t.placeholderText.length,completedParams:[...c.completedParams,{id:crypto.randomUUID(),placeholder:"",type:p.type,text:t.placeholderText,kind:null,suggestionType:p.type,suggestionPlaceholder:p.text,options:p.options??[]}],suggestions:c.suggestions.filter(m=>m!==p)})):this.store.set({text:t.placeholderText,filterBase:t.placeholderText.length})}else if(l)e.preventDefault(),this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i);else if(t.isDropdownOpen){let p=t.filteredOptions.findIndex(c=>c.is_tappable);p>=0&&(e.preventDefault(),this.clickOrSelect(p,t.filteredOptions,i))}break}case"Escape":this.store.set({activeDropdownIndex:-1});break}}getTappableIndices(e){let i=this.store.get().filteredOptions.map((n,a)=>n.is_tappable?a:-1).filter(n=>n!==-1),r=Array.from({length:e},()=>[]);for(let n of i)r[n%e].push(n);return r.flat()}getEffectiveColumns(){let t=document.getElementById(`${this.ctx.listboxId}-option-0`)?.parentElement;if(!t)return this.ctx.columns;let i=getComputedStyle(t).gridTemplateColumns.split(" ").filter(Boolean).length;return i>0?i:this.ctx.columns}clickOrSelect(e,t,i){let r=document.getElementById(`${i}-option-${e}`);r?r.click():this.ctx.selectOption(t[e])}pillsSetActivePill(e){let t=this.store.get(),i=t.suggestions.filter(d=>d.type!=="placeholder");if(e<0||e>=i.length)return;let r=i[e],n=i.filter((d,s)=>s!==e),a=t.suggestions.filter(d=>d.type==="placeholder");this.store.set({suggestions:[...a,r,...n],pillTapped:!0,activeDropdownIndex:-1})}};var re=class{constructor(e){this.store=e}setActivePill(e){let t=this.store.get(),i=t.suggestions.filter(d=>d.type!=="placeholder");if(e<0||e>=i.length)return;let r=i[e],n=i.filter((d,s)=>s!==e),a=t.suggestions.filter(d=>d.type==="placeholder");this.store.set({suggestions:[...a,r,...n],pillTapped:!0,activeDropdownIndex:-1})}removeLastParam(){let e=this.store.get();if(e.completedParams.length===0)return;let t=e.completedParams[e.completedParams.length-1],i={type:t.suggestionType,text:t.suggestionPlaceholder,required:!0,options:t.options};this.store.set(r=>({completedParams:r.completedParams.slice(0,-1),suggestions:[i,...r.suggestions],activeDropdownIndex:-1}))}};function st(o){return o===0?.4:o===1?.3:.15}function se(o,e,t,i,r=!1){let n=o.querySelector(".magicx-aia-pill-list");n||(n=document.createElement("span"),n.className="magicx-aia-pill-list",o.appendChild(n));let a=new Map;for(let s of n.querySelectorAll(".magicx-aia-pill"))a.set(s.dataset.pillKey??"",s);let d=new Set;for(let s=0;s<e.length;s++){let l=e[s],p=`${l.type}-${l.text}`;d.add(p);let c=a.get(p);c||(c=document.createElement("button"),c.type="button",c.dataset.pillKey=p,c.setAttribute("data-aia-pill",""),c.textContent=l.text),c.className=`magicx-aia-pill${r?" magicx-aia-pill--rounded":""}${s===t?" magicx-aia-pill--active":""}`,c.style.opacity=String(st(s)),c.onclick=()=>i(s),n.children[s]!==c&&n.insertBefore(c,n.children[s]??null)}for(let[s,l]of a)d.has(s)||l.remove()}function ae(o){let e=document.createElement("div");return e.id=o,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",t=>t.preventDefault()),e}function le(o,e){let{filteredOptions:t,activeIndex:i,isOpen:r,pills:n,showPills:a,onSelect:d,onHighlight:s,onPillClick:l}=e,p=a&&n.length>0;r&&t.length>0||r&&p?o.classList.add("magicx-aia-dropdown--visible"):o.classList.remove("magicx-aia-dropdown--visible");let h=o.querySelector(".magicx-aia-pill-bar");p?(h||(h=document.createElement("div"),h.className="magicx-aia-pill-bar",h.setAttribute("data-aia-pillbar",""),o.insertBefore(h,o.firstChild)),se(h,n,0,l,!0)):h&&h.remove();let g=o.querySelector(".magicx-aia-grid");t.length>0?(g||(g=document.createElement("div"),g.className="magicx-aia-grid",o.appendChild(g)),at(g,t,i,d,s,e.listboxId)):g&&(g.innerHTML="")}function at(o,e,t,i,r,n){let a=e.map(l=>l.text).join("\0"),d=o.dataset.optionsKey??"",s=a!==d;if(o.dataset.optionsKey=a,s){let l=document.createDocumentFragment();for(let p=0;p<e.length;p++){let c=e[p],m=lt(c,p,t,i,r,n);l.appendChild(m)}o.innerHTML="",o.appendChild(l)}else{let l=o.querySelectorAll(".magicx-aia-option");for(let p=0;p<l.length;p++){let c=l[p],m=p===t;c.setAttribute("aria-selected",String(m)),m?c.classList.add("magicx-aia-option--highlighted"):c.classList.remove("magicx-aia-option--highlighted")}}}function lt(o,e,t,i,r,n){let a=document.createElement("div");a.id=`${n}-option-${e}`,a.setAttribute("role","option"),a.setAttribute("data-aia-option",""),a.setAttribute("aria-selected",String(e===t)),a.tabIndex=o.is_tappable?0:-1;let d=["magicx-aia-option"];e===t&&d.push("magicx-aia-option--highlighted"),o.is_tappable?d.push("magicx-aia-option--tappable"):d.push("magicx-aia-option--non-tappable"),a.className=d.join(" ");let s=document.createElement("div");s.className="magicx-aia-streaks",a.appendChild(s);let l=document.createElement("div");l.className="magicx-aia-streaks-vert",a.appendChild(l);let p=document.createElement("span");if(p.className="magicx-aia-option-content",p.textContent=o.icon?`${o.icon} ${o.text}`:o.text,o.tag){let c=document.createElement("span");c.className="magicx-aia-option-tag",c.textContent=o.tag,p.appendChild(c)}return a.appendChild(p),o.is_tappable&&(a.addEventListener("click",()=>{a.classList.add("magicx-aia-option--pressed"),i(o),setTimeout(()=>a.classList.remove("magicx-aia-option--pressed"),400)}),a.addEventListener("mouseenter",()=>r(e))),a}function He(o,e){let t=ae(e.listboxId);return o.appendChild(t),{dropdown:t}}function Se(o,e,t){le(o.dropdown,{suggestions:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,onSelect:t.selectOption,onHighlight:i=>t.store.set({activeDropdownIndex:i}),onPillClick:t.setActivePill})}function ze(o,e,t,i,r){let n=o.querySelector(".magicx-aia-sizer-text"),a=o.querySelector(".magicx-aia-placeholder");if(i&&r){n&&(n.style.display="none"),a||(a=document.createElement("span"),a.className="magicx-aia-placeholder",o.insertBefore(a,o.firstChild)),a.style.display="",a.textContent=`${r} `,o.dataset.segmentKey="";return}a&&(a.style.display="none"),n||(n=document.createElement("span"),n.className="magicx-aia-sizer-text",o.insertBefore(n,o.firstChild)),n.style.display="",n.className=`magicx-aia-sizer-text${t?" magicx-aia-sizer-text--visible":""}`;let d=e.map(p=>`${p.type}:${p.value}`).join("\0"),s=o.dataset.segmentKey??"",l=o.dataset.newParamId??"";if(!(d===s&&(t??"")===l)){o.dataset.segmentKey=d,o.dataset.newParamId=t??"",n.innerHTML="";for(let p of e){let c=document.createElement("span");p.type==="completed"&&(p.param.id===t?c.className="magicx-aia-shimmer-revealed magicx-aia-shimmer-sweep":c.className="magicx-aia-segment magicx-aia-segment--completed"),c.textContent=p.value,n.appendChild(c)}e.length===0&&(n.textContent="\xA0")}}var dt='<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 Be(o,e){let{listboxId:t}=e,i=ae(t);o.appendChild(i);let r=document.createElement("div");r.className="magicx-aia-input-wrapper",o.appendChild(r);let n=document.createElement("div");n.className="magicx-aia-editor",n.setAttribute("data-aia-editor",""),r.appendChild(n);let a=document.createElement("div");a.className="magicx-aia-sizer",a.setAttribute("aria-hidden","true"),n.appendChild(a);let d=document.createElement("span");a.appendChild(document.createTextNode(" ")),a.appendChild(d);let s=document.createElement("textarea");s.className="magicx-aia-textarea",s.rows=1,s.setAttribute("role","combobox"),s.setAttribute("aria-autocomplete","list"),s.setAttribute("aria-controls",t),s.setAttribute("data-aia-textarea",""),n.appendChild(s);let l=document.createElement("button");return l.type="button",l.className="magicx-aia-submit",l.setAttribute("aria-label","Submit"),l.setAttribute("data-aia-submit",""),l.innerHTML=dt,r.appendChild(l),r.addEventListener("click",()=>s.focus()),s.addEventListener("input",()=>{let p=s.value,m=p.length>0&&p[0]!==p[0].toUpperCase()?p[0].toUpperCase()+p.slice(1):p;e.handleChange(m)}),s.addEventListener("keydown",p=>e.handleKeyDown(p)),s.addEventListener("focus",()=>e.store.set({isFocused:!0})),s.addEventListener("blur",()=>e.store.set({isFocused:!1})),l.addEventListener("click",p=>{p.stopPropagation();let c=e.store.get();if(!(!!c.text||c.completedParams.length>0)||!e.onSubmit)return;let{rawQuery:h,completedParams:g}=E(c.text,c.completedParams);e.onSubmit({query:c.text.trim(),raw_query:h,completed_params:g})}),s.focus(),{textarea:s,dropdown:i,sizer:a,submitButton:l,inlinePillContainer:d}}function Ie(o,e,t){let{textarea:i,dropdown:r,sizer:n,submitButton:a,inlinePillContainer:d}=o,{pillPlacement:s,setActivePill:l,selectOption:p,store:c}=t;i.value!==e.text&&(i.value=e.text),e.placeholderText?i.placeholder=e.placeholderText:i.removeAttribute("placeholder"),i.setAttribute("aria-expanded",String(e.isDropdownOpen));let m=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";m?i.setAttribute("aria-activedescendant",m):i.removeAttribute("aria-activedescendant"),e.newParamId?i.classList.add("magicx-aia-textarea--hidden"):i.classList.remove("magicx-aia-textarea--hidden");let h=!!e.text||e.completedParams.length>0;a.disabled=!h,ze(n,e.segments,e.newParamId,!e.text,e.placeholderText),s==="inline"?se(d,e.actionableSuggestions,0,l):d.innerHTML="",le(r,{suggestions:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:s==="dropdown",onSelect:p,onHighlight:g=>c.set({activeDropdownIndex:g}),onPillClick:l})}function Ne(o){let e=o,t=new Set;return{get:()=>e,set:i=>{let r=typeof i=="function"?i(e):i,n={...e,...r},a=e;e=n;for(let d of t)d(n,a)},subscribe:i=>(t.add(i),()=>{t.delete(i)})}}var _e=!1;function Ke(){if(_e||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){_e=!0;return}_e=!0;let o=document.createElement("style");o.setAttribute("data-magicx-aia",""),o.textContent=pt,document.head.appendChild(o)}var pt="";var ct=0;function ut(){return`:ac-${++ct}:`}function Fe(){return{text:"",completedParams:[],suggestions:[],activeDropdownIndex:-1,newParamId:null,isLoading:!1,isReady:!1,error:null,segments:[],actionableSuggestions:[],filteredOptions:[],placeholderText:"",isDropdownOpen:!1,filterBase:0,filterInProgress:!1,pillTapped:!1,skipNextFetch:!1,lastRawQuery:"",isFocused:!1}}var de=class{constructor(e,t={}){this.store=Ne(Fe());this._listboxId=ut();this.modeController=null;this.unsubscribers=[];this.derivedInProgress=!1;this.domRefs=null;this.dropdownRefs=null;this.externalListeners=new Set;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 re(this.store),this.fetchController=new ie(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.opts.onError),this.keyboardController=new ne(this.store,{columns:t.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.opts.onSubmit,selectOption:i=>this.selectOption(i)}),this.unsubscribers.push(this.store.subscribe((i,r)=>{this.recomputeDerived(i,r)})),this.unsubscribers.push(this.store.subscribe((i,r)=>{i.text!==r.text&&this.opts.onChange?.(i.text),i.completedParams!==r.completedParams&&this.opts.onParamsChange?.(i.completedParams),this.opts.onStateChange?.(i)})),this.renderMode!=="headless"&&(Ke(),this.setupContainer()),this.renderMode==="full"?this.buildAndRenderFull():this.renderMode==="dropdown"&&this.buildAndRenderDropdown(),this.fetchController.start()}focus(){this.domRefs?.textarea.focus()}reset(){this.store.set({...Fe()}),this.fetchController.doFetch("",[])}destroy(){this.fetchController.dispose(),this.modeController?.destroy(),this.newParamTimer&&clearTimeout(this.newParamTimer),this.suggestionRemovalTimer&&clearTimeout(this.suggestionRemovalTimer),this.externalListeners.clear();for(let e of this.unsubscribers)e();this.unsubscribers=[],this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}setValue(e){this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e)}removeLastParam(){this.pillsController.removeLastParam()}clearNewParamId(){this.store.set({newParamId:null})}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}handleTextChange(e){this.handleChange(e)}handleKeyDown(e){this.keyboardController.handleKeyDown(e)}setFocused(e){this.store.get().isFocused!==e&&this.store.set({isFocused:e})}subscribe(e){return this.externalListeners.add(e),()=>{this.externalListeners.delete(e)}}getState(){return this.store.get()}get listboxId(){return this._listboxId}get isReady(){return this.store.get().isReady}on(e,t){switch(e){case"submit":return this.opts.onSubmit=t,()=>{this.opts.onSubmit=void 0};case"error":return this.opts.onError=t,()=>{this.opts.onError=void 0};case"change":return this.opts.onChange=t,()=>{this.opts.onChange=void 0};case"paramsChange":return this.opts.onParamsChange=t,()=>{this.opts.onParamsChange=void 0};case"stateChange":return this.opts.onStateChange=t,()=>{this.opts.onStateChange=void 0};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&&this.store.set({}),e.value!==void 0&&this.store.set({text:e.value}),e.completedParams!==void 0&&this.store.set({completedParams:e.completedParams})}selectOption(e){let t=this.store.get(),i=t.actionableSuggestions[0];if(!i)return;let r=t.filterBase,n=t.text.slice(0,r),a=n.length===0&&t.text.length===0,d=n.length===0&&t.text.length>0&&t.placeholderText.length>0&&t.placeholderText.toLowerCase().startsWith(t.text.toLowerCase());(a||d)&&t.placeholderText&&(n=`${t.placeholderText} `);let s=Ae(n,e.text);s>0&&(n=n.slice(0,n.length-s));let l=n.length>0&&n[n.length-1]!==" ",p=`${n}${l?" ":""}${e.text} `,c=(a||d)&&p.length>0?p[0].toUpperCase()+p.slice(1):p,m=c.toLowerCase().lastIndexOf(e.text.toLowerCase()),h=m>=0?c.slice(m,m+e.text.length):e.text,g={id:crypto.randomUUID(),placeholder:"",type:i.type,text:h,kind:e.kind,suggestionType:i.type,suggestionPlaceholder:i.text,options:i.options??[],metadata:e.metadata},_=t.actionableSuggestions.length-1;this.store.set(x=>({text:c,filterBase:c.length,completedParams:[...x.completedParams,g],newParamId:g.id,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:_>0})),this.suggestionRemovalTimer=window.setTimeout(()=>{this.store.set(x=>({suggestions:x.suggestions.filter(P=>P!==i)}))},400)}recomputeDerived(e,t){if(this.derivedInProgress)return;this.derivedInProgress=!0;let i=ke(e.text,e.completedParams),r=e.suggestions.filter(x=>x.type!=="placeholder"),n=r[0],a=n?this.opts.optionOverrides?.[n.type]:void 0,d=Math.min(e.filterBase,e.text.length),l=e.lastRawQuery!==""||d>0?Q(e.text,d,e.filterInProgress):"",p=n?a?a(l.trim()):n.options??[]:[],c=te(p,l),m=e.suggestions.filter(x=>x.type==="placeholder").map(x=>x.text).join(" "),h=this.opts.dropdownTrigger??"auto",g=!1;h==="auto"?g=!e.isLoading&&c.length>0&&e.isFocused:h==="manual"&&(g=!e.isLoading&&c.length>0&&e.pillTapped),this.store.set({segments:i,actionableSuggestions:r,filteredOptions:c,placeholderText:m,isDropdownOpen:g}),this.derivedInProgress=!1;let _=this.store.get();for(let x of this.externalListeners)x(_)}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 F(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},selectOption:i=>this.selectOption(i),setActivePill:i=>this.pillsController.setActivePill(i),handleKeyDown:i=>this.keyboardController.handleKeyDown(i),handleChange:i=>this.handleChange(i)};this.domRefs=Be(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&Ie(this.domRefs,this.store.get(),t)}),Ie(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=He(this.container,e),this.subscribeBatchedRender(()=>{this.dropdownRefs&&Se(this.dropdownRefs,this.store.get(),e)}),Se(this.dropdownRefs,this.store.get(),e),this.subscribeNewParamTimer()}subscribeBatchedRender(e){let t=!1;this.unsubscribers.push(this.store.subscribe(()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,t)=>{e.newParamId&&e.newParamId!==t.newParamId&&(this.newParamTimer&&clearTimeout(this.newParamTimer),this.newParamTimer=window.setTimeout(()=>{this.store.set({newParamId:null})},650))}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:r}=Te(e,t.completedParams);r.length>0&&this.store.set(n=>({completedParams:i,suggestions:[...r.map(a=>({type:a.suggestionType,text:a.suggestionPlaceholder,required:!0,options:a.options})),...n.suggestions]}))}};function pe({onSubmit:o,onError:e,optionOverrides:t,maskCompletedText:i,apiConfig:r,columns:n=2,dropdownTrigger:a,value:d,completedParams:s,onChange:l,onParamsChange:p}){let c=(0,b.useRef)(null),[m,h]=(0,b.useState)(null),g=(0,b.useRef)(o);g.current=o;let _=(0,b.useRef)(e);_.current=e;let x=(0,b.useRef)(l);x.current=l;let P=(0,b.useRef)(p);P.current=p,(0,b.useEffect)(()=>{if(typeof document>"u")return;let v=new de(document.createElement("div"),{renderMode:"headless",apiConfig:r,optionOverrides:t,maskCompletedText:i,columns:n,dropdownTrigger:a,value:d,completedParams:s,onSubmit:(...S)=>g.current?.(...S),onError:(...S)=>_.current?.(...S),onChange:(...S)=>x.current?.(...S),onParamsChange:(...S)=>P.current?.(...S)});c.current=v,h(v.getState());let f=v.subscribe(S=>h(S));return()=>{f(),v.destroy(),c.current===v&&(c.current=null)}},[]);let u=c.current,y=(0,b.useCallback)(()=>{},[]);(0,b.useEffect)(()=>{d!==void 0&&u?.setValue(d)},[d,u]),(0,b.useEffect)(()=>{s!==void 0&&u?.setCompletedParams(s)},[s,u]);let M=JSON.stringify(r??null),k=(0,b.useRef)(t),H=(0,b.useRef)(0);if(t!==k.current){let v=k.current,f=t,S=Object.keys(v??{}),q=Object.keys(f??{});(S.length!==q.length||q.some(V=>!v?.[V]||f[V]!==v[V]))&&H.current++,k.current=t}(0,b.useEffect)(()=>{u?.update({apiConfig:r,optionOverrides:t,dropdownTrigger:a})},[M,H.current,a,u]);let ce=(0,b.useCallback)(v=>{if(!u)return;let f=v.target.value,q=f.length>0&&!v.nativeEvent?.isComposing&&f[0]!==f[0].toUpperCase()?f[0].toUpperCase()+f.slice(1):f;u.handleTextChange(q)},[u]),ue=(0,b.useCallback)(v=>{u?.handleKeyDown(v.nativeEvent)},[u]),W=(0,b.useCallback)(()=>u?.setFocused(!0),[u]),L=(0,b.useCallback)(()=>u?.setFocused(!1),[u]),$=(0,b.useCallback)(v=>u?.setActivePill(v),[u]),O=(0,b.useCallback)(()=>u?.removeLastParam(),[u]),me=(0,b.useCallback)(()=>u?.clearNewParamId(),[u]),z=(0,b.useCallback)(()=>u?.reset(),[u]),j=(0,b.useCallback)(v=>u?.selectOption(v),[u]),ge=(0,b.useCallback)(v=>u?.setActiveDropdownIndex(v),[u]);if(!u)return{completedParams:s??[],suggestionPills:[],setActivePill:y,removeLastParam:y,segments:[],newParamId:null,clearNewParamId:y,suggestions:[],activeIndex:-1,isReady:!1,isLoading:!0,error:null,inputProps:{value:d??"",placeholder:void 0,onChange:y,onKeyDown:y,onFocus:y,onBlur:y,role:"combobox","aria-expanded":!1,"aria-activedescendant":void 0,"aria-autocomplete":"list","aria-controls":""},reset:y,dropdownProps:{suggestions:[],activeIndex:-1,onSelect:y,onHighlight:y,isOpen:!1,id:"",pills:[],onPillClick:y}};let w=m??u.getState(),G=d!==void 0?d:w.text,fe=s!==void 0?s:w.completedParams,B=w.actionableSuggestions,X=B[0],he=w.filteredOptions,xe=w.activeDropdownIndex>=0?`${u.listboxId}-option-${w.activeDropdownIndex}`:void 0;return{completedParams:fe,suggestionPills:B,setActivePill:$,removeLastParam:O,segments:w.segments,newParamId:w.newParamId,clearNewParamId:me,suggestions:w.suggestions,activeIndex:w.activeDropdownIndex,isReady:w.isReady,isLoading:w.isLoading,error:w.error,inputProps:{value:G,placeholder:w.placeholderText||void 0,onChange:ce,onKeyDown:ue,onFocus:W,onBlur:L,role:"combobox","aria-expanded":w.isDropdownOpen,"aria-activedescendant":xe,"aria-autocomplete":"list","aria-controls":u.listboxId},reset:z,dropdownProps:{suggestions:X?[{...X,options:he}]:[],activeIndex:w.activeDropdownIndex,onSelect:j,onHighlight:ge,isOpen:w.isDropdownOpen,id:u.listboxId,pills:B,onPillClick:$}}}var I=require("react/jsx-runtime");function mt(o){return o!=="auto"?o:typeof window>"u"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}var $e=(0,C.forwardRef)(function({onSubmit:e,onError:t,optionOverrides:i,maskCompletedText:r,className:n,apiConfig:a,columns:d,pillPlacement:s="inline",mode:l="auto",optionsPosition:p="below",animations:c=!0,dropdownTrigger:m,value:h,completedParams:g,onChange:_,onParamsChange:x},P){let u=(0,C.useRef)(null),y=(0,C.useRef)(null),M=(0,C.useRef)(()=>{}),k=(0,C.useRef)(null);(0,C.useEffect)(()=>{let f=u.current;if(f)return k.current?k.current.setMode(l):k.current=new F(f,l),()=>{k.current?.destroy(),k.current=null}},[l]);let{completedParams:H,suggestionPills:ce,setActivePill:ue,segments:W,newParamId:L,clearNewParamId:$,inputProps:O,dropdownProps:me,reset:z}=pe({onSubmit:f=>M.current(f),onError:t,optionOverrides:i,maskCompletedText:r,apiConfig:a,columns:d,dropdownTrigger:m,value:h,completedParams:g,onChange:_,onParamsChange:x}),j=O.onFocus;(0,C.useEffect)(()=>{let f=y.current;f&&(document.activeElement===f?j():f.focus())},[j]),(0,C.useEffect)(()=>{if(!L)return;let f=window.setTimeout(()=>$(),650);return()=>window.clearTimeout(f)},[L,$]),(0,C.useImperativeHandle)(P,()=>({focus:()=>y.current?.focus(),reset:z,setMode:f=>k.current?.setMode(f)}),[z]);let ge=()=>{y.current?.focus()},w=!!O.value||H.length>0,G=(0,C.useCallback)(()=>{if(!w)return;let{rawQuery:f,completedParams:S}=E(O.value,H);e({query:O.value.trim(),raw_query:f,completed_params:S}),z()},[w,O.value,H,e,z]);M.current=G;let{onChange:fe,placeholder:B,...X}=O,he=!O.value,xe=s==="inline",v=s==="dropdown";return(0,I.jsxs)("div",{ref:u,className:`magicx-aia ${A.container} ${n??""}`,"data-pill-placement":s,"data-options-position":p,"data-animations":c?"on":"off","data-mode":mt(l),children:[(0,I.jsx)(ee,{...me,showPills:v}),(0,I.jsxs)("div",{className:A.inputWrapper,onClick:ge,children:[(0,I.jsxs)("div",{className:A.editorArea,"data-aia-editor":"",children:[(0,I.jsxs)("div",{className:A.sizerContent,"aria-hidden":"true",children:[he&&B?(0,I.jsxs)("span",{className:A.placeholderText,children:[B," "]}):(0,I.jsxs)("span",{className:`${A.sizerText} ${L?A.sizerTextVisible:""}`,children:[W.map((f,S)=>{if(f.type==="completed"&&f.param.id===L){let V=`${A.shimmerRevealed} ${A.shimmerSweep}`;return(0,I.jsx)("span",{className:V,children:f.value},`${S}-${f.type}`)}return(0,I.jsx)("span",{children:f.value},`${S}-${f.type}`)}),W.length===0&&"\xA0"]})," ",xe&&(0,I.jsx)(Y,{pills:ce,activePillIndex:0,onSelectPill:ue})]}),(0,I.jsx)("textarea",{ref:y,"data-aia-textarea":"",className:`${A.textarea} ${L?A.textareaHidden:""}`,rows:1,onChange:fe,...X})]}),(0,I.jsx)("button",{type:"button","data-aia-submit":"",className:A.submitButton,disabled:!w,onClick:f=>{f.stopPropagation(),G()},"aria-label":"Submit",children:(0,I.jsx)("svg",{width:"18",height:"18",viewBox:"0 0 18 18",fill:"none",role:"img","aria-label":"Submit",children:(0,I.jsx)("path",{d:"M9 14V4M9 4L4 9M9 4L14 9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})});0&&(module.exports={AIAutocomplete,AIAutocompleteDropdown,useAIAutocomplete});
|
|
686
|
+
`,document.head.appendChild(o)}var x=require("react");function j(o,e,t){let i=o.slice(e);if(t||e===0||o[e-1]===" ")return i;let r=i.indexOf(" ");return r===-1?"":i.slice(r+1)}function Ee(o,e){let t=o.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let i=t.split(" "),r=e.toLowerCase();for(let n=0;n<i.length;n++){let a=i.slice(n).join(" ");if(r.startsWith(a.toLowerCase())){let p=t.length-a.length;return o.length-p}}return 0}function se(o,e){if(!o)return[];let t=e.trimStart();if(!t)return o;let i=t.toLowerCase();return o.filter(r=>!r.is_tappable||r.text.toLowerCase().includes(i))}function Pe(o,e){if(!o)return null;let t=e.trim();if(!t)return null;let i=t.toLowerCase();return o.find(r=>r.is_tappable&&r.text.toLowerCase()===i)??null}var q=class{constructor(e,t="auto"){this.container=e;this.mode=t;this.mediaQuery=null;this.onSystemChange=e=>{this.container.dataset.mode=e.matches?"dark":"light"};this.apply()}setMode(e){this.detachListener(),this.mode=e,this.apply()}destroy(){this.detachListener()}apply(){this.mode==="auto"?(this.mediaQuery??(this.mediaQuery=window.matchMedia("(prefers-color-scheme: dark)")),this.mediaQuery.addEventListener("change",this.onSystemChange),this.container.dataset.mode=this.mediaQuery.matches?"dark":"light"):this.container.dataset.mode=this.mode}detachListener(){this.mediaQuery?.removeEventListener("change",this.onSystemChange)}};function Le(o,e){let t=[],i=0;for(let n of e){let a=o.indexOf(n.text,i);a!==-1&&(a>i&&t.push({type:"text",value:o.slice(i,a)}),t.push({type:"completed",value:n.text,param:n}),i=a+n.text.length)}let r=o.slice(i);return r&&t.push({type:"text",value:r}),t}function Re(o,e){let t=[],i=[],r=0;for(let n of e){let a=o.indexOf(n.text,r);a===-1?i.push(n):(t.push(n),r=a+n.text.length)}return{valid:t,invalid:i}}var ae=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;this.inFlightRefresh=null;e.accessToken&&(this.current=e.accessToken)}async getToken(e=!1){if(!e&&this.current&&!this.isExpired())return this.current;if(!e&&this.inFlightRefresh)return this.inFlightRefresh;this.inFlightRefresh=this.refresh();try{return await this.inFlightRefresh}finally{this.inFlightRefresh=null}}async refresh(){let e=await this.config.getAccessToken();return this.current=e.accessToken,this.expiresAt=e.expiresAt??null,this.current}isExpired(){return this.expiresAt==null?!1:Date.now()>=this.expiresAt-3e4}};var tt="0.1.27",Me=!1;function ot(){return crypto.randomUUID()}function it(o,e){return{placeholder:o.placeholder,type:o.type,...e&&{text:o.text},kind:o.kind}}function Be(o){return o?.type==="accessToken"}function nt(o){if(!(!o||Be(o)))return o}var He=new WeakMap;function rt(o){let e=He.get(o.getAccessToken);return e||(e=new ae(o),He.set(o.getAccessToken,e)),e}function st(o,e,t){let i=e.find(n=>n.type==="contact"&&n.metadata?.contact_account_count)?.metadata?.contact_account_count,r=typeof i=="number"?i:void 0;return{data:{raw_query:o,completed_params:e.map(n=>it(n,t)),...r!=null&&{contact_account_count:r}},meta:{request_id:ot(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:tt}}}function at(o){return{"Content-Type":"application/json",...o?.appIdentifier&&{"X-App-Identifier":o.appIdentifier},...o?.headers}}async function ze(o,e,t,i,r){return fetch(o,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:r})}async function Fe(o,e,t){let i=t?.apiConfig,r=!t?.maskCompletedText,n=st(o,e,r),a=at(i),p=i?.endpoint??"/ac/suggest",s=JSON.stringify(n);if(Be(i)){let m=rt(i),h=await m.getToken(),g=await ze(p,a,h,s,t?.signal);if(g.status===401){let w=await m.getToken(!0);g=await ze(p,a,w,s,t?.signal)}if(!g.ok)throw new Error(`API error: ${g.status} ${g.statusText}`);return g.json()}let l=nt(i),d=l?.apiKey??"";if(!d&&!Me&&(Me=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),d){let m=l?.authScheme??"Bearer";a.Authorization=m==="Basic"?`Basic ${btoa(d)}`:`Bearer ${d}`}let c=await fetch(p,{method:"POST",headers:a,body:s,signal:t?.signal});if(!c.ok)throw new Error(`API error: ${c.status} ${c.statusText}`);return c.json()}function R(o,e){let t=o,i={},r=[];for(let n of e){let a=(i[n.type]??0)+1;i[n.type]=a;let s=`{{${n.type.toUpperCase().replace(/\s+/g,"_")}_${a}}}`,l=t.indexOf(n.text);l!==-1&&(t=t.slice(0,l)+s+t.slice(l+n.text.length)),r.push({...n,placeholder:s})}return{rawQuery:t,completedParams:r}}function Ne(o,e){return e?o.map(t=>{let i=e[t.type];if(!i)return t;let r=i("");if(r.length===0)return t;let n=new Set(r.map(p=>p.text)),a=(t.options??[]).filter(p=>!n.has(p.text));return{...t,options:[...r,...a]}}):o}var lt=100,dt=300,pt=2,le=class{constructor(e,t,i,r,n){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=r;this.getOnError=n;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null}start(){this.doFetch("",[]);let e=this.store.get().text,t=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(i=>{(i.text!==e||i.completedParams!==t)&&(e=i.text,t=i.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let i=new AbortController;this.abortController=i;let r=++this.fetchVersion,n=this.store.get(),a=n.text.length;n.suggestions.some(s=>s.type!=="placeholder")||this.store.set({isLoading:!0}),this.store.set({error:null});try{let s=await Fe(e,t,{maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig()});if(r!==this.fetchVersion)return;let l=Ne(s.data.suggestions??[],this.getOptionOverrides()),d=s.data.input??[],c=d[d.length-1],m=this.store.get().text,h,g;if(c?.state==="in_progress"){g=!0;let P=m.toLowerCase().lastIndexOf(c.text.toLowerCase());h=P!==-1?P:a}else g=!1,h=a;let b=l.filter(P=>P.type!=="placeholder")[0],v=null;if(b){let P=j(m,h,g),D=Pe(b.options,P);D&&(v={id:crypto.randomUUID(),placeholder:"",type:b.type,text:D.text,kind:D.kind,suggestionType:b.type,suggestionPlaceholder:b.text,options:b.options??[],metadata:D.metadata},l=l.filter(B=>B!==b))}this.store.set(P=>({suggestions:l,isLoading:!1,isReady:s.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:h,filterInProgress:g,...v?{completedParams:[...P.completedParams,v]}:{}}))}catch(s){if(r===this.fetchVersion){let l=s instanceof Error?s:new Error(String(s));this.store.set({error:l,isLoading:!1}),this.getOnError()?.(l)}}}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}let t=i=>{let r=this.store.get();if(!r.text&&r.completedParams.length===0)return this.doFetch("",[]),!0;let n=j(r.text,r.filterBase,r.filterInProgress),p=r.suggestions.filter(b=>b.type!=="placeholder")[0],l=(p?se(p.options,n):[]).filter(b=>b.is_tappable),d=p?Pe(p.options,n)!==null:!1,c=n.trim().length>0;if(l.length>0&&!d&&c)return!1;if(r.completedParams.length===0&&r.text.length>0){let b=r.suggestions.filter(v=>v.type==="placeholder").map(v=>v.text).join(" ");if(b.length>0&&b.toLowerCase().startsWith(r.text.toLowerCase()))return!1}let{rawQuery:m,completedParams:h}=R(r.text,r.completedParams),g=m.length<r.lastRawQuery.length,w=Math.abs(m.length-r.lastRawQuery.length);return g||w>=i?(this.doFetch(m,h),!0):!1};this.debounceTimer=setTimeout(()=>{t(pt)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},lt),this.slowDebounceTimer=setTimeout(()=>t(1),dt)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var de=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:r}=this.ctx,n=this.getEffectiveColumns(),a=r(),p=this.getTappableIndices(n);switch(e.key){case"ArrowDown":{let s=e.target;if(!(s.selectionStart!=null&&s.selectionStart===s.value.length)&&t.activeDropdownIndex<0)break;if(e.preventDefault(),!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:p[0]??0});break}if(p.length===0)return;let d=p.indexOf(t.activeDropdownIndex),c=d<p.length-1?d+1:0;this.store.set({activeDropdownIndex:p[c]});break}case"ArrowUp":{if(p.length===0||t.activeDropdownIndex<0)break;if(e.preventDefault(),t.activeDropdownIndex<n){this.store.set({activeDropdownIndex:-1});break}let s=p.indexOf(t.activeDropdownIndex),l=s>0?s-1:p.length-1;this.store.set({activeDropdownIndex:p[l]});break}case"ArrowRight":{if(t.activeDropdownIndex<0){let l=e.target;l.selectionStart!=null&&l.selectionStart===l.value.length&&t.actionableSuggestions.length>1&&(e.preventDefault(),this.pillsSetActivePill(1));break}if(t.activeDropdownIndex%n<n-1){let l=t.activeDropdownIndex+1;l<t.filteredOptions.length&&t.filteredOptions[l]?.is_tappable&&(e.preventDefault(),this.store.set({activeDropdownIndex:l}))}break}case"ArrowLeft":{if(t.activeDropdownIndex<0)break;if(t.activeDropdownIndex%n>0){let s=t.activeDropdownIndex-1;s>=0&&t.filteredOptions[s]?.is_tappable&&(e.preventDefault(),this.store.set({activeDropdownIndex:s}))}break}case"Enter":{if(e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable)this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i);else if(a){let{rawQuery:s,completedParams:l}=R(t.text,t.completedParams);a({query:t.text.trim(),raw_query:s,completed_params:l})}break}case"Tab":{let s=!t.text&&!!t.placeholderText,l=t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable;if(s&&!l){e.preventDefault();let d=t.suggestions.find(c=>c.type==="placeholder");d?this.store.set(c=>({text:t.placeholderText,filterBase:t.placeholderText.length,completedParams:[...c.completedParams,{id:crypto.randomUUID(),placeholder:"",type:d.type,text:t.placeholderText,kind:null,suggestionType:d.type,suggestionPlaceholder:d.text,options:d.options??[]}],suggestions:c.suggestions.filter(m=>m!==d)})):this.store.set({text:t.placeholderText,filterBase:t.placeholderText.length})}else if(l)e.preventDefault(),this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i);else if(t.isDropdownOpen){let d=t.filteredOptions.findIndex(c=>c.is_tappable);d>=0&&(e.preventDefault(),this.clickOrSelect(d,t.filteredOptions,i))}break}case"Escape":this.store.set({activeDropdownIndex:-1});break}}getTappableIndices(e){let i=this.store.get().filteredOptions.map((n,a)=>n.is_tappable?a:-1).filter(n=>n!==-1),r=Array.from({length:e},()=>[]);for(let n of i)r[n%e].push(n);return r.flat()}getEffectiveColumns(){let t=document.getElementById(`${this.ctx.listboxId}-option-0`)?.parentElement;if(!t)return this.ctx.columns;let i=getComputedStyle(t).gridTemplateColumns.split(" ").filter(Boolean).length;return i>0?i:this.ctx.columns}clickOrSelect(e,t,i){let r=document.getElementById(`${i}-option-${e}`);r?r.click():this.ctx.selectOption(t[e])}pillsSetActivePill(e){let t=this.store.get(),i=t.suggestions.filter(p=>p.type!=="placeholder");if(e<0||e>=i.length)return;let r=i[e],n=i.filter((p,s)=>s!==e),a=t.suggestions.filter(p=>p.type==="placeholder");this.store.set({suggestions:[...a,r,...n],pillTapped:!0,activeDropdownIndex:-1})}};var pe=class{constructor(e){this.store=e}setActivePill(e){let t=this.store.get(),i=t.suggestions.filter(p=>p.type!=="placeholder");if(e<0||e>=i.length)return;let r=i[e],n=i.filter((p,s)=>s!==e),a=t.suggestions.filter(p=>p.type==="placeholder");this.store.set({suggestions:[...a,r,...n],pillTapped:!0,activeDropdownIndex:-1})}removeLastParam(){let e=this.store.get();if(e.completedParams.length===0)return;let t=e.completedParams[e.completedParams.length-1],i={type:t.suggestionType,text:t.suggestionPlaceholder,required:!0,options:t.options};this.store.set(r=>({completedParams:r.completedParams.slice(0,-1),suggestions:[i,...r.suggestions],activeDropdownIndex:-1}))}};function ct(o){return o===0?.4:o===1?.3:.15}function ce(o,e,t,i,r=!1){let n=o.querySelector(".magicx-aia-pill-list");n||(n=document.createElement("span"),n.className="magicx-aia-pill-list",o.appendChild(n));let a=new Map;for(let s of n.querySelectorAll(".magicx-aia-pill"))a.set(s.dataset.pillKey??"",s);let p=new Set;for(let s=0;s<e.length;s++){let l=e[s],d=`${l.type}-${l.text}`;p.add(d);let c=a.get(d);c||(c=document.createElement("button"),c.type="button",c.dataset.pillKey=d,c.setAttribute("data-aia-pill",""),c.textContent=l.text),c.className=`magicx-aia-pill${r?" magicx-aia-pill--rounded":""}${s===t?" magicx-aia-pill--active":""}`,c.style.opacity=String(ct(s)),c.onclick=()=>i(s),n.children[s]!==c&&n.insertBefore(c,n.children[s]??null)}for(let[s,l]of a)p.has(s)||l.remove()}function ue(o){let e=document.createElement("div");return e.id=o,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",t=>t.preventDefault()),e}function me(o,e){let{filteredOptions:t,activeIndex:i,isOpen:r,pills:n,showPills:a,onSelect:p,onHighlight:s,onPillClick:l}=e,d=a&&n.length>0;r&&t.length>0||r&&d?o.classList.add("magicx-aia-dropdown--visible"):o.classList.remove("magicx-aia-dropdown--visible");let h=o.querySelector(".magicx-aia-pill-bar");d?(h||(h=document.createElement("div"),h.className="magicx-aia-pill-bar",h.setAttribute("data-aia-pillbar",""),o.insertBefore(h,o.firstChild)),ce(h,n,0,l,!0)):h&&h.remove();let g=o.querySelector(".magicx-aia-grid");t.length>0?(g||(g=document.createElement("div"),g.className="magicx-aia-grid",o.appendChild(g)),ut(g,t,i,p,s,e.listboxId)):g&&(g.innerHTML="")}function ut(o,e,t,i,r,n){let a=e.map(l=>l.text).join("\0"),p=o.dataset.optionsKey??"",s=a!==p;if(o.dataset.optionsKey=a,s){let l=document.createDocumentFragment();for(let d=0;d<e.length;d++){let c=e[d],m=mt(c,d,t,i,r,n);l.appendChild(m)}o.innerHTML="",o.appendChild(l)}else{let l=o.querySelectorAll(".magicx-aia-option");for(let d=0;d<l.length;d++){let c=l[d],m=d===t;c.setAttribute("aria-selected",String(m)),m?c.classList.add("magicx-aia-option--highlighted"):c.classList.remove("magicx-aia-option--highlighted")}}}function mt(o,e,t,i,r,n){let a=document.createElement("div");a.id=`${n}-option-${e}`,a.setAttribute("role","option"),a.setAttribute("data-aia-option",""),a.setAttribute("aria-selected",String(e===t)),a.tabIndex=o.is_tappable?0:-1;let p=["magicx-aia-option"];e===t&&p.push("magicx-aia-option--highlighted"),o.is_tappable?p.push("magicx-aia-option--tappable"):p.push("magicx-aia-option--non-tappable"),a.className=p.join(" ");let s=document.createElement("div");s.className="magicx-aia-streaks",a.appendChild(s);let l=document.createElement("div");l.className="magicx-aia-streaks-vert",a.appendChild(l);let d=document.createElement("span");if(d.className="magicx-aia-option-content",d.textContent=o.icon?`${o.icon} ${o.text}`:o.text,o.tag){let c=document.createElement("span");c.className="magicx-aia-option-tag",c.textContent=o.tag,d.appendChild(c)}return a.appendChild(d),o.is_tappable&&(a.addEventListener("click",()=>{a.classList.add("magicx-aia-option--pressed"),i(o),setTimeout(()=>a.classList.remove("magicx-aia-option--pressed"),400)}),a.addEventListener("mouseenter",()=>r(e))),a}function Ke(o,e){let t=ue(e.listboxId);return o.appendChild(t),{dropdown:t}}function Ae(o,e,t){me(o.dropdown,{suggestions:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,onSelect:t.selectOption,onHighlight:i=>t.store.set({activeDropdownIndex:i}),onPillClick:t.setActivePill})}function $e(o,e,t,i,r){let n=o.querySelector(".magicx-aia-sizer-text"),a=o.querySelector(".magicx-aia-placeholder");if(i&&r){n&&(n.style.display="none"),a||(a=document.createElement("span"),a.className="magicx-aia-placeholder",o.insertBefore(a,o.firstChild)),a.style.display="",a.textContent=`${r} `,o.dataset.segmentKey="";return}a&&(a.style.display="none"),n||(n=document.createElement("span"),n.className="magicx-aia-sizer-text",o.insertBefore(n,o.firstChild)),n.style.display="",n.className=`magicx-aia-sizer-text${t?" magicx-aia-sizer-text--visible":""}`;let p=e.map(d=>`${d.type}:${d.value}`).join("\0"),s=o.dataset.segmentKey??"",l=o.dataset.newParamId??"";if(!(p===s&&(t??"")===l)){o.dataset.segmentKey=p,o.dataset.newParamId=t??"",n.innerHTML="";for(let d of e){let c=document.createElement("span");d.type==="completed"&&(d.param.id===t?c.className="magicx-aia-shimmer-revealed magicx-aia-shimmer-sweep":c.className="magicx-aia-segment magicx-aia-segment--completed"),c.textContent=d.value,n.appendChild(c)}e.length===0&&(n.textContent="\xA0")}}var gt='<svg width="18" height="18" viewBox="0 0 18 18" fill="none" role="img" aria-label="Submit"><path d="M9 14V4M9 4L4 9M9 4L14 9" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';function qe(o,e){let{listboxId:t}=e,i=ue(t);o.appendChild(i);let r=document.createElement("div");r.className="magicx-aia-input-wrapper",o.appendChild(r);let n=document.createElement("div");n.className="magicx-aia-editor",n.setAttribute("data-aia-editor",""),r.appendChild(n);let a=document.createElement("div");a.className="magicx-aia-sizer",a.setAttribute("aria-hidden","true"),n.appendChild(a);let p=document.createElement("span");a.appendChild(document.createTextNode(" ")),a.appendChild(p);let s=document.createElement("textarea");s.className="magicx-aia-textarea",s.rows=1,s.setAttribute("role","combobox"),s.setAttribute("aria-autocomplete","list"),s.setAttribute("aria-controls",t),s.setAttribute("data-aia-textarea",""),n.appendChild(s);let l=document.createElement("button");return l.type="button",l.className="magicx-aia-submit",l.setAttribute("aria-label","Submit"),l.setAttribute("data-aia-submit",""),l.innerHTML=gt,r.appendChild(l),r.addEventListener("click",()=>s.focus()),s.addEventListener("input",()=>{let d=s.value,m=d.length>0&&d[0]!==d[0].toUpperCase()?d[0].toUpperCase()+d.slice(1):d;e.handleChange(m)}),s.addEventListener("keydown",d=>e.handleKeyDown(d)),s.addEventListener("focus",()=>e.store.set({isFocused:!0})),s.addEventListener("blur",()=>e.store.set({isFocused:!1})),l.addEventListener("click",d=>{d.stopPropagation();let c=e.store.get();if(!(!!c.text||c.completedParams.length>0)||!e.onSubmit)return;let{rawQuery:h,completedParams:g}=R(c.text,c.completedParams);e.onSubmit({query:c.text.trim(),raw_query:h,completed_params:g})}),e.autoFocus!==!1&&s.focus(),{textarea:s,dropdown:i,sizer:a,submitButton:l,inlinePillContainer:p}}function ke(o,e,t){let{textarea:i,dropdown:r,sizer:n,submitButton:a,inlinePillContainer:p}=o,{pillPlacement:s,setActivePill:l,selectOption:d,store:c}=t;i.value!==e.text&&(i.value=e.text),e.placeholderText?i.placeholder=e.placeholderText:i.removeAttribute("placeholder"),i.setAttribute("aria-expanded",String(e.isDropdownOpen));let m=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";m?i.setAttribute("aria-activedescendant",m):i.removeAttribute("aria-activedescendant"),e.newParamId?i.classList.add("magicx-aia-textarea--hidden"):i.classList.remove("magicx-aia-textarea--hidden");let h=!!e.text||e.completedParams.length>0;a.disabled=!h,$e(n,e.segments,e.newParamId,!e.text,e.placeholderText),s==="inline"?ce(p,e.actionableSuggestions,0,l):p.innerHTML="",me(r,{suggestions:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:s==="dropdown",onSelect:d,onHighlight:g=>c.set({activeDropdownIndex:g}),onPillClick:l})}function Ve(o){let e=o,t=new Set;return{get:()=>e,set:i=>{let r=typeof i=="function"?i(e):i,n={...e,...r},a=e;e=n;for(let p of t)p(n,a)},subscribe:i=>(t.add(i),()=>{t.delete(i)})}}var Te=!1;function Ue(){if(Te||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){Te=!0;return}Te=!0;let o=document.createElement("style");o.setAttribute("data-magicx-aia",""),o.textContent=ft,document.head.appendChild(o)}var ft="";var ht=0;function xt(){return`:ac-${++ht}:`}function Qe(){return{text:"",completedParams:[],suggestions:[],activeDropdownIndex:-1,newParamId:null,isLoading:!1,isReady:!1,error:null,segments:[],actionableSuggestions:[],filteredOptions:[],placeholderText:"",isDropdownOpen:!1,filterBase:0,filterInProgress:!1,pillTapped:!1,skipNextFetch:!1,lastRawQuery:"",isFocused:!1}}var ge=class{constructor(e,t={}){this.store=Ve(Qe());this._listboxId=xt();this.modeController=null;this.unsubscribers=[];this.derivedInProgress=!1;this.domRefs=null;this.dropdownRefs=null;this.externalListeners=new Set;this.container=e,this.opts=t,this.renderMode=t.renderMode??"full",t.value!==void 0&&this.store.set({text:t.value}),t.completedParams!==void 0&&this.store.set({completedParams:t.completedParams}),this.pillsController=new pe(this.store),this.fetchController=new le(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.opts.onError),this.keyboardController=new de(this.store,{columns:t.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.opts.onSubmit,selectOption:i=>this.selectOption(i)}),this.unsubscribers.push(this.store.subscribe((i,r)=>{this.recomputeDerived(i,r)})),this.unsubscribers.push(this.store.subscribe((i,r)=>{i.text!==r.text&&this.opts.onChange?.(i.text),i.completedParams!==r.completedParams&&this.opts.onParamsChange?.(i.completedParams),i.isFocused!==r.isFocused&&(i.isFocused?this.opts.onFocus?.():this.opts.onBlur?.()),this.opts.onStateChange?.(i)})),this.renderMode!=="headless"&&(Ue(),this.setupContainer()),this.renderMode==="full"?this.buildAndRenderFull():this.renderMode==="dropdown"&&this.buildAndRenderDropdown(),this.fetchController.start()}focus(){this.domRefs?.textarea.focus()}blur(){this.domRefs?.textarea.blur()}reset(){this.store.set({...Qe()}),this.fetchController.doFetch("",[])}destroy(){this.fetchController.dispose(),this.modeController?.destroy(),this.newParamTimer&&clearTimeout(this.newParamTimer),this.suggestionRemovalTimer&&clearTimeout(this.suggestionRemovalTimer),this.externalListeners.clear();for(let e of this.unsubscribers)e();this.unsubscribers=[],this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}setValue(e){this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e)}removeLastParam(){this.pillsController.removeLastParam()}clearNewParamId(){this.store.set({newParamId:null})}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}handleTextChange(e){this.handleChange(e)}handleKeyDown(e){this.keyboardController.handleKeyDown(e)}setFocused(e){this.store.get().isFocused!==e&&this.store.set({isFocused:e})}subscribe(e){return this.externalListeners.add(e),()=>{this.externalListeners.delete(e)}}getState(){return this.store.get()}get listboxId(){return this._listboxId}get isReady(){return this.store.get().isReady}on(e,t){switch(e){case"submit":return this.opts.onSubmit=t,()=>{this.opts.onSubmit=void 0};case"error":return this.opts.onError=t,()=>{this.opts.onError=void 0};case"change":return this.opts.onChange=t,()=>{this.opts.onChange=void 0};case"paramsChange":return this.opts.onParamsChange=t,()=>{this.opts.onParamsChange=void 0};case"stateChange":return this.opts.onStateChange=t,()=>{this.opts.onStateChange=void 0};case"focus":return this.opts.onFocus=t,()=>{this.opts.onFocus=void 0};case"blur":return this.opts.onBlur=t,()=>{this.opts.onBlur=void 0};default:return()=>{}}}update(e){Object.assign(this.opts,e),e.mode!==void 0&&this.modeController?.setMode(e.mode),e.optionsPosition!==void 0&&(this.container.dataset.optionsPosition=e.optionsPosition),e.animations!==void 0&&(this.container.dataset.animations=e.animations?"on":"off"),e.pillPlacement!==void 0&&(this.container.dataset.pillPlacement=e.pillPlacement,this.store.set({})),(e.dropdownTrigger!==void 0||e.closeDropdownOnBlur!==void 0)&&this.store.set({}),e.value!==void 0&&this.store.set({text:e.value}),e.completedParams!==void 0&&this.store.set({completedParams:e.completedParams})}selectOption(e){let t=this.store.get(),i=t.actionableSuggestions[0];if(!i)return;let r=t.filterBase,n=t.text.slice(0,r),a=n.length===0&&t.text.length===0,p=n.length===0&&t.text.length>0&&t.placeholderText.length>0&&t.placeholderText.toLowerCase().startsWith(t.text.toLowerCase());(a||p)&&t.placeholderText&&(n=`${t.placeholderText} `);let s=Ee(n,e.text);s>0&&(n=n.slice(0,n.length-s));let l=n.length>0&&n[n.length-1]!==" ",d=`${n}${l?" ":""}${e.text} `,c=(a||p)&&d.length>0?d[0].toUpperCase()+d.slice(1):d,m=c.toLowerCase().lastIndexOf(e.text.toLowerCase()),h=m>=0?c.slice(m,m+e.text.length):e.text,g={id:crypto.randomUUID(),placeholder:"",type:i.type,text:h,kind:e.kind,suggestionType:i.type,suggestionPlaceholder:i.text,options:i.options??[],metadata:e.metadata},w=t.actionableSuggestions.length-1;this.store.set(b=>({text:c,filterBase:c.length,completedParams:[...b.completedParams,g],newParamId:g.id,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:w>0})),this.suggestionRemovalTimer=window.setTimeout(()=>{this.store.set(b=>({suggestions:b.suggestions.filter(v=>v!==i)}))},400)}recomputeDerived(e,t){if(this.derivedInProgress)return;this.derivedInProgress=!0;let i=Le(e.text,e.completedParams),r=e.suggestions.filter(v=>v.type!=="placeholder"),n=r[0],a=n?this.opts.optionOverrides?.[n.type]:void 0,p=Math.min(e.filterBase,e.text.length),l=e.lastRawQuery!==""||p>0?j(e.text,p,e.filterInProgress):"",d=n?a?a(l.trim()):n.options??[]:[],c=se(d,l),m=e.suggestions.filter(v=>v.type==="placeholder").map(v=>v.text).join(" "),h=this.opts.dropdownTrigger??"auto",g=this.opts.closeDropdownOnBlur??!0,w=!1;if(h==="auto"){let v=g?e.isFocused:!0;w=!e.isLoading&&c.length>0&&v}else h==="manual"&&(w=!e.isLoading&&c.length>0&&e.pillTapped);this.store.set({segments:i,actionableSuggestions:r,filteredOptions:c,placeholderText:m,isDropdownOpen:w}),this.derivedInProgress=!1;let b=this.store.get();for(let v of this.externalListeners)v(b)}setupContainer(){this.container.classList.add("magicx-aia"),this.container.dataset.pillPlacement=this.renderMode==="dropdown"?"dropdown":this.opts.pillPlacement??"inline",this.container.dataset.optionsPosition=this.opts.optionsPosition??"below",this.container.dataset.animations=this.opts.animations??!0?"on":"off",this.modeController=new q(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},autoFocus:this.opts.autoFocus??!0,selectOption:i=>this.selectOption(i),setActivePill:i=>this.pillsController.setActivePill(i),handleKeyDown:i=>this.keyboardController.handleKeyDown(i),handleChange:i=>this.handleChange(i)};this.domRefs=qe(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&ke(this.domRefs,this.store.get(),t)}),ke(this.domRefs,this.store.get(),t),this.subscribeNewParamTimer()}buildAndRenderDropdown(){let e={store:this.store,listboxId:this.listboxId,selectOption:t=>this.selectOption(t),setActivePill:t=>this.pillsController.setActivePill(t)};this.dropdownRefs=Ke(this.container,e),this.subscribeBatchedRender(()=>{this.dropdownRefs&&Ae(this.dropdownRefs,this.store.get(),e)}),Ae(this.dropdownRefs,this.store.get(),e),this.subscribeNewParamTimer()}subscribeBatchedRender(e){let t=!1;this.unsubscribers.push(this.store.subscribe(()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,t)=>{e.newParamId&&e.newParamId!==t.newParamId&&(this.newParamTimer&&clearTimeout(this.newParamTimer),this.newParamTimer=window.setTimeout(()=>{this.store.set({newParamId:null})},650))}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:r}=Re(e,t.completedParams);r.length>0&&this.store.set(n=>({completedParams:i,suggestions:[...r.map(a=>({type:a.suggestionType,text:a.suggestionPlaceholder,required:!0,options:a.options})),...n.suggestions]}))}};function fe({onSubmit:o,onError:e,optionOverrides:t,maskCompletedText:i,apiConfig:r,columns:n=2,dropdownTrigger:a,closeDropdownOnBlur:p,onFocus:s,onBlur:l,value:d,completedParams:c,onChange:m,onParamsChange:h}){let g=(0,x.useRef)(null),[w,b]=(0,x.useState)(null),v=(0,x.useRef)(o);v.current=o;let P=(0,x.useRef)(e);P.current=e;let D=(0,x.useRef)(m);D.current=m;let B=(0,x.useRef)(h);B.current=h;let G=(0,x.useRef)(s);G.current=s;let V=(0,x.useRef)(l);V.current=l,(0,x.useEffect)(()=>{if(typeof document>"u")return;let u=new ge(document.createElement("div"),{renderMode:"headless",apiConfig:r,optionOverrides:t,maskCompletedText:i,columns:n,dropdownTrigger:a,closeDropdownOnBlur:p,value:d,completedParams:c,onSubmit:(...A)=>v.current?.(...A),onError:(...A)=>P.current?.(...A),onChange:(...A)=>D.current?.(...A),onParamsChange:(...A)=>B.current?.(...A),onFocus:()=>G.current?.(),onBlur:()=>V.current?.()});g.current=u,b(u.getState());let S=u.subscribe(A=>b(A));return()=>{S(),u.destroy(),g.current===u&&(g.current=null)}},[]);let f=g.current,C=(0,x.useCallback)(()=>{},[]);(0,x.useEffect)(()=>{d!==void 0&&f?.setValue(d)},[d,f]),(0,x.useEffect)(()=>{c!==void 0&&f?.setCompletedParams(c)},[c,f]);let E=JSON.stringify(r??null),M=(0,x.useRef)(t),X=(0,x.useRef)(0);if(t!==M.current){let u=M.current,S=t,A=Object.keys(u??{}),N=Object.keys(S??{});(A.length!==N.length||N.some(Se=>!u?.[Se]||S[Se]!==u[Se]))&&X.current++,M.current=t}(0,x.useEffect)(()=>{f?.update({apiConfig:r,optionOverrides:t,dropdownTrigger:a,closeDropdownOnBlur:p})},[E,X.current,a,p,f]);let he=(0,x.useCallback)(u=>{if(!f)return;let S=u.target.value,N=S.length>0&&!u.nativeEvent?.isComposing&&S[0]!==S[0].toUpperCase()?S[0].toUpperCase()+S.slice(1):S;f.handleTextChange(N)},[f]),J=(0,x.useCallback)(u=>{f?.handleKeyDown(u.nativeEvent)},[f]),H=(0,x.useCallback)(()=>f?.setFocused(!0),[f]),Y=(0,x.useCallback)(()=>f?.setFocused(!1),[f]),T=(0,x.useCallback)(u=>f?.setActivePill(u),[f]),xe=(0,x.useCallback)(()=>f?.removeLastParam(),[f]),F=(0,x.useCallback)(()=>f?.clearNewParamId(),[f]),Z=(0,x.useCallback)(()=>f?.reset(),[f]),be=(0,x.useCallback)(u=>f?.selectOption(u),[f]),U=(0,x.useCallback)(u=>f?.setActiveDropdownIndex(u),[f]);if(!f)return{completedParams:c??[],suggestionPills:[],setActivePill:C,removeLastParam:C,segments:[],newParamId:null,clearNewParamId:C,suggestions:[],activeIndex:-1,isReady:!1,isLoading:!0,error:null,inputProps:{value:d??"",placeholder:void 0,onChange:C,onKeyDown:C,onFocus:C,onBlur:C,role:"combobox","aria-expanded":!1,"aria-activedescendant":void 0,"aria-autocomplete":"list","aria-controls":""},reset:C,dropdownProps:{suggestions:[],activeIndex:-1,onSelect:C,onHighlight:C,isOpen:!1,id:"",pills:[],onPillClick:C}};let y=w??f.getState(),ve=d!==void 0?d:y.text,ee=c!==void 0?c:y.completedParams,Q=y.actionableSuggestions,te=Q[0],ye=y.filteredOptions,we=y.activeDropdownIndex>=0?`${f.listboxId}-option-${y.activeDropdownIndex}`:void 0;return{completedParams:ee,suggestionPills:Q,setActivePill:T,removeLastParam:xe,segments:y.segments,newParamId:y.newParamId,clearNewParamId:F,suggestions:y.suggestions,activeIndex:y.activeDropdownIndex,isReady:y.isReady,isLoading:y.isLoading,error:y.error,inputProps:{value:ve,placeholder:y.placeholderText||void 0,onChange:he,onKeyDown:J,onFocus:H,onBlur:Y,role:"combobox","aria-expanded":y.isDropdownOpen,"aria-activedescendant":we,"aria-autocomplete":"list","aria-controls":f.listboxId},reset:Z,dropdownProps:{suggestions:te?[{...te,options:ye}]:[],activeIndex:y.activeDropdownIndex,onSelect:be,onHighlight:U,isOpen:y.isDropdownOpen,id:f.listboxId,pills:Q,onPillClick:T}}}var I=require("react/jsx-runtime");function bt(o){return o!=="auto"?o:typeof window>"u"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}var We=(0,_.forwardRef)(function({onSubmit:e,onError:t,optionOverrides:i,maskCompletedText:r,className:n,apiConfig:a,columns:p,pillPlacement:s="inline",mode:l="auto",optionsPosition:d="below",animations:c=!0,dropdownTrigger:m,closeDropdownOnBlur:h,autoFocus:g=!0,onFocus:w,onBlur:b,value:v,completedParams:P,onChange:D,onParamsChange:B},G){let V=(0,_.useRef)(null),f=(0,_.useRef)(null),C=(0,_.useRef)(()=>{}),E=(0,_.useRef)(null);(0,_.useEffect)(()=>{let u=V.current;if(u)return E.current?E.current.setMode(l):E.current=new q(u,l),()=>{E.current?.destroy(),E.current=null}},[l]);let{completedParams:M,suggestionPills:X,setActivePill:he,segments:J,newParamId:H,clearNewParamId:Y,inputProps:T,dropdownProps:xe,reset:F}=fe({onSubmit:u=>C.current(u),onError:t,optionOverrides:i,maskCompletedText:r,apiConfig:a,columns:p,dropdownTrigger:m,closeDropdownOnBlur:h,onFocus:w,onBlur:b,value:v,completedParams:P,onChange:D,onParamsChange:B}),Z=T.onFocus;(0,_.useEffect)(()=>{if(!g)return;let u=f.current;u&&(document.activeElement===u?Z():u.focus())},[Z,g]),(0,_.useEffect)(()=>{if(!H)return;let u=window.setTimeout(()=>Y(),650);return()=>window.clearTimeout(u)},[H,Y]),(0,_.useImperativeHandle)(G,()=>({focus:()=>f.current?.focus(),blur:()=>f.current?.blur(),reset:F,setMode:u=>E.current?.setMode(u)}),[F]);let be=()=>{f.current?.focus()},U=!!T.value||M.length>0,y=(0,_.useCallback)(()=>{if(!U)return;let{rawQuery:u,completedParams:S}=R(T.value,M);e({query:T.value.trim(),raw_query:u,completed_params:S}),F()},[U,T.value,M,e,F]);C.current=y;let{onChange:ve,placeholder:ee,...Q}=T,te=!T.value,ye=s==="inline",we=s==="dropdown";return(0,I.jsxs)("div",{ref:V,className:`magicx-aia ${k.container} ${n??""}`,"data-pill-placement":s,"data-options-position":d,"data-animations":c?"on":"off","data-mode":bt(l),children:[(0,I.jsx)(re,{...xe,showPills:we}),(0,I.jsxs)("div",{className:k.inputWrapper,onClick:be,children:[(0,I.jsxs)("div",{className:k.editorArea,"data-aia-editor":"",children:[(0,I.jsxs)("div",{className:k.sizerContent,"aria-hidden":"true",children:[te&&ee?(0,I.jsxs)("span",{className:k.placeholderText,children:[ee," "]}):(0,I.jsxs)("span",{className:`${k.sizerText} ${H?k.sizerTextVisible:""}`,children:[J.map((u,S)=>{if(u.type==="completed"&&u.param.id===H){let N=`${k.shimmerRevealed} ${k.shimmerSweep}`;return(0,I.jsx)("span",{className:N,children:u.value},`${S}-${u.type}`)}return(0,I.jsx)("span",{children:u.value},`${S}-${u.type}`)}),J.length===0&&"\xA0"]})," ",ye&&(0,I.jsx)(ie,{pills:X,activePillIndex:0,onSelectPill:he})]}),(0,I.jsx)("textarea",{ref:f,"data-aia-textarea":"",className:`${k.textarea} ${H?k.textareaHidden:""}`,rows:1,onChange:ve,...Q})]}),(0,I.jsx)("button",{type:"button","data-aia-submit":"",className:k.submitButton,disabled:!U,onClick:u=>{u.stopPropagation(),y()},"aria-label":"Submit",children:(0,I.jsx)("svg",{width:"18",height:"18",viewBox:"0 0 18 18",fill:"none",role:"img","aria-label":"Submit",children:(0,I.jsx)("path",{d:"M9 14V4M9 4L4 9M9 4L14 9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})});0&&(module.exports={AIAutocomplete,AIAutocompleteDropdown,useAIAutocomplete});
|
|
687
687
|
//# sourceMappingURL=index.js.map
|