@magicx-eng/ai-autocomplete-vanilla 0.1.17 → 0.1.18

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/index.mjs CHANGED
@@ -1,4 +1,68 @@
1
- function T(i,e){let t=i,n={},s=[];for(let r of e){let o=(n[r.type]??0)+1;n[r.type]=o;let l=`{{${r.type.toUpperCase().replace(/\s+/g,"_")}_${o}}}`,c=t.indexOf(r.text);c!==-1&&(t=t.slice(0,c)+l+t.slice(c+r.text.length)),s.push({...r,placeholder:l})}return{rawQuery:t,completedParams:s}}function O(i,e,t){return e>0||!t?e:i.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function w(i,e,t){let n=i.slice(e);if(t||e===0||i[e-1]===" ")return n;let s=n.indexOf(" ");return s===-1?"":n.slice(s+1)}function Z(i,e){let t=i.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let n=t.split(" "),s=e.toLowerCase();for(let r=0;r<n.length;r++){let o=n.slice(r).join(" ");if(s.startsWith(o.toLowerCase())){let a=t.length-o.length;return i.length-a}}return 0}function I(i,e){if(!i)return[];let t=e.trimStart();if(!t)return i;let n=t.toLowerCase();return i.filter(s=>!s.is_tappable||s.text.toLowerCase().includes(n))}function E(i,e){if(!i)return null;let t=e.trim();if(!t)return null;let n=t.toLowerCase();return i.find(s=>s.is_tappable&&s.text.toLowerCase()===n)??null}var M=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 ee(i,e){let t=[],n=0;for(let r of e){let o=i.indexOf(r.text,n);o!==-1&&(o>n&&t.push({type:"text",value:i.slice(n,o)}),t.push({type:"completed",value:r.text,param:r}),n=o+r.text.length)}let s=i.slice(n);return s&&t.push({type:"text",value:s}),t}function te(i,e){let t=[],n=[],s=0;for(let r of e){let o=i.indexOf(r.text,s);o===-1?n.push(r):(t.push(r),s=o+r.text.length)}return{valid:t,invalid:n}}var k=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 Pe="https://api.ai-autocomplete.com",R=`${Pe}/api/suggest`,ne=new WeakMap;function D(i){return i?.type==="accessToken"}function Ce(i){if(!(!i||D(i)))return i}function _(i){let e=ne.get(i.getAccessToken);return e||(e=new k(i),ne.set(i.getAccessToken,e)),e}function N(i){return{"Content-Type":"application/json",...i?.appIdentifier&&{"X-App-Identifier":i.appIdentifier},...i?.headers}}function F(i){let e=Ce(i),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}function we(i){return(i??R).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function Ee(i){return D(i)?`Bearer ${await _(i).getToken()}`:F(i)}async function ie(i){try{let e=we(i.apiConfig?.endpoint),t=N(i.apiConfig),n=await Ee(i.apiConfig);n&&(t.Authorization=n);let s=JSON.stringify({source:i.source,session_id:i.sessionId,type:i.type,at:new Date().toISOString(),query_data:i.queryData});await fetch(e,{method:"POST",headers:t,body:s})}catch{}}var Ae="0.1.41",oe=!1;function Oe(){return crypto.randomUUID()}function Ie(i,e){return{placeholder:i.placeholder,type:i.type,...e&&{text:i.text},kind:i.kind}}function De(i,e,t,n){let s=e.find(o=>o.type==="contact"&&o.metadata?.contact_account_count)?.metadata?.contact_account_count,r=typeof s=="number"?s:void 0;return{data:{raw_query:i,completed_params:e.map(o=>Ie(o,t)),...r!=null&&{contact_account_count:r}},meta:{request_id:Oe(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:Ae,session_id:n}}}async function se(i,e,t,n,s){return fetch(i,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:n,signal:s})}async function re(i,e,t){let n=t.apiConfig,s=!t.maskCompletedText,r=De(i,e,s,t.sessionId),o=N(n),a=n?.endpoint??R,l=JSON.stringify(r);if(D(n)){let u=_(n),d=await u.getToken(),h=await se(a,o,d,l,t.signal);if(h.status===401){let x=await u.getToken(!0);h=await se(a,o,x,l,t.signal)}if(!h.ok)throw new Error(`API error: ${h.status} ${h.statusText}`);return h.json()}let c=F(n);!c&&!oe&&(oe=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),c&&(o.Authorization=c);let m=await fetch(a,{method:"POST",headers:o,body:l,signal:t.signal});if(!m.ok)throw new Error(`API error: ${m.status} ${m.statusText}`);return m.json()}function ae(i,e){return e?i.map(t=>{let n=e[t.type];if(!n)return t;let s=n("");if(s.length===0)return t;let r=new Set(s.map(a=>a.text)),o=(t.options??[]).filter(a=>!r.has(a.text));return{...t,options:[...s,...o]}}):i}var Le=100,Me=300,ke=2,H=class{constructor(e,t,n,s,r,o,a={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=n;this.getMaskCompletedText=s;this.getOnError=r;this.getSessionId=o;this.callbacks=a;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(n=>{(n.text!==e||n.completedParams!==t)&&(e=n.text,t=n.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let n=new AbortController;this.abortController=n;let s=++this.fetchVersion,r=this.store.get().text.length;this.store.set({isLoading:!0,error:null});try{let o=await re(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:n.signal,apiConfig:this.getApiConfig()});if(s!==this.fetchVersion)return;let a=ae(o.data.suggestions??[],this.getOptionOverrides()),l=o.data.input??[],c=l[l.length-1],m=this.store.get().text,u,d;if(c?.state==="in_progress"){d=!0;let f=m.toLowerCase().lastIndexOf(c.text.toLowerCase());u=f!==-1?f:r}else d=!1,u=r;let x=a.filter(f=>f.type!=="placeholder")[0],b=null;if(x){let f=w(m,u,d),p=E(x.options,f);p&&(b={id:crypto.randomUUID(),placeholder:"",type:x.type,text:p.text,kind:p.kind,suggestionType:x.type,suggestionPlaceholder:x.text,options:x.options??[],metadata:p.metadata},a=a.filter(g=>g!==x),this.callbacks.onAutoMatch?.({active:x,matched:p,rawQuery:e}))}this.store.set(f=>({suggestions:a,isLoading:!1,isReady:o.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:u,filterInProgress:d,...b?{completedParams:[...f.completedParams,b]}:{}}))}catch(o){if(s===this.fetchVersion){let a=o instanceof Error?o:new Error(String(o));this.store.set({error:a,isLoading:!1}),this.getOnError()?.(a)}}}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}let t=n=>{let s=this.store.get();if(!s.text&&s.completedParams.length===0)return this.doFetch("",[]),!0;let r=s.suggestions.filter(g=>g.type==="placeholder").map(g=>g.text).join(" "),o=O(s.text,s.filterBase,r),a=w(s.text,o,s.filterInProgress),c=s.suggestions.filter(g=>g.type!=="placeholder")[0],u=(c?I(c.options,a):[]).filter(g=>g.is_tappable),d=c?E(c.options,a)!==null:!1,h=a.trim().length>0;if(u.length>0&&!d&&h||s.completedParams.length===0&&s.text.length>0&&r.length>0&&r.toLowerCase().startsWith(s.text.toLowerCase()))return!1;let{rawQuery:x,completedParams:b}=T(s.text,s.completedParams),f=x.length<s.lastRawQuery.length,p=Math.abs(x.length-s.lastRawQuery.length);return f||p>=n?(this.doFetch(x,b),!0):!1};this.debounceTimer=setTimeout(()=>{t(ke)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},Le),this.slowDebounceTimer=setTimeout(()=>t(1),Me)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var ce='[contenteditable="false"]',A;function Re(){if(A!==void 0)return A;let i=globalThis.Intl.Segmenter;if(!i)return A=null,null;try{A=new i(void 0,{granularity:"grapheme"})}catch{A=null}return A??null}function B(i,e){let t=i;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(ce))return!0;t=t.parentNode}return!1}function K(i){return(i.ownerDocument??document).createTreeWalker(i,NodeFilter.SHOW_TEXT,{acceptNode(e){return B(e,i)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function j(i){let e=K(i),t="",n=e.nextNode();for(;n;)t+=n.data,n=e.nextNode();return t}function de(i){let e=K(i),t=0,n=e.nextNode();for(;n;)t+=n.data.length,n=e.nextNode();return t}function C(i){let e=(i.ownerDocument??document).getSelection();if(!e||e.rangeCount===0)return null;let t=e.anchorNode,n=e.anchorOffset;if(!t||!i.contains(t))return null;if(t.nodeType===Node.ELEMENT_NODE){let s=t;if(B(s,i)&&s!==i)return null;let r=0;for(let o=0;o<n&&o<s.childNodes.length;o++)r+=ue(s.childNodes[o],i);return r+le(s,i)}return t.nodeType!==Node.TEXT_NODE||B(t,i)?null:le(t,i)+n}function ue(i,e){if(i.nodeType===Node.TEXT_NODE)return B(i,e)?0:i.data.length;if(i.nodeType!==Node.ELEMENT_NODE)return 0;let t=i;if(t.matches(ce))return 0;let n=0;for(let s of Array.from(t.childNodes))n+=ue(s,e);return n}function le(i,e){let t=K(e),n=0,s=t.nextNode();for(;s;){if(s===i||i.nodeType===Node.ELEMENT_NODE&&i.contains(s))return n;n+=s.data.length,s=t.nextNode()}return n}function S(i,e){let t=i.ownerDocument??document,n=t.getSelection();if(!n)return;let s=Math.max(0,Math.min(e,de(i))),r=K(i),o=0,a=null,l=0,c=r.nextNode(),m=null;for(;c;){let d=c.data.length;if(s<o+d){a=c,l=s-o;break}if(s===o+d){let h=r.nextNode();h?(a=h,l=0):(a=c,l=d);break}o+=d,m=c,c=r.nextNode()}let u=t.createRange();if(a){let d=a.parentElement?.closest('strong[data-seg="completed"]');d&&d!==i&&i.contains(d)?l===0?u.setStartBefore(d):l===a.data.length?u.setStartAfter(d):u.setStart(a,l):u.setStart(a,l)}else m?u.setStart(m,m.data.length):u.setStart(i,0);u.collapse(!0),n.removeAllRanges(),n.addRange(u)}function pe(i){let e=C(i);return e==null?!1:e>=de(i)}function me(i,e){if(e<=0)return 0;let t=Re();if(!t)return e-1;let n=i.slice(0,e),s=0;for(let{index:r}of t.segment(n))r<e&&(s=r);return s}function ge(i){return i instanceof HTMLTextAreaElement||i instanceof HTMLInputElement?i.selectionStart!=null&&i.selectionStart===i.value.length:i instanceof HTMLElement&&i.hasAttribute("data-aia-input")?pe(i):!1}function _e(i){return i instanceof HTMLElement&&i.hasAttribute("data-aia-input")?C(i):null}var q=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:n,getOnSubmit:s}=this.ctx,r=this.getEffectiveColumns(),o=s(),a=this.getTappableIndices(r);switch(e.key){case"ArrowDown":{let l=ge(e.target),c=!!t.editingParam;if(!l&&!c&&t.activeDropdownIndex<0)break;if(e.preventDefault(),!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:a[0]??0});break}if(a.length===0)return;let m=a.indexOf(t.activeDropdownIndex),u=m<a.length-1?m+1:0;this.store.set({activeDropdownIndex:a[u]});break}case"ArrowUp":{if(a.length===0||t.activeDropdownIndex<0)break;if(e.preventDefault(),t.activeDropdownIndex<r){this.store.set({activeDropdownIndex:-1});break}let l=a.indexOf(t.activeDropdownIndex),c=l>0?l-1:a.length-1;this.store.set({activeDropdownIndex:a[c]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%r<r-1){let m=t.activeDropdownIndex+1;m<t.filteredOptions.length&&t.filteredOptions[m]?.is_tappable&&this.store.set({activeDropdownIndex:m})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let c=e.target.closest("[data-aia-input]")??e.target,m=t.editingTail;this.ctx.exitEditMode?.(),S(c,m);break}ge(e.target)&&t.actionableSuggestions.length>1&&(e.preventDefault(),this.pillsSetActivePill(1));break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%r>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,c=t.editingAnchor;this.ctx.exitEditMode?.(),S(l,c);break}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let l=_e(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,n);else if(o){let{rawQuery:l,completedParams:c}=T(t.text,t.completedParams);o({query:t.text.trim(),raw_query:l,completed_params:c}),this.ctx.afterSubmit?.()}break}case"Tab":{let l=!t.text&&!!t.placeholderText,c=t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable;if(l&&!c){e.preventDefault();let m=t.placeholderText;if(this.store.set(u=>({text:m,filterBase:m.length,suggestions:u.suggestions.filter(d=>d.type!=="placeholder")})),e.target instanceof HTMLElement){let u=e.target.closest("[data-aia-input]")??e.target;queueMicrotask(()=>S(u,m.length))}}else if(c)e.preventDefault(),this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,n);else if(t.isDropdownOpen){let m=t.filteredOptions.findIndex(u=>u.is_tappable);m>=0&&(e.preventDefault(),this.clickOrSelect(m,t.filteredOptions,n))}break}case"Escape":{if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){let l=e.target.closest("[data-aia-input]")??e.target,c=t.editingTail;this.ctx.exitEditMode?.(),S(l,c)}this.store.set({activeDropdownIndex:-1});break}}}getTappableIndices(e){let n=this.store.get().filteredOptions.map((r,o)=>r.is_tappable?o:-1).filter(r=>r!==-1),s=Array.from({length:e},()=>[]);for(let r of n)s[r%e].push(r);return s.flat()}getEffectiveColumns(){let t=document.getElementById(`${this.ctx.listboxId}-option-0`)?.parentElement;if(!t)return this.ctx.columns;let n=getComputedStyle(t).gridTemplateColumns.split(" ").filter(Boolean).length;return n>0?n:this.ctx.columns}clickOrSelect(e,t,n){let s=document.getElementById(`${n}-option-${e}`);s?s.click():this.ctx.selectOption(t[e])}pillsSetActivePill(e){let t=this.store.get(),n=t.suggestions.filter(a=>a.type!=="placeholder");if(e<0||e>=n.length)return;let s=n[e],r=n.filter((a,l)=>l!==e),o=t.suggestions.filter(a=>a.type==="placeholder");this.store.set({suggestions:[...o,s,...r],pillTapped:!0,activeDropdownIndex:-1})}};var Q=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),n=t.suggestions.filter(a=>a.type!=="placeholder");if(e<0||e>=n.length)return;let s=n[e],r=n.filter((a,l)=>l!==e),o=t.suggestions.filter(a=>a.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:a}=T(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:a,selectedPill:s.text,otherPills:r.map(l=>l.text)})}this.store.set({suggestions:[...o,s,...r],pillTapped:!0,activeDropdownIndex:-1})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};var he=[125,69];function fe(i){return i===0?.4:i===1?.3:.15}function $(i,e,t,n,s=!1,r=!1){let o=i.querySelector(".magicx-aia-pill-list");if(o||(o=document.createElement("span"),o.className="magicx-aia-pill-list",i.appendChild(o)),r&&e.length===0){o.setAttribute("data-aia-pill-list-loading",""),o.innerHTML="";for(let c=0;c<he.length;c++){let m=he[c],u=document.createElement("span");u.setAttribute("data-aia-pill-skeleton",""),u.className=`magicx-aia-pill magicx-aia-pill--skeleton${s?" magicx-aia-pill--rounded":""}`,u.style.width=`${m}px`,u.style.opacity=String(fe(c)),o.appendChild(u)}return}r?o.setAttribute("data-aia-pill-list-loading",""):o.removeAttribute("data-aia-pill-list-loading");for(let c of o.querySelectorAll("[data-aia-pill-skeleton]"))c.remove();let a=new Map;for(let c of o.querySelectorAll(".magicx-aia-pill"))a.set(c.dataset.pillKey??"",c);let l=new Set;for(let c=0;c<e.length;c++){let m=e[c],u=`${m.type}-${m.text}`;l.add(u);let d=a.get(u);(!d||d.tagName!=="BUTTON")&&(d?.remove(),d=document.createElement("button"),d.type="button",d.tabIndex=-1,d.dataset.pillKey=u,d.setAttribute("data-aia-pill",""),d.setAttribute("contenteditable","false"),d.textContent=m.text,d.addEventListener("mousedown",x=>x.preventDefault()));let h=["magicx-aia-pill"];s&&h.push("magicx-aia-pill--rounded"),c===t&&!r&&h.push("magicx-aia-pill--active"),r&&h.push("magicx-aia-pill--skeleton"),d.className=h.join(" "),d.style.width="",d.style.opacity=String(fe(c)),r?(d.setAttribute("data-aia-loading",""),d.disabled=!0,d.onclick=null):(d.removeAttribute("data-aia-loading"),d.disabled=!1,d.onclick=()=>n(c)),o.children[c]!==d&&o.insertBefore(d,o.children[c]??null)}for(let[c,m]of a)l.has(c)||m.remove()}function G(i){i.querySelector(".magicx-aia-pill-list")?.remove()}var Ne=[159,119,164];function U(i){let e=document.createElement("div");return e.id=i,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",t=>t.preventDefault()),e}function W(i,e){let{filteredOptions:t,activeIndex:n,isOpen:s,isLoading:r,pills:o,showPills:a,onSelect:l,onHighlight:c,onPillClick:m}=e,u=a&&o.length>0,d=t.length>0;s&&(d||u||r)?i.classList.add("magicx-aia-dropdown--visible"):i.classList.remove("magicx-aia-dropdown--visible"),r?i.setAttribute("data-aia-loading",""):i.removeAttribute("data-aia-loading");let x=u||r&&a,b=i.querySelector(".magicx-aia-pill-bar");x?(b||(b=document.createElement("div"),b.className="magicx-aia-pill-bar",b.setAttribute("data-aia-pillbar",""),i.insertBefore(b,i.firstChild)),$(b,o,0,m,!0,r)):b&&b.remove();let f=i.querySelector(".magicx-aia-grid");d?(f||(f=document.createElement("div"),f.className="magicx-aia-grid",i.appendChild(f)),Fe(f,t,n,l,c,e.listboxId,r)):f&&f.remove();let p=i.querySelector(".magicx-aia-skeleton-bars");if(r&&!d){if(!p){p=document.createElement("div"),p.className="magicx-aia-skeleton-bars",p.setAttribute("data-aia-skeleton-bars","");for(let g of Ne){let y=document.createElement("span");y.className="magicx-aia-skeleton-bar",y.style.width=`${g}px`,p.appendChild(y)}i.appendChild(p)}}else p&&p.remove()}function Fe(i,e,t,n,s,r,o){let a=e.map(d=>d.text).join("\0"),l=i.dataset.optionsKey??"",c=i.dataset.loading??"",m=o?"1":"0",u=a!==l||c!==m;if(i.dataset.optionsKey=a,i.dataset.loading=m,u){let d=document.createDocumentFragment();for(let h=0;h<e.length;h++){let x=e[h],b=He(x,h,t,n,s,r,o);d.appendChild(b)}i.innerHTML="",i.appendChild(d)}else{let d=i.querySelectorAll(".magicx-aia-option");for(let h=0;h<d.length;h++){let x=d[h],b=h===t&&!o;x.setAttribute("aria-selected",String(b)),b?x.classList.add("magicx-aia-option--highlighted"):x.classList.remove("magicx-aia-option--highlighted")}}}function He(i,e,t,n,s,r,o){let a=document.createElement("div");a.id=`${r}-option-${e}`,a.setAttribute("role","option"),a.setAttribute("data-aia-option",""),o&&a.setAttribute("data-aia-loading",""),a.setAttribute("aria-selected",String(e===t&&!o)),a.tabIndex=o||!i.is_tappable?-1:0;let l=["magicx-aia-option"];e===t&&!o&&l.push("magicx-aia-option--highlighted"),i.is_tappable?l.push("magicx-aia-option--tappable"):l.push("magicx-aia-option--non-tappable"),a.className=l.join(" ");let c=document.createElement("div");c.className="magicx-aia-streaks",a.appendChild(c);let m=document.createElement("div");m.className="magicx-aia-streaks-vert",a.appendChild(m);let u=document.createElement("span");if(u.className="magicx-aia-option-content",u.textContent=i.icon?`${i.icon} ${i.text}`:i.text,i.tag){let d=document.createElement("span");d.className="magicx-aia-option-tag",d.textContent=i.tag,u.appendChild(d)}return a.appendChild(u),!o&&i.is_tappable&&(a.addEventListener("click",()=>{a.classList.add("magicx-aia-option--pressed"),n(i),setTimeout(()=>a.classList.remove("magicx-aia-option--pressed"),500)}),a.addEventListener("mouseenter",()=>s(e))),a}function xe(i,e){let t=U(e.listboxId);return i.appendChild(t),{dropdown:t}}function z(i,e,t){W(i.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:n=>t.store.set({activeDropdownIndex:n}),onPillClick:t.setActivePill})}function be(i){let{input:e,segments:t,newParamId:n,editingParamId:s,placeholderText:r,isFocused:o}=i,a=t.length===0;e.dataset.aiaEmpty=a?"true":"false",a&&r?e.dataset.placeholder=r:delete e.dataset.placeholder;let l=t.map(f=>`${f.type}:${f.value}`).join("\0"),c=e.dataset.segKey??"",m=e.dataset.newParamId??"",u=e.dataset.editingParamId??"";if(l===c&&(n??"")===m&&(s??"")===u)return;let d=o?C(e):null;e.dataset.segKey=l,e.dataset.newParamId=n??"",e.dataset.editingParamId=s??"";let h=e.ownerDocument??document,x=h.createDocumentFragment(),b=0;for(let f of t)if(b+=f.value.length,f.type==="completed"){let p=h.createElement("strong");p.dataset.seg="completed",p.dataset.paramId=f.param.id;let g=f.param.id===n,y=f.param.id===s,v=["magicx-aia-segment","magicx-aia-segment--completed"];g&&v.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),y&&v.push("magicx-aia-segment--editing"),p.className=v.join(" "),p.textContent=f.value,x.appendChild(p)}else x.appendChild(h.createTextNode(f.value));e.replaceChildren(x),e.dataset.aiaTextLength=String(b),d!=null&&S(e,Math.max(0,Math.min(d,b)))}var Be='<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 Ke(){let i=document.createElement("div");return i.setAttribute("contenteditable","plaintext-only"),i.contentEditable==="plaintext-only"}function ye(i,e){let{listboxId:t}=e,n=U(t);i.appendChild(n);let s=document.createElement("div");s.className="magicx-aia-input-wrapper",i.appendChild(s);let r=document.createElement("div");r.className="magicx-aia-editor",r.setAttribute("data-aia-editor",""),s.appendChild(r);let o=document.createElement("div");o.className="magicx-aia-input",o.setAttribute("data-aia-input",""),o.setAttribute("contenteditable",Ke()?"plaintext-only":"true"),o.setAttribute("role","combobox"),o.setAttribute("aria-autocomplete","list"),o.setAttribute("aria-haspopup","listbox"),o.setAttribute("aria-controls",t),o.setAttribute("aria-expanded","false"),o.setAttribute("spellcheck","true"),o.setAttribute("enterkeyhint","send"),r.appendChild(o);let a=document.createElement("span");a.className="magicx-aia-pill-list-container",a.setAttribute("data-aia-pill-list-container",""),r.appendChild(a);let l=null,c=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=Be,s.appendChild(l),c=l):e.submitButton!==null&&(c=e.submitButton,c.hasAttribute("data-aia-submit")||c.setAttribute("data-aia-submit",""),s.appendChild(c));let m=new AbortController,{signal:u}=m,d=!1,h=0,x=()=>{let p=j(o),y=p.length>0&&p[0]!==p[0].toUpperCase()?p[0].toUpperCase()+p.slice(1):p;e.handleChange(y)},b=()=>{let p=(o.ownerDocument??document).getSelection();if(!p||p.rangeCount===0)return null;let g=p.anchorNode;return!g||!o.contains(g)?null:(g.nodeType===Node.ELEMENT_NODE?g:g.parentElement)?.closest('strong[data-seg="completed"][data-param-id]')?.dataset.paramId??null};s.addEventListener("click",p=>{p.target?.closest("[data-aia-pill]")||o.focus()},{signal:u}),o.addEventListener("input",()=>{d||(h=performance.now(),x(),e.handleCaretAfterInput(C(o)))},{signal:u});let f=o.ownerDocument??document;return f.addEventListener("selectionchange",()=>{let p=f.getSelection();if(!p||p.rangeCount===0||!o.contains(p.anchorNode))return;let g=b(),y=e.store.get().editingParam?.id??null;if(g&&g!==y){e.startEditingParam(g);return}performance.now()-h<50||e.handleCaretMove(C(o))},{signal:u}),o.addEventListener("compositionstart",()=>{d=!0},{signal:u}),o.addEventListener("compositionend",()=>{d=!1,x()},{signal:u}),o.addEventListener("beforeinput",p=>{let g=p,y=g.inputType;if(y==="insertParagraph"||y==="insertLineBreak"||y==="insertFromDrop"){p.preventDefault();return}if(y.startsWith("insert")||y.startsWith("delete")){let v=y.startsWith("delete")?"":g.data??"";e.replaceEditingRange(v)&&p.preventDefault()}},{signal:u}),o.addEventListener("paste",p=>{p.preventDefault();let g=(p.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!g)return;let y=o.ownerDocument??document,v=y.getSelection();if(!v||v.rangeCount===0)return;let P=v.getRangeAt(0);if(!o.contains(P.startContainer))return;P.deleteContents();let L=y.createTextNode(g);P.insertNode(L),P.setStartAfter(L),P.collapse(!0),v.removeAllRanges(),v.addRange(P),x()},{signal:u}),o.addEventListener("keydown",p=>e.handleKeyDown(p),{signal:u}),o.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:u}),o.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:u}),c&&c.addEventListener("click",p=>{let g=e.store.get();if(!(!!g.text||g.completedParams.length>0)||!e.onSubmit)return;p.stopPropagation();let{rawQuery:v,completedParams:P}=T(g.text,g.completedParams);e.onSubmit({query:g.text.trim(),raw_query:v,completed_params:P}),e.afterSubmit?.()},{signal:u}),e.autoFocus!==!1&&o.focus(),{input:o,inlinePillContainer:a,dropdown:n,submitButton:l,abort:m}}function V(i,e,t){let{input:n,inlinePillContainer:s,dropdown:r,submitButton:o}=i,{pillPlacement:a,setActivePill:l,selectOption:c,store:m}=t;n.setAttribute("aria-expanded",String(e.isDropdownOpen));let u=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(u?n.setAttribute("aria-activedescendant",u):n.removeAttribute("aria-activedescendant"),o){let f=!!e.text||e.completedParams.length>0;o.disabled=!f}let d=n.dataset.newParamId??"",h=e.newParamId!==null&&e.newParamId!==d;if(be({input:n,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused}),a==="inline"){let f=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;f||e.actionableSuggestions.length>0?$(s,e.actionableSuggestions,0,l,!1,f):G(s)}else G(s);h?(n.focus(),S(n,e.caretOffset??e.text.length)):e.isFocused&&j(n)!==e.text&&S(n,e.text.length);let x=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:null,b=x??e.actionableSuggestions[0];W(r,{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:x?[x]:e.actionableSuggestions,showPills:a==="dropdown",onSelect:c,onHighlight:f=>m.set({activeDropdownIndex:f}),onPillClick:l})}function X(i){let e=i,t=new Set;return{get:()=>e,set:n=>{let s=typeof n=="function"?n(e):n,r={...e,...s},o=e;e=r;for(let a of t)a(r,o)},subscribe:n=>(t.add(n),()=>{t.delete(n)})}}var J=!1;function ve(){if(J||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){J=!0;return}J=!0;let i=document.createElement("style");i.setAttribute("data-magicx-aia",""),i.textContent=qe,document.head.appendChild(i)}var qe=`/* ===================================================================
1
+ function v(n,e){let t=n,i={},r=[];for(let s of e){let o=(i[s.type]??0)+1;i[s.type]=o;let l=`{{${s.type.toUpperCase().replace(/\s+/g,"_")}_${o}}}`,c=t.indexOf(s.text);c!==-1&&(t=t.slice(0,c)+l+t.slice(c+s.text.length)),r.push({...s,placeholder:l})}return{rawQuery:t,completedParams:r}}function A(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function E(n,e,t){let i=n.slice(e);if(t||e===0||n[e-1]===" ")return i;let r=i.indexOf(" ");return r===-1?"":i.slice(r+1)}function re(n,e){let t=n.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let i=t.split(" "),r=e.toLowerCase();for(let s=0;s<i.length;s++){let o=i.slice(s).join(" ");if(r.startsWith(o.toLowerCase())){let a=t.length-o.length;return n.length-a}}return 0}function w(n,e){if(!n)return[];let t=e.trimStart();if(!t)return n;let i=t.toLowerCase();return n.filter(r=>!r.is_tappable||r.text.toLowerCase().includes(i))}function I(n,e){if(!n)return null;let t=e.trim();if(!t)return null;let i=t.toLowerCase();return n.find(r=>r.is_tappable&&r.text.toLowerCase()===i)??null}var M=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 oe(n,e){let t=[],i=0;for(let s of e){let o=n.indexOf(s.text,i);o!==-1&&(o>i&&t.push({type:"text",value:n.slice(i,o)}),t.push({type:"completed",value:s.text,param:s}),i=o+s.text.length)}let r=n.slice(i);return r&&t.push({type:"text",value:r}),t}function se(n,e){let t=[],i=[],r=0;for(let s of e){let o=n.indexOf(s.text,r);o===-1?i.push(s):(t.push(s),r=o+s.text.length)}return{valid:t,invalid:i}}var L=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 Re="https://api.ai-autocomplete.com",k=`${Re}/api/suggest`,ae=new WeakMap;function D(n){return n?.type==="accessToken"}function _e(n){if(!(!n||D(n)))return n}function R(n){let e=ae.get(n.getAccessToken);return e||(e=new L(n),ae.set(n.getAccessToken,e)),e}function _(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function N(n){let e=_e(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}function Ne(n){return(n??k).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function Fe(n){return D(n)?`Bearer ${await R(n).getToken()}`:N(n)}async function le(n){try{let e=Ne(n.apiConfig?.endpoint),t=_(n.apiConfig),i=await Fe(n.apiConfig);i&&(t.Authorization=i);let r=JSON.stringify({source:n.source,session_id:n.sessionId,type:n.type,at:new Date().toISOString(),query_data:n.queryData});await fetch(e,{method:"POST",headers:t,body:r})}catch{}}var He="0.1.42",ce=!1;function Be(){return crypto.randomUUID()}function Ke(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.text},kind:n.kind}}function Qe(n,e,t,i){let r=e.find(o=>o.type==="contact"&&o.metadata?.contact_account_count)?.metadata?.contact_account_count,s=typeof r=="number"?r:void 0;return{data:{raw_query:n,completed_params:e.map(o=>Ke(o,t)),...s!=null&&{contact_account_count:s}},meta:{request_id:Be(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:He,session_id:i}}}async function de(n,e,t,i,r){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:r})}async function ue(n,e,t){let i=t.apiConfig,r=!t.maskCompletedText,s=Qe(n,e,r,t.sessionId),o=_(i),a=i?.endpoint??k,l=JSON.stringify(s);if(D(i)){let d=R(i),m=await d.getToken(),b=await de(a,o,m,l,t.signal);if(b.status===401){let g=await d.getToken(!0);b=await de(a,o,g,l,t.signal)}if(!b.ok)throw new Error(`API error: ${b.status} ${b.statusText}`);return b.json()}let c=N(i);!c&&!ce&&(ce=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),c&&(o.Authorization=c);let u=await fetch(a,{method:"POST",headers:o,body:l,signal:t.signal});if(!u.ok)throw new Error(`API error: ${u.status} ${u.statusText}`);return u.json()}function pe(n,e){return e?n.map(t=>{let i=e[t.type];if(!i)return t;let r=i("");if(r.length===0)return t;let s=new Set(r.map(a=>a.text)),o=(t.options??[]).filter(a=>!s.has(a.text));return{...t,options:[...r,...o]}}):n}var $e=100,Ue=300,qe=2,F=class{constructor(e,t,i,r,s,o,a={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=r;this.getOnError=s;this.getSessionId=o;this.callbacks=a;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,s=this.store.get().text.length;this.store.set({isLoading:!0,error:null});try{let o=await ue(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig()});if(r!==this.fetchVersion)return;let a=pe(o.data.suggestions??[],this.getOptionOverrides()),l=o.data.input??[],c=l[l.length-1],u=this.store.get().text,d,m;if(c?.state==="in_progress"){m=!0;let f=u.toLowerCase().lastIndexOf(c.text.toLowerCase());d=f!==-1?f:s}else m=!1,d=s;let g=a.filter(f=>f.type!=="placeholder")[0],h=null;if(g){let f=E(u,d,m),p=I(g.options,f);p&&(h={id:crypto.randomUUID(),placeholder:"",type:g.type,text:p.text,kind:p.kind,suggestionType:g.type,suggestionPlaceholder:g.text,options:g.options??[],metadata:p.metadata},a=a.filter(x=>x!==g),this.callbacks.onAutoMatch?.({active:g,matched:p,rawQuery:e}))}this.store.set(f=>({suggestions:a,isLoading:!1,isReady:o.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:d,filterInProgress:m,...h?{completedParams:[...f.completedParams,h]}:{}}))}catch(o){if(r===this.fetchVersion){let a=o instanceof Error?o:new Error(String(o));this.store.set({error:a,isLoading:!1}),this.getOnError()?.(a)}}}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 s=r.suggestions.filter(x=>x.type==="placeholder").map(x=>x.text).join(" "),o=A(r.text,r.filterBase,s),a=E(r.text,o,r.filterInProgress),c=r.suggestions.filter(x=>x.type!=="placeholder")[0],d=(c?w(c.options,a):[]).filter(x=>x.is_tappable),m=c?I(c.options,a)!==null:!1,b=a.trim().length>0;if(d.length>0&&!m&&b||r.completedParams.length===0&&r.text.length>0&&s.length>0&&s.toLowerCase().startsWith(r.text.toLowerCase()))return!1;let{rawQuery:g,completedParams:h}=v(r.text,r.completedParams),f=g.length<r.lastRawQuery.length,p=Math.abs(g.length-r.lastRawQuery.length);return f||p>=i?(this.doFetch(g,h),!0):!1};this.debounceTimer=setTimeout(()=>{t(qe)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},$e),this.slowDebounceTimer=setTimeout(()=>t(1),Ue)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var ge='[contenteditable="false"]',O;function We(){if(O!==void 0)return O;let n=globalThis.Intl.Segmenter;if(!n)return O=null,null;try{O=new n(void 0,{granularity:"grapheme"})}catch{O=null}return O??null}function H(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(ge))return!0;t=t.parentNode}return!1}function B(n){return(n.ownerDocument??document).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return H(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function X(n){let e=B(n),t="",i=e.nextNode();for(;i;)t+=i.data,i=e.nextNode();return t}function fe(n){let e=B(n),t=0,i=e.nextNode();for(;i;)t+=i.data.length,i=e.nextNode();return t}function C(n){let e=(n.ownerDocument??document).getSelection();if(!e||e.rangeCount===0)return null;let t=e.anchorNode,i=e.anchorOffset;if(!t||!n.contains(t))return null;if(t.nodeType===Node.ELEMENT_NODE){let r=t;if(H(r,n)&&r!==n)return null;let s=0;for(let o=0;o<i&&o<r.childNodes.length;o++)s+=he(r.childNodes[o],n);return s+me(r,n)}return t.nodeType!==Node.TEXT_NODE||H(t,n)?null:me(t,n)+i}function he(n,e){if(n.nodeType===Node.TEXT_NODE)return H(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(ge))return 0;let i=0;for(let r of Array.from(t.childNodes))i+=he(r,e);return i}function me(n,e){let t=B(e),i=0,r=t.nextNode();for(;r;){if(r===n||n.nodeType===Node.ELEMENT_NODE&&n.contains(r))return i;i+=r.data.length,r=t.nextNode()}return i}function P(n,e){let t=n.ownerDocument??document,i=t.getSelection();if(!i)return;let r=Math.max(0,Math.min(e,fe(n))),s=B(n),o=0,a=null,l=0,c=s.nextNode(),u=null;for(;c;){let m=c.data.length;if(r<o+m){a=c,l=r-o;break}if(r===o+m){let b=s.nextNode();b?(a=b,l=0):(a=c,l=m);break}o+=m,u=c,c=s.nextNode()}let d=t.createRange();if(a){let m=a.parentElement?.closest('strong[data-seg="completed"]');m&&m!==n&&n.contains(m)?l===0?d.setStartBefore(m):l===a.data.length?d.setStartAfter(m):d.setStart(a,l):d.setStart(a,l)}else u?d.setStart(u,u.data.length):d.setStart(n,0);d.collapse(!0),i.removeAllRanges(),i.addRange(d)}function xe(n){let e=C(n);return e==null?!1:e>=fe(n)}function be(n,e){if(e<=0)return 0;let t=We();if(!t)return e-1;let i=n.slice(0,e),r=0;for(let{index:s}of t.segment(i))s<e&&(r=s);return r}function ye(n){return n instanceof HTMLTextAreaElement||n instanceof HTMLInputElement?n.selectionStart!=null&&n.selectionStart===n.value.length:n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?xe(n):!1}function je(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?C(n):null}var K=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:r}=this.ctx,s=this.getEffectiveColumns(),o=r(),a=this.getTappableIndices(s);switch(e.key){case"ArrowDown":{let l=ye(e.target),c=!!t.editingParam;if(!l&&!c&&t.activeDropdownIndex<0)break;if(e.preventDefault(),!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:a[0]??0});break}if(a.length===0)return;let u=a.indexOf(t.activeDropdownIndex),d=u<a.length-1?u+1:0;this.store.set({activeDropdownIndex:a[d]});break}case"ArrowUp":{if(a.length===0||t.activeDropdownIndex<0)break;if(e.preventDefault(),t.activeDropdownIndex<s){this.store.set({activeDropdownIndex:-1});break}let l=a.indexOf(t.activeDropdownIndex),c=l>0?l-1:a.length-1;this.store.set({activeDropdownIndex:a[c]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%s<s-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 c=e.target.closest("[data-aia-input]")??e.target,u=t.editingTail;this.ctx.exitEditMode?.(),P(c,u);break}ye(e.target)&&t.actionableSuggestions.length>1&&(e.preventDefault(),this.pillsSetActivePill(1));break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%s>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,c=t.editingAnchor;this.ctx.exitEditMode?.(),P(l,c);break}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let l=je(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,i);else if(o){let{rawQuery:l,completedParams:c}=v(t.text,t.completedParams);o({query:t.text.trim(),raw_query:l,completed_params:c}),this.ctx.afterSubmit?.()}break}case"Tab":{let l=!t.text&&!!t.placeholderText,c=t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable;if(l&&!c){e.preventDefault();let u=t.placeholderText;if(this.store.set(d=>({text:u,filterBase:u.length,suggestions:d.suggestions.filter(m=>m.type!=="placeholder")})),e.target instanceof HTMLElement){let d=e.target.closest("[data-aia-input]")??e.target;queueMicrotask(()=>P(d,u.length))}}else if(c)e.preventDefault(),this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i);else if(t.isDropdownOpen){let u=t.filteredOptions.findIndex(d=>d.is_tappable);u>=0&&(e.preventDefault(),this.clickOrSelect(u,t.filteredOptions,i))}break}case"Escape":{if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){let l=e.target.closest("[data-aia-input]")??e.target,c=t.editingTail;this.ctx.exitEditMode?.(),P(l,c)}this.store.set({activeDropdownIndex:-1});break}}}getTappableIndices(e){let i=this.store.get().filteredOptions.map((s,o)=>s.is_tappable?o:-1).filter(s=>s!==-1),r=Array.from({length:e},()=>[]);for(let s of i)r[s%e].push(s);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(a=>a.type!=="placeholder");if(e<0||e>=i.length)return;let r=i[e],s=i.filter((a,l)=>l!==e),o=t.suggestions.filter(a=>a.type==="placeholder");this.store.set({suggestions:[...o,r,...s],pillTapped:!0,activeDropdownIndex:-1})}};var Q=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),i=t.suggestions.filter(a=>a.type!=="placeholder");if(e<0||e>=i.length)return;let r=i[e],s=i.filter((a,l)=>l!==e),o=t.suggestions.filter(a=>a.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:a}=v(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:a,selectedPill:r.text,otherPills:s.map(l=>l.text)})}this.store.set({suggestions:[...o,r,...s],pillTapped:!0,activeDropdownIndex:-1})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};function Se(n,e){let t=e.dropdownTrigger??"auto",i=e.closeDropdownOnBlur??!0,r=n.filteredOptionsLength>0;if(n.inEditMode){let s=i?n.isFocused:!0;return r&&s}if(t==="auto"){let s=i?n.isFocused:!0,o=n.text.replace(/\s+$/,"").length,a=n.caretOffset==null||n.caretOffset>=o;return(r||n.isLoading)&&s&&a}return t==="manual"?(r||n.isLoading)&&n.pillTapped:!1}function ve(n,e){let t=oe(n.text,n.completedParams),i=n.suggestions.filter(g=>g.type!=="placeholder"),r=i[0],s=r?e.optionOverrides?.[r.type]:void 0,o=n.suggestions.filter(g=>g.type==="placeholder").map(g=>g.text).join(" "),a=A(n.text,Math.min(n.filterBase,n.text.length),o),c=n.lastRawQuery!==""||a>0?E(n.text,a,n.filterInProgress):"",u=r?s?s(c.trim()):r.options??[]:[],d=n.editingParam!=null&&n.editingAnchor!=null,m;if(d&&n.editingParam&&n.editingAnchor!=null){let g=n.editingParam.id,h=n.completedParams.some(x=>x.id===g),f=n.caretOffset??n.editingAnchor,p=h?"":n.text.slice(n.editingAnchor,f);m=w(n.editingParam.options,p)}else m=w(u,c);e.showNonTappableOptions===!1&&(m=m.filter(g=>g.is_tappable));let b=Se({inEditMode:d,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:i,filteredOptions:m,placeholderText:o,isDropdownOpen:b}}function $(n){return n.mode==="fresh"?Ge(n):Ve(n)}function Ge(n){let{text:e,completedParams:t,suggestions:i,filterBase:r,filterInProgress:s}=n,a=i.filter(S=>S.type!=="placeholder")[0];if(!a?.options)return null;let l=i.filter(S=>S.type==="placeholder").map(S=>S.text).join(" "),c=A(e,r,l),u=E(e,c,s),d=I(a.options,u);if(!d)return null;let m=d.text.toLowerCase(),b=e.toLowerCase().lastIndexOf(m),g=b>=0?b:Math.max(0,e.length-d.text.length),h=g+d.text.length,f=e.slice(g,h),x=h<e.length&&e[h]===" "?h+1:h,y={id:crypto.randomUUID(),placeholder:"",type:a.type,text:f,kind:d.kind,suggestionType:a.type,suggestionPlaceholder:a.text,options:a.options??[],metadata:d.metadata};return{patch:{text:e,completedParams:[...t,y],suggestions:i.filter(S=>S!==a),filterBase:x,newParamId:y.id,caretOffset:x,activeDropdownIndex:-1},caretPos:x}}function Ve(n){let{text:e,completedParams:t,editingParam:i,editingAnchor:r,editingTail:s}=n;if(t.some(y=>y.id===i.id))return null;let o=e.slice(r,s),a=I(i.options,o);if(!a)return null;let l=a.text.toLowerCase(),c=o.toLowerCase().lastIndexOf(l),u=r+Math.max(0,c),d=u+a.text.length,m=e.slice(u,d),g=d<e.length&&e[d]===" "?d+1:d,h={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:m,kind:a.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:a.metadata},f=t.length,p=0;for(let y=0;y<t.length;y++){let S=e.indexOf(t[y].text,p);if(S!==-1){if(S>=g){f=y;break}p=S+t[y].text.length}}let x=[...t];return x.splice(f,0,h),{patch:{text:e,completedParams:x,newParamId:h.id,filterBase:g,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:g,activeDropdownIndex:-1},caretPos:g}}var U=class{constructor(e){this.deps=e}start(e){let t=this.deps.store.get();if(t.editingParam?.id===e)return;let i=t.completedParams.find(o=>o.id===e);if(!i)return;let r=0,s=-1;for(let o of t.completedParams){let a=t.text.indexOf(o.text,r);if(a!==-1){if(o.id===e){s=a;break}r=a+o.text.length}}s<0||this.deps.store.set({editingParam:i,editingAnchor:s,editingTail:s+i.text.length,caretOffset:s+i.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(),i=t.editingParam,r=t.editingAnchor,s=t.editingTail;if(!i||r==null||s==null||!t.completedParams.some(l=>l.id===i.id))return!1;let o=t.text.slice(0,r)+e+t.text.slice(s),a=r+e.length;return this.deps.store.set(l=>({text:o,completedParams:l.completedParams.filter(c=>c.id!==i.id),editingTail:a,caretOffset:a,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(a),this.tryPromote(),!0}caretAfterInput(e){let t=this.deps.store.get(),i={caretOffset:e};t.editingParam&&t.editingAnchor!=null&&e!=null&&(e<t.editingAnchor?(i.editingParam=null,i.editingAnchor=null,i.editingTail=null,i.activeDropdownIndex=-1):t.editingTail!=null&&(i.editingTail=Math.max(t.editingTail,e))),this.deps.store.set(i),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(),i=t.editingParam,r=t.editingAnchor,s=t.editingTail;if(!i||r==null||s==null)return;this.deps.fireTelemetry("option",{raw_query:v(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:i.options.filter(p=>p.text!==e.text).map(p=>p.text)});let o=t.text.slice(0,r),a=t.text.slice(s),l=r===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,c=a.length===0||a[0]!==" ",u=c?`${l} `:l,d=o+u+a,m=r+u.length+(c?0:1),b={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:l,kind:e.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:e.metadata},g=t.completedParams.findIndex(p=>p.id===i.id),h=t.completedParams.filter(p=>p.id!==i.id),f=g>=0?Math.min(g,h.length):h.length;h.splice(f,0,b),this.deps.store.set({text:d,completedParams:h,newParamId:b.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=$({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 Pe="data-aia-key";function q(n,e,t){let i=new Map;for(let o of Array.from(n.children)){let a=o.getAttribute(Pe);a!=null&&i.set(a,o)}let r=new Set,s=[];for(let o=0;o<e.length;o++){let a=e[o],l=t.keyOf(a,o);r.add(l);let c=i.get(l);c||(c=t.create(a,o),c.setAttribute(Pe,l)),t.update?.(c,a,o),n.children[o]!==c&&n.insertBefore(c,n.children[o]??null),s.push(c)}for(let[o,a]of i)r.has(o)||a.remove();return s}var Te=[125,69];function Ce(n){return n===0?.4:n===1?.3:.15}function W(n,e,t,i,r=!1,s=!1){let o=n.querySelector(".magicx-aia-pill-list");if(o||(o=document.createElement("span"),o.className="magicx-aia-pill-list",n.appendChild(o)),s&&e.length===0){o.setAttribute("data-aia-pill-list-loading",""),o.innerHTML="";for(let a=0;a<Te.length;a++){let l=Te[a],c=document.createElement("span");c.setAttribute("data-aia-pill-skeleton",""),c.className=`magicx-aia-pill magicx-aia-pill--skeleton${r?" magicx-aia-pill--rounded":""}`,c.style.width=`${l}px`,c.style.opacity=String(Ce(a)),o.appendChild(c)}return}s?o.setAttribute("data-aia-pill-list-loading",""):o.removeAttribute("data-aia-pill-list-loading");for(let a of o.querySelectorAll("[data-aia-pill-skeleton]"))a.remove();q(o,e,{keyOf:a=>`${a.type}-${a.text}`,create:a=>{let l=document.createElement("button");return l.type="button",l.tabIndex=-1,l.setAttribute("data-aia-pill",""),l.setAttribute("contenteditable","false"),l.textContent=a.text,l.addEventListener("mousedown",c=>c.preventDefault()),l},update:(a,l,c)=>{let u=a,d=["magicx-aia-pill"];r&&d.push("magicx-aia-pill--rounded"),c===t&&!s&&d.push("magicx-aia-pill--active"),s&&d.push("magicx-aia-pill--skeleton"),u.className=d.join(" "),u.style.width="",u.style.opacity=String(Ce(c)),s?(u.setAttribute("data-aia-loading",""),u.disabled=!0,u.onclick=null):(u.removeAttribute("data-aia-loading"),u.disabled=!1,u.onclick=()=>i(c))}})}function Y(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var ze=[159,119,164];function j(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 G(n,e){let{filteredOptions:t,activeIndex:i,isOpen:r,isLoading:s,pills:o,showPills:a,onSelect:l,onHighlight:c,onPillClick:u}=e,d=a&&o.length>0,m=t.length>0;r&&(m||d||s)?n.classList.add("magicx-aia-dropdown--visible"):n.classList.remove("magicx-aia-dropdown--visible"),s?n.setAttribute("data-aia-loading",""):n.removeAttribute("data-aia-loading");let g=d||s&&a,h=n.querySelector(".magicx-aia-pill-bar");g?(h||(h=document.createElement("div"),h.className="magicx-aia-pill-bar",h.setAttribute("data-aia-pillbar",""),n.insertBefore(h,n.firstChild)),W(h,o,0,u,!0,s)):h&&h.remove();let f=n.querySelector(".magicx-aia-grid");m?(f||(f=document.createElement("div"),f.className="magicx-aia-grid",n.appendChild(f)),Xe(f,t,i,l,c,e.listboxId,s)):f&&f.remove();let p=n.querySelector(".magicx-aia-skeleton-bars");if(s&&!m){if(!p){p=document.createElement("div"),p.className="magicx-aia-skeleton-bars",p.setAttribute("data-aia-skeleton-bars","");for(let x of ze){let y=document.createElement("span");y.className="magicx-aia-skeleton-bar",y.style.width=`${x}px`,p.appendChild(y)}n.appendChild(p)}}else p&&p.remove()}function Xe(n,e,t,i,r,s,o){let a=o?"1":"0";q(n,e,{keyOf:l=>`${l.text}\0${a}`,create:l=>Ye(l,o),update:(l,c,u)=>{let d=u===t&&!o;l.id=`${s}-option-${u}`,l.dataset.aiaIndex=String(u),l.setAttribute("aria-selected",String(d)),l.classList.toggle("magicx-aia-option--highlighted",d),!o&&c.is_tappable?(l.onclick=()=>{l.classList.add("magicx-aia-option--pressed"),i(c),setTimeout(()=>l.classList.remove("magicx-aia-option--pressed"),500)},l.onmouseenter=()=>{let m=Number.parseInt(l.dataset.aiaIndex??"-1",10);m>=0&&r(m)}):(l.onclick=null,l.onmouseenter=null)}})}function Ye(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 i=["magicx-aia-option"];n.is_tappable?i.push("magicx-aia-option--tappable"):i.push("magicx-aia-option--non-tappable"),t.className=i.join(" ");let r=document.createElement("div");r.className="magicx-aia-streaks",t.appendChild(r);let s=document.createElement("div");s.className="magicx-aia-streaks-vert",t.appendChild(s);let o=document.createElement("span");if(o.className="magicx-aia-option-content",o.textContent=n.icon?`${n.icon} ${n.text}`:n.text,n.tag){let a=document.createElement("span");a.className="magicx-aia-option-tag",a.textContent=n.tag,o.appendChild(a)}return t.appendChild(o),t}function Ee(n,e){let t=j(e.listboxId);return n.appendChild(t),{dropdown:t}}function J(n,e,t){G(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:i=>t.store.set({activeDropdownIndex:i}),onPillClick:t.setActivePill})}function we(n){let{input:e,segments:t,newParamId:i,editingParamId:r,placeholderText:s,isFocused:o}=n,a=t.length===0;e.dataset.aiaEmpty=a?"true":"false",a&&s?e.dataset.placeholder=s:delete e.dataset.placeholder;let l=t.map(f=>`${f.type}:${f.value}`).join("\0"),c=e.dataset.segKey??"",u=e.dataset.newParamId??"",d=e.dataset.editingParamId??"";if(l===c&&(i??"")===u&&(r??"")===d)return;let m=o?C(e):null;e.dataset.segKey=l,e.dataset.newParamId=i??"",e.dataset.editingParamId=r??"";let b=e.ownerDocument??document,g=b.createDocumentFragment(),h=0;for(let f of t)if(h+=f.value.length,f.type==="completed"){let p=b.createElement("strong");p.dataset.seg="completed",p.dataset.paramId=f.param.id;let x=f.param.id===i,y=f.param.id===r,S=["magicx-aia-segment","magicx-aia-segment--completed"];x&&S.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),y&&S.push("magicx-aia-segment--editing"),p.className=S.join(" "),p.textContent=f.value,g.appendChild(p)}else g.appendChild(b.createTextNode(f.value));e.replaceChildren(g),e.dataset.aiaTextLength=String(h),m!=null&&P(e,Math.max(0,Math.min(m,h)))}var Je='<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 Ze(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function Ae(n,e){let{listboxId:t}=e,i=j(t);n.appendChild(i);let r=document.createElement("div");r.className="magicx-aia-input-wrapper",n.appendChild(r);let s=document.createElement("div");s.className="magicx-aia-editor",s.setAttribute("data-aia-editor",""),r.appendChild(s);let o=document.createElement("div");o.className="magicx-aia-input",o.setAttribute("data-aia-input",""),o.setAttribute("contenteditable",Ze()?"plaintext-only":"true"),o.setAttribute("role","combobox"),o.setAttribute("aria-autocomplete","list"),o.setAttribute("aria-haspopup","listbox"),o.setAttribute("aria-controls",t),o.setAttribute("aria-expanded","false"),o.setAttribute("spellcheck","true"),o.setAttribute("enterkeyhint","send"),s.appendChild(o);let a=document.createElement("span");a.className="magicx-aia-pill-list-container",a.setAttribute("data-aia-pill-list-container",""),s.appendChild(a);let l=null,c=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=Je,r.appendChild(l),c=l):e.submitButton!==null&&(c=e.submitButton,c.hasAttribute("data-aia-submit")||c.setAttribute("data-aia-submit",""),r.appendChild(c));let u=new AbortController,{signal:d}=u,m=!1,b=0,g=()=>{let p=X(o),y=p.length>0&&p[0]!==p[0].toUpperCase()?p[0].toUpperCase()+p.slice(1):p;e.handleChange(y)},h=()=>{let p=(o.ownerDocument??document).getSelection();if(!p||p.rangeCount===0)return null;let x=p.anchorNode;return!x||!o.contains(x)?null:(x.nodeType===Node.ELEMENT_NODE?x:x.parentElement)?.closest('strong[data-seg="completed"][data-param-id]')?.dataset.paramId??null};r.addEventListener("click",p=>{p.target?.closest("[data-aia-pill]")||o.focus()},{signal:d}),o.addEventListener("input",()=>{m||(b=performance.now(),g(),e.handleCaretAfterInput(C(o)))},{signal:d});let f=o.ownerDocument??document;return f.addEventListener("selectionchange",()=>{let p=f.getSelection();if(!p||p.rangeCount===0||!o.contains(p.anchorNode))return;let x=h(),y=e.store.get().editingParam?.id??null;if(x&&x!==y){e.startEditingParam(x);return}performance.now()-b<50||e.handleCaretMove(C(o))},{signal:d}),o.addEventListener("compositionstart",()=>{m=!0},{signal:d}),o.addEventListener("compositionend",()=>{m=!1,g()},{signal:d}),o.addEventListener("beforeinput",p=>{let x=p,y=x.inputType;if(y==="insertParagraph"||y==="insertLineBreak"||y==="insertFromDrop"){p.preventDefault();return}if(y.startsWith("insert")||y.startsWith("delete")){let S=y.startsWith("delete")?"":x.data??"";e.replaceEditingRange(S)&&p.preventDefault()}},{signal:d}),o.addEventListener("paste",p=>{p.preventDefault();let x=(p.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!x)return;let y=o.ownerDocument??document,S=y.getSelection();if(!S||S.rangeCount===0)return;let T=S.getRangeAt(0);if(!o.contains(T.startContainer))return;T.deleteContents();let ie=y.createTextNode(x);T.insertNode(ie),T.setStartAfter(ie),T.collapse(!0),S.removeAllRanges(),S.addRange(T),g()},{signal:d}),o.addEventListener("keydown",p=>e.handleKeyDown(p),{signal:d}),o.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:d}),o.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:d}),c&&c.addEventListener("click",p=>{let x=e.store.get();if(!(!!x.text||x.completedParams.length>0)||!e.onSubmit)return;p.stopPropagation();let{rawQuery:S,completedParams:T}=v(x.text,x.completedParams);e.onSubmit({query:x.text.trim(),raw_query:S,completed_params:T}),e.afterSubmit?.()},{signal:d}),e.autoFocus!==!1&&o.focus(),{input:o,inlinePillContainer:a,dropdown:i,submitButton:l,abort:u}}function Z(n,e,t){let{input:i,inlinePillContainer:r,dropdown:s,submitButton:o}=n,{pillPlacement:a,setActivePill:l,selectOption:c,store:u}=t;i.setAttribute("aria-expanded",String(e.isDropdownOpen));let d=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(d?i.setAttribute("aria-activedescendant",d):i.removeAttribute("aria-activedescendant"),o){let f=!!e.text||e.completedParams.length>0;o.disabled=!f}let m=i.dataset.newParamId??"",b=e.newParamId!==null&&e.newParamId!==m;if(we({input:i,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused}),a==="inline"){let f=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;f||e.actionableSuggestions.length>0?W(r,e.actionableSuggestions,0,l,!1,f):Y(r)}else Y(r);b?(i.focus(),P(i,e.caretOffset??e.text.length)):e.isFocused&&X(i)!==e.text&&P(i,e.text.length);let g=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:null,h=g??e.actionableSuggestions[0];G(s,{suggestions:h?[{...h,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:a==="dropdown",onSelect:c,onHighlight:f=>u.set({activeDropdownIndex:f}),onPillClick:l})}function Ie(n,e){let t=n.actionableSuggestions[0];if(!t)return null;let i=n.filterBase,r=n.text.slice(0,i),s=r.length===0&&n.text.length===0,o=r.length===0&&n.text.length>0&&n.placeholderText.length>0&&n.placeholderText.toLowerCase().startsWith(n.text.toLowerCase());(s||o)&&n.placeholderText&&(r=`${n.placeholderText} `);let a=re(r,e.text);a>0&&(r=r.slice(0,r.length-a));let l=r.length>0&&r[r.length-1]!==" ",c=`${r}${l?" ":""}${e.text} `,u=(s||o)&&c.length>0?c[0].toUpperCase()+c.slice(1):c,d=u.toLowerCase().lastIndexOf(e.text.toLowerCase()),m=d>=0?u.slice(d,d+e.text.length):e.text,b={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,b],newParamId:b.id,caretOffset:u.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:g>0,inSelectionAnimation:!0},telemetry:{selectedOption:e.text,otherOptions:n.filteredOptions.filter(h=>h.text!==e.text).map(h=>h.text)},consumedSuggestion:t,remainingActionable:g}}function ee(n){let e=n,t=new Set;return{get:()=>e,set:i=>{let r=typeof i=="function"?i(e):i,s={...e,...r},o=e;e=s;for(let a of t)a(s,o)},subscribe:i=>(t.add(i),()=>{t.delete(i)})}}function Oe(n,e){let t,i,r=s=>(s!==t&&(t=s,i=e(s)),i);return{get:()=>{let s=n.get();return{...s,...r(s)}},set:s=>{typeof s=="function"?n.set(o=>{let a={...o,...r(o)};return s(a)}):n.set(s)},subscribe:s=>n.subscribe((o,a)=>{let l={...a,...r(a)},c={...o,...r(o)};s(c,l)})}}var te=!1;function De(){if(te||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){te=!0;return}te=!0;let n=document.createElement("style");n.setAttribute("data-magicx-aia",""),n.textContent=et,document.head.appendChild(n)}var et=`@layer layout {
2
+ .aia-stack {
3
+ display: flex;
4
+ flex-direction: column;
5
+ gap: var(--aia-stack-space, 0.5rem);
6
+ }
7
+ .aia-stack[data-align="start"] {
8
+ align-items: start;
9
+ }
10
+ .aia-stack[data-align="center"] {
11
+ align-items: center;
12
+ }
13
+ .aia-stack[data-align="end"] {
14
+ align-items: end;
15
+ }
16
+ /* data-align="stretch" is the flex default \u2014 no rule needed. */
17
+ }
18
+
19
+ @layer layout {
20
+ .aia-cluster {
21
+ display: flex;
22
+ flex-wrap: wrap;
23
+ gap: var(--aia-cluster-gap, 0.5rem);
24
+ }
25
+ .aia-cluster[data-nowrap] {
26
+ flex-wrap: nowrap;
27
+ }
28
+ .aia-cluster[data-align="start"] {
29
+ align-items: start;
30
+ }
31
+ .aia-cluster[data-align="center"] {
32
+ align-items: center;
33
+ }
34
+ .aia-cluster[data-align="end"] {
35
+ align-items: end;
36
+ }
37
+ .aia-cluster[data-align="baseline"] {
38
+ align-items: baseline;
39
+ }
40
+ .aia-cluster[data-justify="start"] {
41
+ justify-content: start;
42
+ }
43
+ .aia-cluster[data-justify="center"] {
44
+ justify-content: center;
45
+ }
46
+ .aia-cluster[data-justify="end"] {
47
+ justify-content: end;
48
+ }
49
+ .aia-cluster[data-justify="between"] {
50
+ justify-content: space-between;
51
+ }
52
+ .aia-cluster[data-justify="around"] {
53
+ justify-content: space-around;
54
+ }
55
+ }
56
+
57
+ @layer layout {
58
+ .aia-grid {
59
+ display: grid;
60
+ grid-template-columns: repeat(auto-fit, minmax(min(var(--aia-grid-min), 100%), 1fr));
61
+ gap: var(--aia-grid-gap, 0);
62
+ }
63
+ }
64
+
65
+ /* ===================================================================
2
66
  Vanilla core styles \u2014 stable BEM class names (magicx-aia-*)
3
67
  Auto-injected at runtime on first instantiation.
4
68
  =================================================================== */
@@ -805,5 +869,5 @@ function T(i,e){let t=i,n={},s=[];for(let r of e){let o=(n[r.type]??0)+1;n[r.typ
805
869
  animation-duration: 0s !important;
806
870
  transition-duration: 0s !important;
807
871
  }
808
- `;var Qe=0;function $e(){return`:ac-${++Qe}:`}var Se=500;function Te(){return{text:"",completedParams:[],suggestions:[],activeDropdownIndex:-1,newParamId:null,isLoading:!1,isReady:!1,error:null,segments:[],actionableSuggestions:[],filteredOptions:[],placeholderText:"",isDropdownOpen:!1,filterBase:0,filterInProgress:!1,pillTapped:!1,skipNextFetch:!1,lastRawQuery:"",isFocused:!1,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:null,inSelectionAnimation:!1}}var Y=class{constructor(e,t={}){this.store=X(Te());this._listboxId=$e();this.modeController=null;this.unsubscribers=[];this.derivedInProgress=!1;this.domRefs=null;this.dropdownRefs=null;this.externalListeners=new Set;this.sessionId=crypto.randomUUID();this.container=e,this.opts=t,this.renderMode=t.renderMode??"full",t.value!==void 0&&this.store.set({text:t.value}),t.completedParams!==void 0&&this.store.set({completedParams:t.completedParams}),this.pillsController=new Q(this.store,{onPillSelected:({rawQuery:n,selectedPill:s,otherPills:r})=>{this.fireTelemetry("pill",{raw_query:n,selected_pill:s,other_pills:r})}}),this.fetchController=new H(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.opts.onError,()=>this.sessionId,{onAutoMatch:({active:n,matched:s,rawQuery:r})=>{this.fireTelemetry("option",{raw_query:r,selected_option:s.text,other_options:(n.options??[]).filter(o=>o.text!==s.text).map(o=>o.text)})}}),this.keyboardController=new q(this.store,{columns:t.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.opts.onSubmit,afterSubmit:this.renderMode==="full"?()=>this.reset():void 0,selectOption:n=>this.selectOption(n),removeParamAtCaret:n=>this.removeParamAtCaret(n),exitEditMode:()=>this.exitEditMode()}),this.unsubscribers.push(this.store.subscribe((n,s)=>{this.recomputeDerived(n,s)})),this.unsubscribers.push(this.store.subscribe((n,s)=>{n.text!==s.text&&this.opts.onChange?.(n.text),n.completedParams!==s.completedParams&&this.opts.onParamsChange?.(n.completedParams),n.isFocused!==s.isFocused&&(n.isFocused?this.opts.onFocus?.():this.opts.onBlur?.()),this.opts.onStateChange?.(n)})),this.renderMode!=="headless"&&(ve(),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({...Te(),skipNextFetch:!0}),this.sessionId=crypto.randomUUID(),this.fetchController.doFetch("",[])}destroy(){this.fetchController.dispose(),this.modeController?.destroy(),this.newParamTimer&&clearTimeout(this.newParamTimer),this.suggestionRemovalTimer&&clearTimeout(this.suggestionRemovalTimer),this.selectionAnimationTimer&&clearTimeout(this.selectionAnimationTimer),this.externalListeners.clear();for(let e of this.unsubscribers)e();this.unsubscribers=[],this.domRefs?.abort.abort(),this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}setValue(e){this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e)}removeLastParam(){this.pillsController.removeLastParam()}removeParamAtCaret(e){let t=this.store.get(),{text:n,completedParams:s}=t,r=0;for(let o=0;o<s.length;o++){let a=s[o],l=n.indexOf(a.text,r);if(l===-1)continue;let c=l,m=l+a.text.length;if(e>c&&e<=m){let u=me(n,e),d=n.slice(0,u)+n.slice(e),h=s.filter((x,b)=>b!==o);return this.store.set(x=>({text:d,filterBase:Math.min(x.filterBase,d.length),completedParams:h,pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(u),!0}r=m}return!1}scheduleSetCursor(e){queueMicrotask(()=>{let t=this.domRefs;t?S(t.input,e):this.opts.setCursor?.(e)})}clearNewParamId(){this.store.set({newParamId:null})}startEditingParam(e){let t=this.store.get();if(t.editingParam?.id===e)return;let n=t.completedParams.find(o=>o.id===e);if(!n)return;let s=0,r=-1;for(let o of t.completedParams){let a=t.text.indexOf(o.text,s);if(a!==-1){if(o.id===e){r=a;break}s=a+o.text.length}}r<0||this.store.set({editingParam:n,editingAnchor:r,editingTail:r+n.text.length,caretOffset:r+n.text.length,activeDropdownIndex:-1})}replaceEditingRange(e){let t=this.store.get(),n=t.editingParam,s=t.editingAnchor,r=t.editingTail;if(!n||s==null||r==null||!t.completedParams.some(l=>l.id===n.id))return!1;let o=t.text.slice(0,s)+e+t.text.slice(r),a=s+e.length;return this.store.set(l=>({text:o,completedParams:l.completedParams.filter(c=>c.id!==n.id),editingTail:a,caretOffset:a,activeDropdownIndex:-1})),this.scheduleSetCursor(a),this.maybePromoteEditExactMatch(),!0}exitEditMode(){this.store.get().editingParam&&this.store.set({editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1})}handleCaretAfterInput(e){let t=this.store.get(),n={caretOffset:e};t.editingParam&&t.editingAnchor!=null&&e!=null&&(e<t.editingAnchor?(n.editingParam=null,n.editingAnchor=null,n.editingTail=null,n.activeDropdownIndex=-1):t.editingTail!=null&&(n.editingTail=Math.max(t.editingTail,e))),this.store.set(n),this.maybePromoteEditExactMatch()}handleCaretMove(e){let t=this.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null&&e!=null&&(e<t.editingAnchor||e>t.editingTail)){this.store.set({caretOffset:e,editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1});return}this.store.set({caretOffset:e})}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}handleTextChange(e){this.handleChange(e)}handleKeyDown(e){this.keyboardController.handleKeyDown(e)}setFocused(e){this.store.get().isFocused!==e&&this.store.set({isFocused:e})}subscribe(e){return this.externalListeners.add(e),()=>{this.externalListeners.delete(e)}}getState(){return this.store.get()}get listboxId(){return this._listboxId}get isReady(){return this.store.get().isReady}on(e,t){switch(e){case"submit":return this.opts.onSubmit=t,()=>{this.opts.onSubmit=void 0};case"error":return this.opts.onError=t,()=>{this.opts.onError=void 0};case"change":return this.opts.onChange=t,()=>{this.opts.onChange=void 0};case"paramsChange":return this.opts.onParamsChange=t,()=>{this.opts.onParamsChange=void 0};case"stateChange":return this.opts.onStateChange=t,()=>{this.opts.onStateChange=void 0};case"focus":return this.opts.onFocus=t,()=>{this.opts.onFocus=void 0};case"blur":return this.opts.onBlur=t,()=>{this.opts.onBlur=void 0};default:return()=>{}}}update(e){Object.assign(this.opts,e),e.mode!==void 0&&this.modeController?.setMode(e.mode),e.optionsPosition!==void 0&&(this.container.dataset.optionsPosition=e.optionsPosition),e.animations!==void 0&&(this.container.dataset.animations=e.animations?"on":"off"),e.pillPlacement!==void 0&&(this.container.dataset.pillPlacement=e.pillPlacement,this.store.set({})),(e.dropdownTrigger!==void 0||e.closeDropdownOnBlur!==void 0)&&this.store.set({}),e.value!==void 0&&this.store.set({text:e.value}),e.completedParams!==void 0&&this.store.set({completedParams:e.completedParams})}selectOption(e){let t=this.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null){this.selectOptionInEditMode(e);return}let n=t.actionableSuggestions[0];if(!n)return;let{rawQuery:s}=T(t.text,t.completedParams);this.fireTelemetry("option",{raw_query:s,selected_option:e.text,other_options:t.filteredOptions.filter(p=>p.text!==e.text).map(p=>p.text)});let r=t.filterBase,o=t.text.slice(0,r),a=o.length===0&&t.text.length===0,l=o.length===0&&t.text.length>0&&t.placeholderText.length>0&&t.placeholderText.toLowerCase().startsWith(t.text.toLowerCase());(a||l)&&t.placeholderText&&(o=`${t.placeholderText} `);let c=Z(o,e.text);c>0&&(o=o.slice(0,o.length-c));let m=o.length>0&&o[o.length-1]!==" ",u=`${o}${m?" ":""}${e.text} `,d=(a||l)&&u.length>0?u[0].toUpperCase()+u.slice(1):u,h=d.toLowerCase().lastIndexOf(e.text.toLowerCase()),x=h>=0?d.slice(h,h+e.text.length):e.text,b={id:crypto.randomUUID(),placeholder:"",type:n.type,text:x,kind:e.kind,suggestionType:n.type,suggestionPlaceholder:n.text,options:n.options??[],metadata:e.metadata},f=t.actionableSuggestions.length-1;this.store.set(p=>({text:d,filterBase:d.length,completedParams:[...p.completedParams,b],newParamId:b.id,caretOffset:d.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:f>0,inSelectionAnimation:!0})),this.startSelectionAnimationTimer(),this.suggestionRemovalTimer&&clearTimeout(this.suggestionRemovalTimer),f>0&&(this.suggestionRemovalTimer=window.setTimeout(()=>{this.store.set(p=>({suggestions:p.suggestions.filter(g=>g!==n)}))},Se))}startSelectionAnimationTimer(){this.selectionAnimationTimer&&clearTimeout(this.selectionAnimationTimer),this.selectionAnimationTimer=window.setTimeout(()=>{this.store.set({inSelectionAnimation:!1})},Se)}selectOptionInEditMode(e){let t=this.store.get(),n=t.editingParam,s=t.editingAnchor,r=t.editingTail;if(!n||s==null||r==null)return;this.fireTelemetry("option",{raw_query:T(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:n.options.filter(p=>p.text!==e.text).map(p=>p.text)});let o=t.text.slice(0,s),a=t.text.slice(r),l=s===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,c=a.length===0||a[0]!==" ",m=c?`${l} `:l,u=o+m+a,d=s+m.length+(c?0:1),h={id:crypto.randomUUID(),placeholder:"",type:n.suggestionType,text:l,kind:e.kind,suggestionType:n.suggestionType,suggestionPlaceholder:n.suggestionPlaceholder,options:n.options,metadata:e.metadata},x=t.completedParams.findIndex(p=>p.id===n.id),b=t.completedParams.filter(p=>p.id!==n.id),f=x>=0?Math.min(x,b.length):b.length;b.splice(f,0,h),this.store.set({text:u,completedParams:b,newParamId:h.id,filterBase:d,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:d,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.startSelectionAnimationTimer(),this.scheduleSetCursor(d)}fireTelemetry(e,t){let n=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");ie({source:n,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}recomputeDerived(e,t){if(this.derivedInProgress)return;this.derivedInProgress=!0;let n=ee(e.text,e.completedParams),s=e.suggestions.filter(g=>g.type!=="placeholder"),r=s[0],o=r?this.opts.optionOverrides?.[r.type]:void 0,a=e.suggestions.filter(g=>g.type==="placeholder").map(g=>g.text).join(" "),l=O(e.text,Math.min(e.filterBase,e.text.length),a),m=e.lastRawQuery!==""||l>0?w(e.text,l,e.filterInProgress):"",u=r?o?o(m.trim()):r.options??[]:[],d=e.editingParam!=null&&e.editingAnchor!=null,h;if(d&&e.editingParam&&e.editingAnchor!=null){let g=e.editingParam.id,y=e.completedParams.some(L=>L.id===g),v=e.caretOffset??e.editingAnchor,P=y?"":e.text.slice(e.editingAnchor,v);h=I(e.editingParam.options,P)}else h=I(u,m);let x=this.opts.dropdownTrigger??"auto",b=this.opts.closeDropdownOnBlur??!0,f=!1;if(d){let g=b?e.isFocused:!0;f=h.length>0&&g}else if(x==="auto"){let g=b?e.isFocused:!0,y=e.text.replace(/\s+$/,"").length,v=e.caretOffset==null||e.caretOffset>=y;f=(h.length>0||e.isLoading)&&g&&v}else x==="manual"&&(f=(h.length>0||e.isLoading)&&e.pillTapped);this.store.set({segments:n,actionableSuggestions:s,filteredOptions:h,placeholderText:a,isDropdownOpen:f}),this.derivedInProgress=!1;let p=this.store.get();for(let g of this.externalListeners)g(p)}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 M(this.container,this.opts.mode??"auto")}buildAndRenderFull(){let e=this,t={store:this.store,listboxId:this.listboxId,get pillPlacement(){return e.opts.pillPlacement??"inline"},get onSubmit(){return e.opts.onSubmit},afterSubmit:()=>e.reset(),submitButton:this.opts.submitButton,autoFocus:this.opts.autoFocus??!0,selectOption:n=>this.selectOption(n),setActivePill:n=>this.pillsController.setActivePill(n),handleKeyDown:n=>this.keyboardController.handleKeyDown(n),handleChange:n=>this.handleChange(n),startEditingParam:n=>this.startEditingParam(n),handleCaretAfterInput:n=>this.handleCaretAfterInput(n),handleCaretMove:n=>this.handleCaretMove(n),replaceEditingRange:n=>this.replaceEditingRange(n)};this.domRefs=ye(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&V(this.domRefs,this.store.get(),t)}),V(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=xe(this.container,e),this.subscribeBatchedRender(()=>{this.dropdownRefs&&z(this.dropdownRefs,this.store.get(),e)}),z(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:n,invalid:s}=te(e,t.completedParams);s.length>0&&this.store.set({completedParams:n}),this.maybePromoteExactMatch(e)}maybePromoteExactMatch(e){let t=this.store.get(),s=t.suggestions.filter(g=>g.type!=="placeholder")[0];if(!s?.options)return;let r=t.suggestions.filter(g=>g.type==="placeholder").map(g=>g.text).join(" "),o=O(e,t.filterBase,r),a=w(e,o,t.filterInProgress),l=E(s.options,a);if(!l)return;let c=l.text.toLowerCase(),m=e.toLowerCase().lastIndexOf(c),u=m>=0?m:Math.max(0,e.length-l.text.length),d=u+l.text.length,h=e.slice(u,d),x=e,f=d<e.length&&e[d]===" "?d+1:d,p={id:crypto.randomUUID(),placeholder:"",type:s.type,text:h,kind:l.kind,suggestionType:s.type,suggestionPlaceholder:s.text,options:s.options??[],metadata:l.metadata};this.store.set(g=>({text:x,completedParams:[...g.completedParams,p],suggestions:g.suggestions.filter(y=>y!==s),filterBase:f,newParamId:p.id,caretOffset:f,activeDropdownIndex:-1}))}maybePromoteEditExactMatch(){let e=this.store.get(),t=e.editingParam,n=e.editingAnchor,s=e.editingTail;if(!t||n==null||s==null||e.completedParams.some(y=>y.id===t.id))return;let r=e.text.slice(n,s),o=E(t.options,r);if(!o)return;let a=o.text.toLowerCase(),l=r.toLowerCase().lastIndexOf(a),c=n+Math.max(0,l),m=c+o.text.length,u=e.text.slice(c,m),d=e.text,x=m<e.text.length&&e.text[m]===" "?m+1:m,b={id:crypto.randomUUID(),placeholder:"",type:t.suggestionType,text:u,kind:o.kind,suggestionType:t.suggestionType,suggestionPlaceholder:t.suggestionPlaceholder,options:t.options,metadata:o.metadata},f=e.completedParams.length,p=0;for(let y=0;y<e.completedParams.length;y++){let v=d.indexOf(e.completedParams[y].text,p);if(v!==-1){if(v>=x){f=y;break}p=v+e.completedParams[y].text.length}}let g=[...e.completedParams];g.splice(f,0,b),this.store.set(()=>({text:d,completedParams:g,newParamId:b.id,filterBase:x,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:x,activeDropdownIndex:-1})),this.scheduleSetCursor(x)}};export{Y as AIAutocomplete,X as createStore};
872
+ `;var V=class{constructor(){this.listeners={}}on(e,t){let i=(...s)=>t(...s),r=this.listeners[e];return r||(r=new Set,this.listeners[e]=r),r.add(i),()=>{this.listeners[e]?.delete(i)}}emit(e,...t){let i=this.listeners[e];if(i)for(let r of i)r(...t)}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var z=class{constructor(){this.timers=new Map}schedule(e,t,i){this.clear(e);let r=setTimeout(()=>{this.timers.delete(e),t()},i);this.timers.set(e,r)}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 tt="newParam",Me="suggestionRemoval",nt="selectionAnimation",it=650,rt=0;function ot(){return`:ac-${++rt}:`}var Le=500;function ke(){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 ne=class{constructor(e,t={}){this.inputStore=ee(ke());this._listboxId=ot();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new z;this.emitter=new V;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=Oe(this.inputStore,i=>ve(i,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 Q(this.store,{onPillSelected:({rawQuery:i,selectedPill:r,otherPills:s})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:r,other_pills:s})}}),this.reEdit=new U({store:this.store,scheduleSetCursor:i=>this.scheduleSetCursor(i),fireTelemetry:(i,r)=>this.fireTelemetry(i,r),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer()}),this.fetchController=new F(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.emitter.hasListeners("error")?this.emitError:void 0,()=>this.sessionId,{onAutoMatch:({active:i,matched:r,rawQuery:s})=>{this.fireTelemetry("option",{raw_query:s,selected_option:r.text,other_options:(i.options??[]).filter(o=>o.text!==r.text).map(o=>o.text)})}}),this.keyboardController=new K(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:i=>this.selectOption(i),removeParamAtCaret:i=>this.removeParamAtCaret(i),exitEditMode:()=>this.exitEditMode()}),this.unsubscribers.push(this.store.subscribe((i,r)=>{i.text!==r.text&&this.emitter.emit("change",i.text),i.completedParams!==r.completedParams&&this.emitter.emit("paramsChange",i.completedParams),i.isFocused!==r.isFocused&&(i.isFocused?this.emitter.emit("focus"):this.emitter.emit("blur")),this.emitter.emit("stateChange",i)})),this.unsubscribers.push(this.store.subscribe(()=>this.maybeExitReEditOnNoMatch())),this.renderMode!=="headless"&&(De(),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({...ke(),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:i,completedParams:r}=t,s=0;for(let o=0;o<r.length;o++){let a=r[o],l=i.indexOf(a.text,s);if(l===-1)continue;let c=l,u=l+a.text.length;if(e>c&&e<=u){let d=be(i,e),m=i.slice(0,d)+i.slice(e),b=r.filter((g,h)=>h!==o);return this.store.set(g=>({text:m,filterBase:Math.min(g.filterBase,m.length),completedParams:b,pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(d),!0}s=u}return!1}scheduleSetCursor(e){queueMicrotask(()=>{let t=this.domRefs;t?(t.input.focus(),P(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 i=Ie(t,e);if(i&&(this.fireTelemetry("option",{raw_query:v(t.text,t.completedParams).rawQuery,selected_option:i.telemetry.selectedOption,other_options:i.telemetry.otherOptions}),this.store.set(i.patch),this.startSelectionAnimationTimer(),this.timers.clear(Me),i.remainingActionable>0)){let r=i.consumedSuggestion;this.timers.schedule(Me,()=>{this.store.set(s=>({suggestions:s.suggestions.filter(o=>o!==r)}))},Le)}}startSelectionAnimationTimer(){this.timers.schedule(nt,()=>this.store.set({inSelectionAnimation:!1}),Le)}fireTelemetry(e,t){let i=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");le({source:i,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 M(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:i=>this.selectOption(i),setActivePill:i=>this.pillsController.setActivePill(i),handleKeyDown:i=>this.keyboardController.handleKeyDown(i),handleChange:i=>this.handleChange(i),startEditingParam:i=>this.startEditingParam(i),handleCaretAfterInput:i=>this.handleCaretAfterInput(i),handleCaretMove:i=>this.handleCaretMove(i),replaceEditingRange:i=>this.replaceEditingRange(i)};this.domRefs=Ae(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&Z(this.domRefs,this.store.get(),t)}),Z(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=Ee(this.container,e),this.subscribeBatchedRender(()=>{this.dropdownRefs&&J(this.dropdownRefs,this.store.get(),e)}),J(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(tt,()=>this.store.set({newParamId:null}),it)}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:r}=se(e,t.completedParams);r.length>0&&this.store.set({completedParams:i}),this.maybePromoteExactMatch(e)}maybeExitReEditOnNoMatch(){let e=this.store.get();if(!e.editingParam||e.editingAnchor==null||e.completedParams.some(a=>a.id===e.editingParam?.id))return;let t=e.caretOffset??e.editingAnchor,i=e.text.slice(e.editingAnchor,t);if(w(e.editingParam.options,i).some(a=>a.is_tappable))return;this.reEdit.exit();let{rawQuery:s,completedParams:o}=v(e.text,e.completedParams);this.fetchController.doFetch(s,o)}maybePromoteExactMatch(e){let t=this.store.get(),i=$({mode:"fresh",text:e,completedParams:t.completedParams,suggestions:t.suggestions,filterBase:t.filterBase,filterInProgress:t.filterInProgress});i&&this.store.set(i.patch)}};export{ne as AIAutocomplete,ee as createStore};
809
873
  //# sourceMappingURL=index.mjs.map