@magicx-eng/ai-autocomplete-react 0.1.42 → 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.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import{forwardRef as qn,useCallback as dt,useEffect as Xt,useImperativeHandle as Gn,useLayoutEffect as Qn,useRef as ve}from"react";if(typeof document<"u"&&!document.getElementById("ac-style-cc65f4cc")){let n=document.createElement("style");n.id="ac-style-cc65f4cc",n.textContent=`.AIAutocomplete-module_container_KKjFU {
1
+ import{forwardRef as mt,useCallback as Pe,useEffect as Ne,useImperativeHandle as gt,useLayoutEffect as ft,useRef as le}from"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
@@ -58,7 +58,11 @@ import{forwardRef as qn,useCallback as dt,useEffect as Xt,useImperativeHandle as
58
58
  CSS Modules' class-name hashing. */
59
59
  :where(.AIAutocomplete-module_input_IW-P-) strong[class~="magicx-aia-segment--editing"] {
60
60
  background-color: color-mix(in srgb, var(--aia-edit-outline, currentColor) 20%, transparent);
61
- border-radius: 4px;
61
+ border-radius: 6px;
62
+ padding: 2px 3px;
63
+ /* Pull surrounding inline text back so the wider/taller fill doesn't shove
64
+ the rest of the line \u2014 only the visible background grows. */
65
+ margin: 0 -1.5px;
62
66
  caret-color: transparent;
63
67
  }
64
68
 
@@ -162,7 +166,7 @@ import{forwardRef as qn,useCallback as dt,useEffect as Xt,useImperativeHandle as
162
166
  background-position: -50% 0;
163
167
  }
164
168
  }
165
- `,document.head.appendChild(n)}var J={container:"AIAutocomplete-module_container_KKjFU",inputWrapper:"AIAutocomplete-module_inputWrapper_FLq1b",editorArea:"AIAutocomplete-module_editorArea_7rBWq",input:"AIAutocomplete-module_input_IW-P-",pillListContainer:"AIAutocomplete-module_pillListContainer_h92IA",submitButton:"AIAutocomplete-module_submitButton_sl1Mi",submitSlot:"AIAutocomplete-module_submitSlot_GhuCM",textShimmer:"AIAutocomplete-module_textShimmer_eCLdq"};if(typeof document<"u"&&!document.getElementById("ac-style-2eef895d")){let n=document.createElement("style");n.id="ac-style-2eef895d",n.textContent=`.AIAutocompleteDropdown-module_dropdown_yz2KC {
169
+ `,document.head.appendChild(e)}var U={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 {
166
170
  position: absolute;
167
171
  left: 0;
168
172
  right: 0;
@@ -244,7 +248,7 @@ import{forwardRef as qn,useCallback as dt,useEffect as Xt,useImperativeHandle as
244
248
  opacity: 0.25;
245
249
  }
246
250
  }
247
- `,document.head.appendChild(n)}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-b745b4fb")){let n=document.createElement("style");n.id="ac-style-b745b4fb",n.textContent=`.PillList-module_list_qvLqO {
251
+ `,document.head.appendChild(e)}var Z={dropdown:"AIAutocompleteDropdown-module_dropdown_yz2KC",visible:"AIAutocompleteDropdown-module_visible_QCoXj",pillBar:"AIAutocompleteDropdown-module_pillBar_pwTXe",skeletonBars:"AIAutocompleteDropdown-module_skeletonBars_HVr9C",skeletonBar:"AIAutocompleteDropdown-module_skeletonBar_O3xIx",aiaSkeletonPulse:"AIAutocompleteDropdown-module_aiaSkeletonPulse_G8W7q"};if(typeof document<"u"&&!document.getElementById("ac-style-0fcb7940")){let e=document.createElement("style");e.id="ac-style-0fcb7940",e.textContent=`.PillList-module_list_qvLqO {
248
252
  position: relative;
249
253
  z-index: 1;
250
254
  pointer-events: auto;
@@ -327,7 +331,7 @@ import{forwardRef as qn,useCallback as dt,useEffect as Xt,useImperativeHandle as
327
331
  opacity: 0;
328
332
  }
329
333
  }
330
- `,document.head.appendChild(n)}var $={list:"PillList-module_list_qvLqO",pill:"PillList-module_pill_osSyz",fadeIn:"PillList-module_fadeIn_Aezob",rounded:"PillList-module_rounded_WvXy4",skeleton:"PillList-module_skeleton_Lp8x6",skeletonPulse:"PillList-module_skeletonPulse_xZ8Yf",active:"PillList-module_active_Oll--"};import{jsx as Ce}from"react/jsx-runtime";var an=[125,69];function ft(n){return n===0?.4:n===1?.3:.15}function be({pills:n,activePillIndex:e,onSelectPill:t,rounded:o,loading:i}){return i&&n.length===0?Ce("span",{className:$.list,"data-aia-pill-list-loading":"",children:an.map((a,r)=>Ce("span",{"data-aia-pill-skeleton":"",className:`${$.pill} ${o?$.rounded:""} ${$.skeleton}`,style:{width:a,opacity:ft(r)}},`skel-${a}`))}):Ce("span",{className:$.list,"data-aia-pill-list-loading":i?"":void 0,children:n.map((a,r)=>Ce("button",{type:"button","data-aia-pill":"","data-aia-loading":i?"":void 0,tabIndex:-1,contentEditable:!1,suppressContentEditableWarning:!0,className:`${$.pill} ${o?$.rounded:""} ${r===e&&!i?$.active:""} ${i?$.skeleton:""}`,style:{opacity:ft(r)},onMouseDown:s=>s.preventDefault(),onClick:i?void 0:()=>t(r),disabled:i,children:a.text},`${a.type}-${a.text}`))})}import{useEffect as cn,useLayoutEffect as pn,useRef as un,useState as mn}from"react";if(typeof document<"u"&&!document.getElementById("ac-style-d91f2b06")){let n=document.createElement("style");n.id="ac-style-d91f2b06",n.textContent=`.SuggestionGrid-module_scrollWrapper_MOqfw {
334
+ `,document.head.appendChild(e)}var M={list:"PillList-module_list_qvLqO",pill:"PillList-module_pill_osSyz",fadeIn:"PillList-module_fadeIn_Aezob",rounded:"PillList-module_rounded_WvXy4",skeleton:"PillList-module_skeleton_Lp8x6",skeletonPulse:"PillList-module_skeletonPulse_xZ8Yf",active:"PillList-module_active_Oll--"};import{jsx as ge}from"react/jsx-runtime";var Je=[125,69];function Te(e){return e===0?.4:e===1?.3:.15}function se({pills:e,activePillIndex:y,onSelectPill:b,rounded:v,loading:p}){return p&&e.length===0?ge("span",{className:M.list,"data-aia-pill-list-loading":"",children:Je.map((l,u)=>ge("span",{"data-aia-pill-skeleton":"",className:`${M.pill} ${v?M.rounded:""} ${M.skeleton}`,style:{width:l,opacity:Te(u)}},`skel-${l}`))}):ge("span",{className:M.list,"data-aia-pill-list-loading":p?"":void 0,children:e.map((l,u)=>ge("button",{type:"button","data-aia-pill":"","data-aia-loading":p?"":void 0,tabIndex:-1,contentEditable:!1,suppressContentEditableWarning:!0,className:`${M.pill} ${v?M.rounded:""} ${u===y&&!p?M.active:""} ${p?M.skeleton:""}`,style:{opacity:Te(u)},onMouseDown:c=>c.preventDefault(),onClick:p?void 0:()=>b(u),disabled:p,children:l.text},`${l.type}-${l.text}`))})}import{useEffect as tt,useLayoutEffect as ot,useRef as at,useState as nt}from"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 {
331
335
  position: relative;
332
336
  }
333
337
 
@@ -382,7 +386,7 @@ import{forwardRef as qn,useCallback as dt,useEffect as Xt,useImperativeHandle as
382
386
  background: var(--aia-scrollbar-thumb, rgba(0, 0, 0, 0.3));
383
387
  border-radius: 3px;
384
388
  }
385
- `,document.head.appendChild(n)}var Ye={scrollWrapper:"SuggestionGrid-module_scrollWrapper_MOqfw",grid:"SuggestionGrid-module_grid_jvaPb"};import{useEffect as sn,useRef as ln,useState as dn}from"react";if(typeof document<"u"&&!document.getElementById("ac-style-f6bdc634")){let n=document.createElement("style");n.id="ac-style-f6bdc634",n.textContent=`.SuggestionItem-module_item_d4vpD {
389
+ `,document.head.appendChild(e)}var _e={scrollWrapper:"SuggestionGrid-module_scrollWrapper_MOqfw",grid:"SuggestionGrid-module_grid_jvaPb"};import{useEffect as Ye,useRef as Ze,useState as et}from"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 {
386
390
  position: relative;
387
391
  overflow: visible;
388
392
  display: flex;
@@ -391,11 +395,11 @@ import{forwardRef as qn,useCallback as dt,useEffect as Xt,useImperativeHandle as
391
395
  align-items: flex-start;
392
396
  font-family: inherit;
393
397
  font-size: var(--aia-option-font-size, 19px);
398
+ font-weight: 250;
394
399
  line-height: 24px;
395
400
  color: var(--aia-option-color, var(--aia-color-text-muted, #c1c4cb));
396
401
  white-space: normal;
397
402
  word-break: break-word;
398
- opacity: 0.4;
399
403
  border-radius: 12px;
400
404
  padding: 13px 13px;
401
405
  animation: SuggestionItem-module_fadeIn_I8u35 500ms cubic-bezier(0.4, 0, 0.2, 1) forwards;
@@ -422,13 +426,11 @@ import{forwardRef as qn,useCallback as dt,useEffect as Xt,useImperativeHandle as
422
426
 
423
427
  .SuggestionItem-module_nonTappable_xSZM- {
424
428
  cursor: default;
425
- opacity: 0.3;
426
429
  }
427
430
 
428
431
  .SuggestionItem-module_highlighted_Hb0SU {
429
432
  color: var(--aia-option-color-selected, var(--aia-color-text-default, #fff));
430
433
  background: var(--aia-option-bg, transparent);
431
- opacity: 0.5;
432
434
  }
433
435
 
434
436
  .SuggestionItem-module_tag_e3Fwe {
@@ -705,10 +707,17 @@ import{forwardRef as qn,useCallback as dt,useEffect as Xt,useImperativeHandle as
705
707
  animation: SuggestionItem-module_skeletonPulse_plvdD 1.4s ease-in-out infinite;
706
708
  }
707
709
 
708
- .SuggestionItem-module_item_d4vpD[data-aia-loading] .SuggestionItem-module_content_T-Qba {
710
+ /* Skeleton fill is on the inner text span (a true inline element) so multi-
711
+ line options wrap into one skeleton bar per line. The outer .content is a
712
+ flex item \u2014 blockified by spec \u2014 so painting the background there would
713
+ collapse all lines into one tall rectangle. \`box-decoration-break: clone\`
714
+ makes the radius render cleanly on each line bar. */
715
+ .SuggestionItem-module_item_d4vpD[data-aia-loading] .SuggestionItem-module_text_yqoh9 {
709
716
  color: transparent;
710
717
  background: var(--aia-skeleton-bg, var(--aia-pill-bg, rgba(189, 189, 189, 0.51)));
711
718
  border-radius: 999px;
719
+ -webkit-box-decoration-break: clone;
720
+ box-decoration-break: clone;
712
721
  }
713
722
 
714
723
  .SuggestionItem-module_item_d4vpD[data-aia-loading] .SuggestionItem-module_tag_e3Fwe {
@@ -724,7 +733,7 @@ import{forwardRef as qn,useCallback as dt,useEffect as Xt,useImperativeHandle as
724
733
  filter: brightness(0.55);
725
734
  }
726
735
  }
727
- `,document.head.appendChild(n)}var U={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"};import{jsx as Ze,jsxs as ht}from"react/jsx-runtime";function bt({option:n,isHighlighted:e,onSelect:t,onHighlight:o,id:i,loading:a}){let[r,s]=dn(!1),l=ln(void 0);sn(()=>()=>clearTimeout(l.current),[]);let d=()=>{a||!n.is_tappable||r||(s(!0),t(n),clearTimeout(l.current),l.current=setTimeout(()=>s(!1),500))},u=[U.item,e&&!a?U.highlighted:"",n.is_tappable?U.tappable:U.nonTappable,r?U.pressed:""].filter(Boolean).join(" ");return ht("div",{id:i,role:"option","data-aia-option":"","data-aia-loading":a?"":void 0,"aria-selected":e,className:u,tabIndex:a||!n.is_tappable?-1:0,onClick:d,onKeyDown:p=>{!a&&n.is_tappable&&(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),d())},onMouseEnter:!a&&n.is_tappable?o:void 0,children:[Ze("div",{className:U.streaks}),Ze("div",{className:U.streaksVert}),ht("span",{className:U.content,children:[n.icon?`${n.icon} ${n.text}`:n.text,n.tag&&Ze("span",{className:U.tag,children:n.tag})]})]})}import{jsx as et}from"react/jsx-runtime";function xt({options:n,activeIndex:e,onSelect:t,onHighlight:o,listboxId:i,loading:a}){let r=un(null),[s,l]=mn(!1);return cn(()=>{let d=r.current;if(!d)return;let u=()=>{l(d.scrollHeight-d.scrollTop-d.clientHeight>1)};d.addEventListener("scroll",u,{passive:!0});let p=new ResizeObserver(u);return p.observe(d),()=>{d.removeEventListener("scroll",u),p.disconnect()}},[]),pn(()=>{let d=r.current;d&&l(d.scrollHeight-d.scrollTop-d.clientHeight>1)},[n]),et("div",{className:Ye.scrollWrapper,"data-fade":s?"":void 0,children:et("div",{ref:r,className:Ye.grid,children:n.map((d,u)=>et(bt,{option:d,isHighlighted:u===e,onSelect:t,onHighlight:()=>o(u),id:`${i}-option-${u}`,loading:a},d.text))})})}import{jsx as oe,jsxs as fn}from"react/jsx-runtime";var gn=[159,119,164];function tt({suggestions:n,activeIndex:e,onSelect:t,onHighlight:o,isOpen:i,id:a,className:r,pills:s,onPillClick:l,showPills:d=!0,isLoading:u=!1}){let m=n[0]?.options??[],v=d&&s&&s.length>0&&l,g=m.length>0,b=u&&!g,f=i&&(g||v||u);return fn("div",{id:a,role:"listbox","data-aia-dropdown":"","data-aia-loading":u?"":void 0,className:`${ne.dropdown} ${f?ne.visible:""} ${r??""}`,onMouseDown:c=>c.preventDefault(),children:[d&&s&&s.length>0&&l&&oe("div",{className:ne.pillBar,"data-aia-pillbar":"",children:oe(be,{pills:s,activePillIndex:0,onSelectPill:l,rounded:!0,loading:u})}),d&&(!s||s.length===0)&&u&&oe("div",{className:ne.pillBar,"data-aia-pillbar":"",children:oe(be,{pills:[],activePillIndex:0,onSelectPill:()=>{},rounded:!0,loading:!0})}),g&&oe(xt,{options:m,activeIndex:e,onSelect:t,onHighlight:o,listboxId:a,loading:u}),b&&oe("div",{className:ne.skeletonBars,"data-aia-skeleton-bars":"",children:gn.map(c=>oe("span",{className:ne.skeletonBar,style:{width:c}},`bar-${c}`))})]})}if(typeof document<"u"&&!document.getElementById("ac-style-dc8da745")){let n=document.createElement("style");n.id="ac-style-dc8da745",n.textContent=`/*
736
+ `,document.head.appendChild(e)}var D={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"};import{jsx as fe,jsxs as ze}from"react/jsx-runtime";function Me({option:e,isHighlighted:y,onSelect:b,onHighlight:v,id:p,loading:l}){let[u,c]=et(!1),x=Ze(void 0);Ye(()=>()=>clearTimeout(x.current),[]);let n=()=>{l||!e.is_tappable||u||(c(!0),b(e),clearTimeout(x.current),x.current=setTimeout(()=>c(!1),500))},m=[D.item,y&&!l?D.highlighted:"",e.is_tappable?D.tappable:D.nonTappable,u?D.pressed:""].filter(Boolean).join(" ");return ze("div",{id:p,role:"option","data-aia-option":"","data-aia-loading":l?"":void 0,"aria-selected":y,className:m,tabIndex:l||!e.is_tappable?-1:0,onClick:n,onKeyDown:w=>{!l&&e.is_tappable&&(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),n())},onMouseEnter:!l&&e.is_tappable?v:void 0,children:[fe("div",{className:D.streaks}),fe("div",{className:D.streaksVert}),ze("span",{className:D.content,children:[fe("span",{className:D.text,children:e.icon?`${e.icon} ${e.text}`:e.text}),e.tag&&fe("span",{className:D.tag,children:e.tag})]})]})}import{jsx as ye}from"react/jsx-runtime";function Oe({options:e,activeIndex:y,onSelect:b,onHighlight:v,listboxId:p,loading:l}){let u=at(null),[c,x]=nt(!1);return tt(()=>{let n=u.current;if(!n)return;let m=()=>{x(n.scrollHeight-n.scrollTop-n.clientHeight>1)};n.addEventListener("scroll",m,{passive:!0});let w=new ResizeObserver(m);return w.observe(n),()=>{n.removeEventListener("scroll",m),w.disconnect()}},[]),ot(()=>{let n=u.current;n&&x(n.scrollHeight-n.scrollTop-n.clientHeight>1)},[e]),ye("div",{className:_e.scrollWrapper,"data-fade":c?"":void 0,children:ye("div",{ref:u,className:_e.grid,children:e.map((n,m)=>ye(Me,{option:n,isHighlighted:m===y,onSelect:b,onHighlight:()=>v(m),id:`${p}-option-${m}`,loading:l},n.text))})})}import{jsx as ee,jsxs as it}from"react/jsx-runtime";var rt=[159,119,164];function Ie({suggestions:e,activeIndex:y,onSelect:b,onHighlight:v,isOpen:p,id:l,className:u,pills:c,onPillClick:x,showPills:n=!0,isLoading:m=!1}){let S=e[0]?.options??[],O=n&&c&&c.length>0&&x,E=S.length>0,N=m&&!E,B=p&&(E||O||m);return it("div",{id:l,role:"listbox","data-aia-dropdown":"","data-aia-loading":m?"":void 0,className:`${Z.dropdown} ${B?Z.visible:""} ${u??""}`,onMouseDown:a=>a.preventDefault(),children:[n&&c&&c.length>0&&x&&ee("div",{className:Z.pillBar,"data-aia-pillbar":"",children:ee(se,{pills:c,activePillIndex:0,onSelectPill:x,rounded:!0,loading:m})}),n&&(!c||c.length===0)&&m&&ee("div",{className:Z.pillBar,"data-aia-pillbar":"",children:ee(se,{pills:[],activePillIndex:0,onSelectPill:()=>{},rounded:!0,loading:!0})}),E&&ee(Oe,{options:S,activeIndex:y,onSelect:b,onHighlight:v,listboxId:l,loading:m}),N&&ee("div",{className:Z.skeletonBars,"data-aia-skeleton-bars":"",children:rt.map(a=>ee("span",{className:Z.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=`/*
728
737
  * Built-in appearance defaults \u2014 zero specificity via :where().
729
738
  * Consumer CSS always wins without !important.
730
739
  *
@@ -754,7 +763,7 @@ import{forwardRef as qn,useCallback as dt,useEffect as Xt,useImperativeHandle as
754
763
  --aia-pill-font-size: 19px;
755
764
 
756
765
  --aia-option-bg: transparent;
757
- --aia-option-color: #000000;
766
+ --aia-option-color: #4f4f4f;
758
767
  --aia-option-color-selected: #000000;
759
768
  --aia-option-font-size: 19px;
760
769
 
@@ -780,7 +789,7 @@ import{forwardRef as qn,useCallback as dt,useEffect as Xt,useImperativeHandle as
780
789
  --aia-pill-font-size: 19px;
781
790
 
782
791
  --aia-option-bg: transparent;
783
- --aia-option-color: #ffffff;
792
+ --aia-option-color: #b0b0b0;
784
793
  --aia-option-color-selected: #ffffff;
785
794
  --aia-option-font-size: 19px;
786
795
 
@@ -819,5 +828,5 @@ import{forwardRef as qn,useCallback as dt,useEffect as Xt,useImperativeHandle as
819
828
  animation-duration: 0s !important;
820
829
  transition-duration: 0s !important;
821
830
  }
822
- `,document.head.appendChild(n)}var yt='[contenteditable="false"]',le;function hn(){if(le!==void 0)return le;let n=globalThis.Intl.Segmenter;if(!n)return le=null,null;try{le=new n(void 0,{granularity:"grapheme"})}catch{le=null}return le??null}function Ae(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(yt))return!0;t=t.parentNode}return!1}function Ee(n){return(n.ownerDocument??document).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return Ae(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function de(n){let e=Ee(n),t="",o=e.nextNode();for(;o;)t+=o.data,o=e.nextNode();return t}function Te(n){let e=Ee(n),t=0,o=e.nextNode();for(;o;)t+=o.data.length,o=e.nextNode();return t}function B(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(Ae(i,n)&&i!==n)return null;let a=0;for(let r=0;r<o&&r<i.childNodes.length;r++)a+=wt(i.childNodes[r],n);return a+vt(i,n)}return t.nodeType!==Node.TEXT_NODE||Ae(t,n)?null:vt(t,n)+o}function wt(n,e){if(n.nodeType===Node.TEXT_NODE)return Ae(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(yt))return 0;let o=0;for(let i of Array.from(t.childNodes))o+=wt(i,e);return o}function vt(n,e){let t=Ee(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 O(n,e){let t=n.ownerDocument??document,o=t.getSelection();if(!o)return;let i=Math.max(0,Math.min(e,Te(n))),a=Ee(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 St(n){let e=B(n);return e==null?!1:e>=Te(n)}function Pt(n,e){if(e<=0)return 0;let t=hn();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}import{useCallback as Vt,useEffect as Qe,useRef as K,useState as Wn}from"react";function R(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 ce(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function ie(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 It(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 re(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 pe(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 ue=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 Ct(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 At(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 _e=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 bn="https://api.ai-autocomplete.com",ke=`${bn}/api/suggest`,Et=new WeakMap;function xe(n){return n?.type==="accessToken"}function xn(n){if(!(!n||xe(n)))return n}function Oe(n){let e=Et.get(n.getAccessToken);return e||(e=new _e(n),Et.set(n.getAccessToken,e)),e}function De(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function Le(n){let e=xn(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}function vn(n){return(n??ke).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function yn(n){return xe(n)?`Bearer ${await Oe(n).getToken()}`:Le(n)}async function Tt(n){try{let e=vn(n.apiConfig?.endpoint),t=De(n.apiConfig),o=await yn(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 wn="0.1.42",_t=!1;function Sn(){return crypto.randomUUID()}function Pn(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.text},kind:n.kind}}function In(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=>Pn(r,t)),...a!=null&&{contact_account_count:a}},meta:{request_id:Sn(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:wn,session_id:o}}}async function kt(n,e,t,o,i){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:o,signal:i})}async function Ot(n,e,t){let o=t.apiConfig,i=!t.maskCompletedText,a=In(n,e,i,t.sessionId),r=De(o),s=o?.endpoint??ke,l=JSON.stringify(a);if(xe(o)){let p=Oe(o),m=await p.getToken(),v=await kt(s,r,m,l,t.signal);if(v.status===401){let g=await p.getToken(!0);v=await kt(s,r,g,l,t.signal)}if(!v.ok)throw new Error(`API error: ${v.status} ${v.statusText}`);return v.json()}let d=Le(o);!d&&!_t&&(_t=!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 Dt(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 Cn=100,An=300,En=2,Me=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 Ot(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:o.signal,apiConfig:this.getApiConfig()});if(i!==this.fetchVersion)return;let s=Dt(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=ie(u,p,m),c=pe(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=ce(i.text,i.filterBase,a),s=ie(i.text,r,i.filterInProgress),d=i.suggestions.filter(h=>h.type!=="placeholder")[0],p=(d?re(d.options,s):[]).filter(h=>h.is_tappable),m=d?pe(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}=R(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(En)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},Cn),this.slowDebounceTimer=setTimeout(()=>t(1),An)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};function Lt(n){return n instanceof HTMLTextAreaElement||n instanceof HTMLInputElement?n.selectionStart!=null&&n.selectionStart===n.value.length:n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?St(n):!1}function Tn(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?B(n):null}var Re=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:o,getOnSubmit:i}=this.ctx,a=this.getEffectiveColumns(),r=i(),s=this.getTappableIndices(a);switch(e.key){case"ArrowDown":{let l=Lt(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?.(),O(d,u);break}Lt(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?.(),O(l,d);break}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let l=Tn(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}=R(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(()=>O(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?.(),O(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 Ne=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}=R(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 Mt(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 Rt(n,e){let t=Ct(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=ce(n.text,Math.min(n.filterBase,n.text.length),r),d=n.lastRawQuery!==""||s>0?ie(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=re(n.editingParam.options,c)}else m=re(u,d);e.showNonTappableOptions===!1&&(m=m.filter(g=>g.is_tappable));let v=Mt({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 He(n){return n.mode==="fresh"?_n(n):kn(n)}function _n(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=ce(e,i,l),u=ie(e,d,a),p=pe(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 kn(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=pe(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 Fe=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:R(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=He({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 Nt="data-aia-key";function Be(n,e,t){let o=new Map;for(let r of Array.from(n.children)){let s=r.getAttribute(Nt);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(Nt,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 Ht=[125,69];function Ft(n){return n===0?.4:n===1?.3:.15}function Ke(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<Ht.length;s++){let l=Ht[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(Ft(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();Be(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(Ft(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 nt(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var On=[159,119,164];function ze(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 We(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)),Ke(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)),Dn(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 On){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 Dn(n,e,t,o,i,a,r){let s=r?"1":"0";Be(n,e,{keyOf:l=>`${l.text}\0${s}`,create:l=>Ln(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 Ln(n,e){let t=document.createElement("div");t.setAttribute("role","option"),t.setAttribute("data-aia-option",""),e&&t.setAttribute("data-aia-loading",""),t.tabIndex=e||!n.is_tappable?-1:0;let o=["magicx-aia-option"];n.is_tappable?o.push("magicx-aia-option--tappable"):o.push("magicx-aia-option--non-tappable"),t.className=o.join(" ");let i=document.createElement("div");i.className="magicx-aia-streaks",t.appendChild(i);let a=document.createElement("div");a.className="magicx-aia-streaks-vert",t.appendChild(a);let r=document.createElement("span");if(r.className="magicx-aia-option-content",r.textContent=n.icon?`${n.icon} ${n.text}`:n.text,n.tag){let s=document.createElement("span");s.className="magicx-aia-option-tag",s.textContent=n.tag,r.appendChild(s)}return t.appendChild(r),t}function Bt(n,e){let t=ze(e.listboxId);return n.appendChild(t),{dropdown:t}}function ot(n,e,t){We(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 $e(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?B(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&&O(e,Math.max(0,Math.min(m,b)))}var Mn='<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 Rn(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function Kt(n,e){let{listboxId:t}=e,o=ze(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",Rn()?"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=Mn,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=de(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(B(r)))},{signal:p});let f=r.ownerDocument??document;return f.addEventListener("selectionchange",()=>{let c=f.getSelection();if(!c||c.rangeCount===0||!r.contains(c.anchorNode))return;let h=b(),x=e.store.get().editingParam?.id??null;if(h&&h!==x){e.startEditingParam(h);return}performance.now()-v<50||e.handleCaretMove(B(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 D=S.getRangeAt(0);if(!r.contains(D.startContainer))return;D.deleteContents();let N=x.createTextNode(h);D.insertNode(N),D.setStartAfter(N),D.collapse(!0),S.removeAllRanges(),S.addRange(D),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:D}=R(h.text,h.completedParams);e.onSubmit({query:h.text.trim(),raw_query:S,completed_params:D}),e.afterSubmit?.()},{signal:p}),e.autoFocus!==!1&&r.focus(),{input:r,inlinePillContainer:s,dropdown:o,submitButton:l,abort:u}}function it(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($e({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?Ke(i,e.actionableSuggestions,0,l,!1,f):nt(i)}else nt(i);v?(o.focus(),O(o,e.caretOffset??e.text.length)):e.isFocused&&de(o)!==e.text&&O(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];We(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 zt(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=It(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 Wt(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 $t(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 rt=!1;function Ut(){if(rt||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){rt=!0;return}rt=!0;let n=document.createElement("style");n.setAttribute("data-magicx-aia",""),n.textContent=Nn,document.head.appendChild(n)}var Nn="";var Ue=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 qe=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 Hn="newParam",qt="suggestionRemoval",Fn="selectionAnimation",Bn=650,Kn=0;function zn(){return`:ac-${++Kn}:`}var Gt=500;function Qt(){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 Ge=class{constructor(e,t={}){this.inputStore=Wt(Qt());this._listboxId=zn();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new qe;this.emitter=new Ue;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=$t(this.inputStore,o=>Rt(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 Ne(this.store,{onPillSelected:({rawQuery:o,selectedPill:i,otherPills:a})=>{this.fireTelemetry("pill",{raw_query:o,selected_pill:i,other_pills:a})}}),this.reEdit=new Fe({store:this.store,scheduleSetCursor:o=>this.scheduleSetCursor(o),fireTelemetry:(o,i)=>this.fireTelemetry(o,i),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer()}),this.fetchController=new Me(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 Re(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"&&(Ut(),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({...Qt(),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=Pt(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(),O(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=zt(t,e);if(o&&(this.fireTelemetry("option",{raw_query:R(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(qt),o.remainingActionable>0)){let i=o.consumedSuggestion;this.timers.schedule(qt,()=>{this.store.set(a=>({suggestions:a.suggestions.filter(r=>r!==i)}))},Gt)}}startSelectionAnimationTimer(){this.timers.schedule(Fn,()=>this.store.set({inSelectionAnimation:!1}),Gt)}fireTelemetry(e,t){let o=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");Tt({source:o,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}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 ue(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=Kt(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&it(this.domRefs,this.store.get(),t)}),it(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=Bt(this.container,e),this.subscribeBatchedRender(()=>{this.dropdownRefs&&ot(this.dropdownRefs,this.store.get(),e)}),ot(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(Hn,()=>this.store.set({newParamId:null}),Bn)}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:o,invalid:i}=At(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(re(e.editingParam.options,o).some(s=>s.is_tappable))return;this.reEdit.exit();let{rawQuery:a,completedParams:r}=R(e.text,e.completedParams);this.fetchController.doFetch(a,r)}maybePromoteExactMatch(e){let t=this.store.get(),o=He({mode:"fresh",text:e,completedParams:t.completedParams,suggestions:t.suggestions,filterBase:t.filterBase,filterInProgress:t.filterInProgress});o&&this.store.set(o.patch)}};var $n={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 at({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=K(null),[h,x]=Wn(null),S=K(n);S.current=n;let D=K(e);D.current=e;let N=K(v);N.current=v;let Z=K(g);Z.current=g;let V=K(d);V.current=d;let H=K(u);H.current=u;let ee=K(f);ee.current=f,Qe(()=>{if(typeof document>"u")return;let y=new Ge(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:(...L)=>S.current?.(...L),onError:(...L)=>D.current?.(...L),onChange:(...L)=>N.current?.(...L),onParamsChange:(...L)=>Z.current?.(...L),onFocus:()=>V.current?.(),onBlur:()=>H.current?.(),setCursor:L=>ee.current?.(L)});c.current=y,x(y.getState());let M=y.subscribe(L=>x(L));return()=>{M(),y.destroy(),c.current===y&&(c.current=null)}},[]),Qe(()=>{p!==void 0&&c.current?.setValue(p)},[p]),Qe(()=>{m!==void 0&&c.current?.setCompletedParams(m)},[m]);let W=JSON.stringify(i??null),j=K(t),ae=K(0);if(t!==j.current){let y=j.current,M=t,L=Object.keys(y??{}),se=Object.keys(M??{});(L.length!==se.length||se.some(he=>!y?.[he]||M[he]!==y[he]))&&ae.current++,j.current=t}Qe(()=>{c.current?.update({apiConfig:i,optionOverrides:t,dropdownTrigger:r,closeDropdownOnBlur:s,showNonTappableOptions:l})},[W,ae.current,r,s,l]);let q=K(null);q.current===null&&(q.current={handleTextChange:y=>c.current?.handleTextChange(y),handleKeyDown:y=>{let M="nativeEvent"in y?y.nativeEvent:y;c.current?.handleKeyDown(M)},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 E=q.current,ge=Vt(y=>{let M=y.target.value,se=M.length>0&&!y.nativeEvent?.isComposing&&M[0]!==M[0].toUpperCase()?M[0].toUpperCase()+M.slice(1):M;c.current?.handleTextChange(se)},[]),te=Vt(y=>{c.current?.handleKeyDown(y.nativeEvent)},[]),G=c.current,I=h??$n,fe=p!==void 0?p:I.text,w=m!==void 0?m:I.completedParams,P=I.actionableSuggestions,A=P[0],T=G?.listboxId??"",_=I.activeDropdownIndex>=0&&G?`${T}-option-${I.activeDropdownIndex}`:void 0,k=I.editingParam,Q=k?{type:k.suggestionType,text:k.suggestionPlaceholder,required:!0,options:k.options}:null,X=Q??A,je=Q?[Q]:P,ye=!G||I.isLoading&&!I.editingParam&&!I.inSelectionAnimation;return{completedParams:w,suggestionPills:P,setActivePill:E.setActivePill,removeLastParam:E.removeLastParam,segments:I.segments,newParamId:I.newParamId,clearNewParamId:E.clearNewParamId,suggestions:I.suggestions,activeIndex:I.activeDropdownIndex,isReady:I.isReady,isLoading:ye,isFocused:I.isFocused,isDropdownOpen:I.isDropdownOpen,placeholderText:I.placeholderText,listboxId:T,error:I.error,handleTextChange:E.handleTextChange,handleKeyDown:E.handleKeyDown,setFocused:E.setFocused,editingParam:k,editingAnchor:I.editingAnchor,caretOffset:I.caretOffset,startEditingParam:E.startEditingParam,exitEditMode:E.exitEditMode,handleCaretAfterInput:E.handleCaretAfterInput,handleCaretMove:E.handleCaretMove,replaceEditingRange:E.replaceEditingRange,inputProps:{value:fe,placeholder:I.placeholderText||void 0,onChange:ge,onKeyDown:te,onFocus:E.handleFocus,onBlur:E.handleBlur,role:"combobox","aria-expanded":I.isDropdownOpen,"aria-activedescendant":_,"aria-autocomplete":"list","aria-controls":T},reset:E.reset,dropdownProps:{suggestions:X?[{...X,options:I.filteredOptions}]:[],activeIndex:I.activeDropdownIndex,onSelect:E.selectOption,onHighlight:E.setActiveDropdownIndex,isOpen:I.isDropdownOpen,id:T,pills:je,onPillClick:E.setActivePill,isLoading:ye}}}import{useCallback as z,useEffect as st,useLayoutEffect as lt,useRef as me}from"react";var Ve;function Un(){if(Ve!==void 0)return Ve;if(typeof document>"u")return!1;let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),Ve=n.contentEditable==="plaintext-only",Ve}function jt(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=me(null),S=me(!1),D=me(""),N=me(""),Z=me(null),V=me(0);Z.current=a,st(()=>{if(!p)return;let w=x.current;w&&(document.activeElement===w?h(!0):w.focus())},[p,h]),st(()=>{let w=x.current;if(!w)return;let P=w.ownerDocument??document,A=()=>{let T=P.getSelection();if(!T||T.rangeCount===0||!T.anchorNode||!w.contains(T.anchorNode))return;let _=T.anchorNode,X=(_.nodeType===Node.ELEMENT_NODE?_:_.parentElement)?.closest('strong[data-seg="completed"][data-param-id]')?.dataset.paramId??null;if(X&&X!==o?.id){f(X);return}performance.now()-V.current<50||b(B(w))};return P.addEventListener("selectionchange",A),()=>P.removeEventListener("selectionchange",A)},[o,f,b]),lt(()=>{let w=x.current;w&&$e({input:w,segments:e,newParamId:t,editingParamId:o?.id??null,placeholderText:r??"",isFocused:s})},[e,t,o,r,s]),lt(()=>{let w=D.current,P=t??"";if(D.current=P,!P||P===w)return;let A=x.current;if(!A)return;A.focus();let T=Z.current??Te(A);O(A,T)},[t]),lt(()=>{let w=N.current,P=o?.id??"";if(N.current=P,!P||P===w||i==null)return;let A=x.current;A&&O(A,i)},[o,i]);let H=z(()=>{if(S.current)return;let w=x.current;if(!w)return;let P=de(w),T=P.length>0&&P[0]!==P[0].toUpperCase()?P[0].toUpperCase()+P.slice(1):P;m(T)},[m]),ee=z(()=>{V.current=performance.now(),H();let w=x.current;w&&g(B(w))},[H,g]);st(()=>{let w=x.current;if(!w)return;let P=A=>{let T=A,_=T.inputType;if(_==="insertParagraph"||_==="insertLineBreak"||_==="insertFromDrop"){A.preventDefault();return}if(_.startsWith("insert")||_.startsWith("delete")){let k=_.startsWith("delete")?"":T.data??"";c(k)&&A.preventDefault()}};return w.addEventListener("beforeinput",P),()=>w.removeEventListener("beforeinput",P)},[c]);let W=z(()=>{S.current=!0},[]),j=z(()=>{S.current=!1,H()},[H]),ae=z(w=>{w.preventDefault();let P=x.current;if(!P)return;let A=(w.clipboardData.getData("text/plain")??"").replace(/\r?\n/g," ");if(!A)return;let T=P.ownerDocument??document,_=T.getSelection();if(!_||_.rangeCount===0)return;let k=_.getRangeAt(0);if(!P.contains(k.startContainer))return;k.deleteContents();let Q=T.createTextNode(A);k.insertNode(Q),k.setStartAfter(Q),k.collapse(!0),_.removeAllRanges(),_.addRange(k),H()},[H]),q=z(w=>v(w),[v]),E=z(()=>h(!0),[h]),ge=z(()=>h(!1),[h]),te=z(()=>x.current?.focus(),[]),G=z(()=>x.current?.blur(),[]),I=z(()=>{let w=x.current;return w?de(w):""},[]),fe=Un()?"plaintext-only":"true";return{inputRef:x,editorProps:{ref:x,contentEditable:fe,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:ee,onKeyDown:q,onCompositionStart:W,onCompositionEnd:j,onPaste:ae,onFocus:E,onBlur:ge},getPlainText:I,focus:te,blur:G}}import{jsx as Y,jsxs as ct}from"react/jsx-runtime";function Vn(n){return n!=="auto"?n:typeof window>"u"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}var jn=qn(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:D,submitButton:N},Z){let V=ve(null),H=ve(null),ee=ve(()=>{}),W=ve(null),j=ve(null);Xt(()=>{let C=V.current;if(C)return W.current?W.current.setMode(d):W.current=new ue(C,d),()=>{W.current?.destroy(),W.current=null}},[d]);let ae=dt(C=>{let F=j.current?.current;F&&(F.focus(),O(F,C))},[]),{completedParams:q,suggestionPills:E,setActivePill:ge,segments:te,newParamId:G,clearNewParamId:I,placeholderText:fe,isFocused:w,isDropdownOpen:P,isLoading:A,activeIndex:T,listboxId:_,handleTextChange:k,handleKeyDown:Q,setFocused:X,editingParam:je,editingAnchor:ye,caretOffset:y,startEditingParam:M,handleCaretAfterInput:L,handleCaretMove:se,replaceEditingRange:he,dropdownProps:Jt,reset:we}=at({onSubmit:C=>ee.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:D,source:"full-sdk",setCursor:ae});Xt(()=>{if(!G)return;let C=window.setTimeout(()=>I(),650);return()=>window.clearTimeout(C)},[G,I]);let Yt=T>=0?`${_}-option-${T}`:void 0,{inputRef:Xe,editorProps:Zt,focus:Se,blur:pt,getPlainText:ut}=jt({segments:te,newParamId:G,editingParam:je,editingAnchor:ye,caretOffset:y,placeholderText:fe,isFocused:w,isDropdownOpen:P,listboxId:_,activeDescendantId:Yt,autoFocus:b,handleTextChange:k,handleKeyDown:Q,handleCaretAfterInput:L,handleCaretMove:se,startEditingParam:M,replaceEditingRange:he,setFocused:X});j.current=Xe,Qn(()=>{let C=H.current,F=Xe.current;if(!C||!F)return;let Ie=()=>{let gt=C.firstElementChild;if(!gt)return;if(F.dataset.aiaEmpty==="true"){C.setAttribute("data-aia-pill-wrapped","");return}let on=gt.getBoundingClientRect(),rn=F.getBoundingClientRect();on.top>=rn.bottom-2?C.setAttribute("data-aia-pill-wrapped",""):C.removeAttribute("data-aia-pill-wrapped")};Ie();let mt=new ResizeObserver(Ie);return mt.observe(F),()=>mt.disconnect()},[te,E.length,A,Xe]),Gn(Z,()=>({focus:Se,blur:pt,reset:we,setMode:C=>W.current?.setMode(C)}),[Se,pt,we]);let Pe=!!te.length||q.length>0,Je=dt(()=>{if(!Pe)return;let C=ut(),{rawQuery:F,completedParams:Ie}=R(C,q);e({query:C.trim(),raw_query:F,completed_params:Ie}),we()},[Pe,q,e,we,ut]);ee.current=Je;let en=dt(C=>{C.target?.closest("[data-aia-pill]")||Se()},[Se]),tn=l==="inline",nn=l==="dropdown";return ct("div",{ref:V,className:`magicx-aia ${J.container} ${a??""}`,"data-pill-placement":l,"data-options-position":u,"data-animations":p?"on":"off","data-mode":Vn(d),children:[Y(tt,{...Jt,showPills:nn}),ct("div",{className:J.inputWrapper,onClick:en,children:[ct("div",{className:J.editorArea,"data-aia-editor":"",children:[Y("div",{...Zt,className:J.input,"data-aia-input":""}),tn&&(A||E.length>0)&&Y("span",{ref:H,className:J.pillListContainer,"data-aia-pill-list-container":"",children:Y(be,{pills:E,activePillIndex:0,onSelectPill:ge,loading:A})})]}),N===null?null:N===void 0?Y("button",{type:"button","data-aia-submit":"",className:J.submitButton,disabled:!Pe,onClick:C=>{C.stopPropagation(),Je()},"aria-label":"Submit",children:Y("svg",{width:"18",height:"18",viewBox:"0 0 18 18",fill:"none",role:"img","aria-label":"Submit",children:Y("path",{d:"M9 14V4M9 4L4 9M9 4L14 9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}):Y("span",{"data-aia-submit":"",className:J.submitSlot,onClick:C=>{Pe&&(C.stopPropagation(),Je())},children:N})]})]})});export{jn as AIAutocomplete,tt as AIAutocompleteDropdown,at as useAIAutocomplete};
831
+ `,document.head.appendChild(e)}import{buildQuery as bt,ModeController as ht,setCursorOffset as xt}from"@magicx-eng/ai-autocomplete-vanilla";import{AIAutocomplete as st}from"@magicx-eng/ai-autocomplete-vanilla";import{useCallback as Be,useEffect as be,useRef as L,useState as lt}from"react";var dt={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 ke({onSubmit:e,onError:y,optionOverrides:b,maskCompletedText:v,apiConfig:p,columns:l=2,dropdownTrigger:u,closeDropdownOnBlur:c,showNonTappableOptions:x,onFocus:n,onBlur:m,value:w,completedParams:S,onChange:O,onParamsChange:E,source:N,setCursor:B}){let a=L(null),[T,_]=lt(null),G=L(e);G.current=e;let X=L(y);X.current=y;let H=L(O);H.current=O;let Q=L(E);Q.current=E;let V=L(n);V.current=n;let P=L(m);P.current=m;let J=L(B);J.current=B,be(()=>{if(typeof document>"u")return;let t=new st(document.createElement("div"),{renderMode:"headless",apiConfig:p,optionOverrides:b,maskCompletedText:v,columns:l,dropdownTrigger:u,closeDropdownOnBlur:c,showNonTappableOptions:x,source:N,value:w,completedParams:S,onSubmit:(...k)=>G.current?.(...k),onError:(...k)=>X.current?.(...k),onChange:(...k)=>H.current?.(...k),onParamsChange:(...k)=>Q.current?.(...k),onFocus:()=>V.current?.(),onBlur:()=>P.current?.(),setCursor:k=>J.current?.(k)});a.current=t,_(t.getState());let A=t.subscribe(k=>_(k));return()=>{A(),t.destroy(),a.current===t&&(a.current=null)}},[]),be(()=>{w!==void 0&&a.current?.setValue(w)},[w]),be(()=>{S!==void 0&&a.current?.setCompletedParams(S)},[S]);let z=JSON.stringify(p??null),q=L(b),te=L(0);if(b!==q.current){let t=q.current,A=b,k=Object.keys(t??{}),oe=Object.keys(A??{});(k.length!==oe.length||oe.some(ie=>!t?.[ie]||A[ie]!==t[ie]))&&te.current++,q.current=b}be(()=>{a.current?.update({apiConfig:p,optionOverrides:b,dropdownTrigger:u,closeDropdownOnBlur:c,showNonTappableOptions:x})},[z,te.current,u,c,x]);let K=L(null);K.current===null&&(K.current={handleTextChange:t=>a.current?.handleTextChange(t),handleKeyDown:t=>{let A="nativeEvent"in t?t.nativeEvent:t;a.current?.handleKeyDown(A)},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 g=K.current,ne=Be(t=>{let A=t.target.value,oe=A.length>0&&!t.nativeEvent?.isComposing&&A[0]!==A[0].toUpperCase()?A[0].toUpperCase()+A.slice(1):A;a.current?.handleTextChange(oe)},[]),Y=Be(t=>{a.current?.handleKeyDown(t.nativeEvent)},[]),F=a.current,i=T??dt,re=w!==void 0?w:i.text,o=S!==void 0?S:i.completedParams,r=i.actionableSuggestions,d=r[0],f=F?.listboxId??"",h=i.activeDropdownIndex>=0&&F?`${f}-option-${i.activeDropdownIndex}`:void 0,I=i.editingParam,W=I?{type:I.suggestionType,text:I.suggestionPlaceholder,required:!0,options:I.options}:null,$=W??d,xe=W?[W]:r,de=!F||i.isLoading&&!i.editingParam&&!i.inSelectionAnimation;return{completedParams:o,suggestionPills:r,setActivePill:g.setActivePill,removeLastParam:g.removeLastParam,segments:i.segments,newParamId:i.newParamId,clearNewParamId:g.clearNewParamId,suggestions:i.suggestions,activeIndex:i.activeDropdownIndex,isReady:i.isReady,isLoading:de,isFocused:i.isFocused,isDropdownOpen:i.isDropdownOpen,placeholderText:i.placeholderText,listboxId:f,error:i.error,handleTextChange:g.handleTextChange,handleKeyDown:g.handleKeyDown,setFocused:g.setFocused,editingParam:I,editingAnchor:i.editingAnchor,caretOffset:i.caretOffset,startEditingParam:g.startEditingParam,exitEditMode:g.exitEditMode,handleCaretAfterInput:g.handleCaretAfterInput,handleCaretMove:g.handleCaretMove,replaceEditingRange:g.replaceEditingRange,inputProps:{value:re,placeholder:i.placeholderText||void 0,onChange:ne,onKeyDown:Y,onFocus:g.handleFocus,onBlur:g.handleBlur,role:"combobox","aria-expanded":i.isDropdownOpen,"aria-activedescendant":h,"aria-autocomplete":"list","aria-controls":f},reset:g.reset,dropdownProps:{suggestions:$?[{...$,options:i.filteredOptions}]:[],activeIndex:i.activeDropdownIndex,onSelect:g.selectOption,onHighlight:g.setActiveDropdownIndex,isOpen:i.isDropdownOpen,id:f,pills:xe,onPillClick:g.setActivePill,isLoading:de}}}import{extractPlainText as He,getCursorOffset as Ke,plainTextLength as pt,renderEditableContent as ut,setCursorOffset as Fe}from"@magicx-eng/ai-autocomplete-vanilla";import{useCallback as R,useEffect as Ae,useLayoutEffect as Se,useRef as ae}from"react";var he;function ct(){if(he!==void 0)return he;if(typeof document>"u")return!1;let e=document.createElement("div");return e.setAttribute("contenteditable","plaintext-only"),he=e.contentEditable==="plaintext-only",he}function We(e){let{segments:y,newParamId:b,editingParam:v,editingAnchor:p,caretOffset:l,placeholderText:u,isFocused:c,isDropdownOpen:x,listboxId:n,activeDescendantId:m,autoFocus:w,handleTextChange:S,handleKeyDown:O,handleCaretAfterInput:E,handleCaretMove:N,startEditingParam:B,replaceEditingRange:a,setFocused:T}=e,_=ae(null),G=ae(!1),X=ae(""),H=ae(""),Q=ae(null),V=ae(0);Q.current=l,Ae(()=>{if(!w)return;let o=_.current;o&&(document.activeElement===o?T(!0):o.focus())},[w,T]),Ae(()=>{let o=_.current;if(!o)return;let r=o.ownerDocument??document,d=()=>{let f=r.getSelection();if(!f||f.rangeCount===0||!f.anchorNode||!o.contains(f.anchorNode))return;let h=f.anchorNode,$=(h.nodeType===Node.ELEMENT_NODE?h:h.parentElement)?.closest('strong[data-seg="completed"][data-param-id]')?.dataset.paramId??null;if($&&$!==v?.id){B($);return}performance.now()-V.current<50||N(Ke(o))};return r.addEventListener("selectionchange",d),()=>r.removeEventListener("selectionchange",d)},[v,B,N]),Se(()=>{let o=_.current;o&&ut({input:o,segments:y,newParamId:b,editingParamId:v?.id??null,placeholderText:u??"",isFocused:c})},[y,b,v,u,c]),Se(()=>{let o=X.current,r=b??"";if(X.current=r,!r||r===o)return;let d=_.current;if(!d)return;d.focus();let f=Q.current??pt(d);Fe(d,f)},[b]),Se(()=>{let o=H.current,r=v?.id??"";if(H.current=r,!r||r===o||p==null)return;let d=_.current;d&&Fe(d,p)},[v,p]);let P=R(()=>{if(G.current)return;let o=_.current;if(!o)return;let r=He(o),f=r.length>0&&r[0]!==r[0].toUpperCase()?r[0].toUpperCase()+r.slice(1):r;S(f)},[S]),J=R(()=>{V.current=performance.now(),P();let o=_.current;o&&E(Ke(o))},[P,E]);Ae(()=>{let o=_.current;if(!o)return;let r=d=>{let f=d,h=f.inputType;if(h==="insertParagraph"||h==="insertLineBreak"||h==="insertFromDrop"){d.preventDefault();return}if(h.startsWith("insert")||h.startsWith("delete")){let I=h.startsWith("delete")?"":f.data??"";a(I)&&d.preventDefault()}};return o.addEventListener("beforeinput",r),()=>o.removeEventListener("beforeinput",r)},[a]);let z=R(()=>{G.current=!0},[]),q=R(()=>{G.current=!1,P()},[P]),te=R(o=>{o.preventDefault();let r=_.current;if(!r)return;let d=(o.clipboardData.getData("text/plain")??"").replace(/\r?\n/g," ");if(!d)return;let f=r.ownerDocument??document,h=f.getSelection();if(!h||h.rangeCount===0)return;let I=h.getRangeAt(0);if(!r.contains(I.startContainer))return;I.deleteContents();let W=f.createTextNode(d);I.insertNode(W),I.setStartAfter(W),I.collapse(!0),h.removeAllRanges(),h.addRange(I),P()},[P]),K=R(o=>O(o),[O]),g=R(()=>T(!0),[T]),ne=R(()=>T(!1),[T]),Y=R(()=>_.current?.focus(),[]),F=R(()=>_.current?.blur(),[]),i=R(()=>{let o=_.current;return o?He(o):""},[]),re=ct()?"plaintext-only":"true";return{inputRef:_,editorProps:{ref:_,contentEditable:re,suppressContentEditableWarning:!0,tabIndex:0,role:"combobox","aria-autocomplete":"list","aria-haspopup":"listbox","aria-controls":n,"aria-expanded":x,"aria-activedescendant":m,spellCheck:!0,enterKeyHint:"send",onInput:J,onKeyDown:K,onCompositionStart:z,onCompositionEnd:q,onPaste:te,onFocus:g,onBlur:ne},getPlainText:i,focus:Y,blur:F}}import{jsx as j,jsxs as Ee}from"react/jsx-runtime";function vt(e){return e!=="auto"?e:typeof window>"u"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}var wt=mt(function({onSubmit:y,onError:b,optionOverrides:v,maskCompletedText:p,className:l,apiConfig:u,columns:c,pillPlacement:x="inline",mode:n="auto",optionsPosition:m="below",animations:w=!0,dropdownTrigger:S,closeDropdownOnBlur:O,showNonTappableOptions:E,autoFocus:N=!0,onFocus:B,onBlur:a,value:T,completedParams:_,onChange:G,onParamsChange:X,submitButton:H},Q){let V=le(null),P=le(null),J=le(()=>{}),z=le(null),q=le(null);Ne(()=>{let s=V.current;if(s)return z.current?z.current.setMode(n):z.current=new ht(s,n),()=>{z.current?.destroy(),z.current=null}},[n]);let te=Pe(s=>{let C=q.current?.current;C&&(C.focus(),xt(C,s))},[]),{completedParams:K,suggestionPills:g,setActivePill:ne,segments:Y,newParamId:F,clearNewParamId:i,placeholderText:re,isFocused:o,isDropdownOpen:r,isLoading:d,activeIndex:f,listboxId:h,handleTextChange:I,handleKeyDown:W,setFocused:$,editingParam:xe,editingAnchor:de,caretOffset:t,startEditingParam:A,handleCaretAfterInput:k,handleCaretMove:oe,replaceEditingRange:ie,dropdownProps:Ge,reset:pe}=ke({onSubmit:s=>J.current(s),onError:b,optionOverrides:v,maskCompletedText:p,apiConfig:u,columns:c,dropdownTrigger:S,closeDropdownOnBlur:O,showNonTappableOptions:E,onFocus:B,onBlur:a,value:T,completedParams:_,onChange:G,onParamsChange:X,source:"full-sdk",setCursor:te});Ne(()=>{if(!F)return;let s=window.setTimeout(()=>i(),650);return()=>window.clearTimeout(s)},[F,i]);let Ve=f>=0?`${h}-option-${f}`:void 0,{inputRef:ve,editorProps:qe,focus:ue,blur:Ce,getPlainText:De}=We({segments:Y,newParamId:F,editingParam:xe,editingAnchor:de,caretOffset:t,placeholderText:re,isFocused:o,isDropdownOpen:r,listboxId:h,activeDescendantId:Ve,autoFocus:N,handleTextChange:I,handleKeyDown:W,handleCaretAfterInput:k,handleCaretMove:oe,startEditingParam:A,replaceEditingRange:ie,setFocused:$});q.current=ve,ft(()=>{let s=P.current,C=ve.current;if(!s||!C)return;let me=()=>{let Re=s.firstElementChild;if(!Re)return;if(C.dataset.aiaEmpty==="true"){s.setAttribute("data-aia-pill-wrapped","");return}let Xe=Re.getBoundingClientRect(),Qe=C.getBoundingClientRect();Xe.top>=Qe.bottom-2?s.setAttribute("data-aia-pill-wrapped",""):s.removeAttribute("data-aia-pill-wrapped")};me();let Le=new ResizeObserver(me);return Le.observe(C),()=>Le.disconnect()},[Y,g.length,d,ve]),gt(Q,()=>({focus:ue,blur:Ce,reset:pe,setMode:s=>z.current?.setMode(s)}),[ue,Ce,pe]);let ce=!!Y.length||K.length>0,we=Pe(()=>{if(!ce)return;let s=De(),{rawQuery:C,completedParams:me}=bt(s,K);y({query:s.trim(),raw_query:C,completed_params:me}),pe()},[ce,K,y,pe,De]);J.current=we;let $e=Pe(s=>{s.target?.closest("[data-aia-pill]")||ue()},[ue]),Ue=x==="inline",je=x==="dropdown";return Ee("div",{ref:V,className:`magicx-aia ${U.container} ${l??""}`,"data-pill-placement":x,"data-options-position":m,"data-animations":w?"on":"off","data-mode":vt(n),children:[j(Ie,{...Ge,showPills:je}),Ee("div",{className:U.inputWrapper,onClick:$e,children:[Ee("div",{className:U.editorArea,"data-aia-editor":"",children:[j("div",{...qe,className:U.input,"data-aia-input":""}),Ue&&(d||g.length>0)&&j("span",{ref:P,className:U.pillListContainer,"data-aia-pill-list-container":"",children:j(se,{pills:g,activePillIndex:0,onSelectPill:ne,loading:d})})]}),H===null?null:H===void 0?j("button",{type:"button","data-aia-submit":"",className:U.submitButton,disabled:!ce,onClick:s=>{s.stopPropagation(),we()},"aria-label":"Submit",children:j("svg",{width:"18",height:"18",viewBox:"0 0 18 18",fill:"none",role:"img","aria-label":"Submit",children:j("path",{d:"M9 14V4M9 4L4 9M9 4L14 9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}):j("span",{"data-aia-submit":"",className:U.submitSlot,onClick:s=>{ce&&(s.stopPropagation(),we())},children:H})]})]})});export{wt as AIAutocomplete,Ie as AIAutocompleteDropdown,ke as useAIAutocomplete};
823
832
  //# sourceMappingURL=index.mjs.map