@magicx-eng/ai-autocomplete-vanilla 0.1.10 → 0.1.11

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,4 @@
1
- function v(o,e,t){let i=o.slice(e);if(t||e===0||o[e-1]===" ")return i;let n=i.indexOf(" ");return n===-1?"":i.slice(n+1)}function B(o,e){let t=o.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let i=t.split(" "),n=e.toLowerCase();for(let s=0;s<i.length;s++){let r=i.slice(s).join(" ");if(n.startsWith(r.toLowerCase())){let p=t.length-r.length;return o.length-p}}return 0}function C(o,e){if(!o)return[];let t=e.trimStart();if(!t)return o;let i=t.toLowerCase();return o.filter(n=>!n.is_tappable||n.text.toLowerCase().includes(i))}function L(o,e){if(!o)return null;let t=e.trim();if(!t)return null;let i=t.toLowerCase();return o.find(n=>n.is_tappable&&n.text.toLowerCase()===i)??null}var w=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 H(o,e){let t=[],i=0;for(let s of e){let r=o.indexOf(s.text,i);r!==-1&&(r>i&&t.push({type:"text",value:o.slice(i,r)}),t.push({type:"completed",value:s.text,param:s}),i=r+s.text.length)}let n=o.slice(i);return n&&t.push({type:"text",value:n}),t}function N(o,e){let t=[],i=[],n=0;for(let s of e){let r=o.indexOf(s.text,n);r===-1?i.push(s):(t.push(s),n=r+s.text.length)}return{valid:t,invalid:i}}var P=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 J="0.1.34",K=!1;function Z(){return crypto.randomUUID()}function ee(o,e){return{placeholder:o.placeholder,type:o.type,...e&&{text:o.text},kind:o.kind}}function Q(o){return o?.type==="accessToken"}function te(o){if(!(!o||Q(o)))return o}var $=new WeakMap;function ie(o){let e=$.get(o.getAccessToken);return e||(e=new P(o),$.set(o.getAccessToken,e)),e}function oe(o,e,t,i){let n=e.find(r=>r.type==="contact"&&r.metadata?.contact_account_count)?.metadata?.contact_account_count,s=typeof n=="number"?n:void 0;return{data:{raw_query:o,completed_params:e.map(r=>ee(r,t)),...s!=null&&{contact_account_count:s}},meta:{request_id:Z(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:J,session_id:i}}}function se(o){return{"Content-Type":"application/json",...o?.appIdentifier&&{"X-App-Identifier":o.appIdentifier},...o?.headers}}async function q(o,e,t,i,n){return fetch(o,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:n})}async function U(o,e,t){let i=t.apiConfig,n=!t.maskCompletedText,s=oe(o,e,n,t.sessionId),r=se(i),p=i?.endpoint??"https://api.ai-autocomplete.com/api/suggest",a=JSON.stringify(s);if(Q(i)){let u=ie(i),m=await u.getToken(),g=await q(p,r,m,a,t.signal);if(g.status===401){let b=await u.getToken(!0);g=await q(p,r,b,a,t.signal)}if(!g.ok)throw new Error(`API error: ${g.status} ${g.statusText}`);return g.json()}let l=te(i),c=l?.apiKey??"";if(!c&&!K&&(K=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),c){let u=l?.authScheme??"Bearer";r.Authorization=u==="Basic"?`Basic ${btoa(c)}`:`Bearer ${c}`}let d=await fetch(p,{method:"POST",headers:r,body:a,signal:t.signal});if(!d.ok)throw new Error(`API error: ${d.status} ${d.statusText}`);return d.json()}function y(o,e){let t=o,i={},n=[];for(let s of e){let r=(i[s.type]??0)+1;i[s.type]=r;let a=`{{${s.type.toUpperCase().replace(/\s+/g,"_")}_${r}}}`,l=t.indexOf(s.text);l!==-1&&(t=t.slice(0,l)+a+t.slice(l+s.text.length)),n.push({...s,placeholder:a})}return{rawQuery:t,completedParams:n}}function j(o,e){return e?o.map(t=>{let i=e[t.type];if(!i)return t;let n=i("");if(n.length===0)return t;let s=new Set(n.map(p=>p.text)),r=(t.options??[]).filter(p=>!s.has(p.text));return{...t,options:[...n,...r]}}):o}var ne=100,re=300,ae=2,O=class{constructor(e,t,i,n,s,r){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=n;this.getOnError=s;this.getSessionId=r;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 n=++this.fetchVersion,s=this.store.get(),r=s.text.length;s.suggestions.some(a=>a.type!=="placeholder")||this.store.set({isLoading:!0}),this.store.set({error:null});try{let a=await U(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig()});if(n!==this.fetchVersion)return;let l=j(a.data.suggestions??[],this.getOptionOverrides()),c=a.data.input??[],d=c[c.length-1],u=this.store.get().text,m,g;if(d?.state==="in_progress"){g=!0;let x=u.toLowerCase().lastIndexOf(d.text.toLowerCase());m=x!==-1?x:r}else g=!1,m=r;let h=l.filter(x=>x.type!=="placeholder")[0],f=null;if(h){let x=v(u,m,g),S=L(h.options,x);S&&(f={id:crypto.randomUUID(),placeholder:"",type:h.type,text:S.text,kind:S.kind,suggestionType:h.type,suggestionPlaceholder:h.text,options:h.options??[],metadata:S.metadata},l=l.filter(Y=>Y!==h))}this.store.set(x=>({suggestions:l,isLoading:!1,isReady:a.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:m,filterInProgress:g,...f?{completedParams:[...x.completedParams,f]}:{}}))}catch(a){if(n===this.fetchVersion){let l=a instanceof Error?a:new Error(String(a));this.store.set({error:l,isLoading:!1}),this.getOnError()?.(l)}}}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}let t=i=>{let n=this.store.get();if(!n.text&&n.completedParams.length===0)return this.doFetch("",[]),!0;let s=v(n.text,n.filterBase,n.filterInProgress),p=n.suggestions.filter(h=>h.type!=="placeholder")[0],l=(p?C(p.options,s):[]).filter(h=>h.is_tappable),c=p?L(p.options,s)!==null:!1,d=s.trim().length>0;if(l.length>0&&!c&&d)return!1;if(n.completedParams.length===0&&n.text.length>0){let h=n.suggestions.filter(f=>f.type==="placeholder").map(f=>f.text).join(" ");if(h.length>0&&h.toLowerCase().startsWith(n.text.toLowerCase()))return!1}let{rawQuery:u,completedParams:m}=y(n.text,n.completedParams),g=u.length<n.lastRawQuery.length,b=Math.abs(u.length-n.lastRawQuery.length);return g||b>=i?(this.doFetch(u,m),!0):!1};this.debounceTimer=setTimeout(()=>{t(ae)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},ne),this.slowDebounceTimer=setTimeout(()=>t(1),re)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var T=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:n}=this.ctx,s=this.getEffectiveColumns(),r=n(),p=this.getTappableIndices(s);switch(e.key){case"ArrowDown":{let a=e.target;if(!(a.selectionStart!=null&&a.selectionStart===a.value.length)&&t.activeDropdownIndex<0)break;if(e.preventDefault(),!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:p[0]??0});break}if(p.length===0)return;let c=p.indexOf(t.activeDropdownIndex),d=c<p.length-1?c+1:0;this.store.set({activeDropdownIndex:p[d]});break}case"ArrowUp":{if(p.length===0||t.activeDropdownIndex<0)break;if(e.preventDefault(),t.activeDropdownIndex<s){this.store.set({activeDropdownIndex:-1});break}let a=p.indexOf(t.activeDropdownIndex),l=a>0?a-1:p.length-1;this.store.set({activeDropdownIndex:p[l]});break}case"ArrowRight":{if(t.activeDropdownIndex<0){let l=e.target;l.selectionStart!=null&&l.selectionStart===l.value.length&&t.actionableSuggestions.length>1&&(e.preventDefault(),this.pillsSetActivePill(1));break}if(t.activeDropdownIndex%s<s-1){let l=t.activeDropdownIndex+1;l<t.filteredOptions.length&&t.filteredOptions[l]?.is_tappable&&(e.preventDefault(),this.store.set({activeDropdownIndex:l}))}break}case"ArrowLeft":{if(t.activeDropdownIndex<0)break;if(t.activeDropdownIndex%s>0){let a=t.activeDropdownIndex-1;a>=0&&t.filteredOptions[a]?.is_tappable&&(e.preventDefault(),this.store.set({activeDropdownIndex:a}))}break}case"Enter":{if(e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable)this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i);else if(r){let{rawQuery:a,completedParams:l}=y(t.text,t.completedParams);r({query:t.text.trim(),raw_query:a,completed_params:l})}break}case"Tab":{let a=!t.text&&!!t.placeholderText,l=t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable;if(a&&!l){e.preventDefault();let c=t.suggestions.find(d=>d.type==="placeholder");c?this.store.set(d=>({text:t.placeholderText,filterBase:t.placeholderText.length,completedParams:[...d.completedParams,{id:crypto.randomUUID(),placeholder:"",type:c.type,text:t.placeholderText,kind:null,suggestionType:c.type,suggestionPlaceholder:c.text,options:c.options??[]}],suggestions:d.suggestions.filter(u=>u!==c)})):this.store.set({text:t.placeholderText,filterBase:t.placeholderText.length})}else if(l)e.preventDefault(),this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i);else if(t.isDropdownOpen){let c=t.filteredOptions.findIndex(d=>d.is_tappable);c>=0&&(e.preventDefault(),this.clickOrSelect(c,t.filteredOptions,i))}break}case"Escape":this.store.set({activeDropdownIndex:-1});break}}getTappableIndices(e){let i=this.store.get().filteredOptions.map((s,r)=>s.is_tappable?r:-1).filter(s=>s!==-1),n=Array.from({length:e},()=>[]);for(let s of i)n[s%e].push(s);return n.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 n=document.getElementById(`${i}-option-${e}`);n?n.click():this.ctx.selectOption(t[e])}pillsSetActivePill(e){let t=this.store.get(),i=t.suggestions.filter(p=>p.type!=="placeholder");if(e<0||e>=i.length)return;let n=i[e],s=i.filter((p,a)=>a!==e),r=t.suggestions.filter(p=>p.type==="placeholder");this.store.set({suggestions:[...r,n,...s],pillTapped:!0,activeDropdownIndex:-1})}};var I=class{constructor(e){this.store=e}setActivePill(e){let t=this.store.get(),i=t.suggestions.filter(p=>p.type!=="placeholder");if(e<0||e>=i.length)return;let n=i[e],s=i.filter((p,a)=>a!==e),r=t.suggestions.filter(p=>p.type==="placeholder");this.store.set({suggestions:[...r,n,...s],pillTapped:!0,activeDropdownIndex:-1})}removeLastParam(){let e=this.store.get();if(e.completedParams.length===0)return;let t=e.completedParams[e.completedParams.length-1],i={type:t.suggestionType,text:t.suggestionPlaceholder,required:!0,options:t.options};this.store.set(n=>({completedParams:n.completedParams.slice(0,-1),suggestions:[i,...n.suggestions],activeDropdownIndex:-1}))}};function le(o){return o===0?.4:o===1?.3:.15}function A(o,e,t,i,n=!1){let s=o.querySelector(".magicx-aia-pill-list");s||(s=document.createElement("span"),s.className="magicx-aia-pill-list",o.appendChild(s));let r=new Map;for(let a of s.querySelectorAll(".magicx-aia-pill"))r.set(a.dataset.pillKey??"",a);let p=new Set;for(let a=0;a<e.length;a++){let l=e[a],c=`${l.type}-${l.text}`;p.add(c);let d=r.get(c);d||(d=document.createElement("button"),d.type="button",d.dataset.pillKey=c,d.setAttribute("data-aia-pill",""),d.textContent=l.text),d.className=`magicx-aia-pill${n?" magicx-aia-pill--rounded":""}${a===t?" magicx-aia-pill--active":""}`,d.style.opacity=String(le(a)),d.onclick=()=>i(a),s.children[a]!==d&&s.insertBefore(d,s.children[a]??null)}for(let[a,l]of r)p.has(a)||l.remove()}function D(o){let e=document.createElement("div");return e.id=o,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",t=>t.preventDefault()),e}function E(o,e){let{filteredOptions:t,activeIndex:i,isOpen:n,pills:s,showPills:r,onSelect:p,onHighlight:a,onPillClick:l}=e,c=r&&s.length>0;n&&t.length>0||n&&c?o.classList.add("magicx-aia-dropdown--visible"):o.classList.remove("magicx-aia-dropdown--visible");let m=o.querySelector(".magicx-aia-pill-bar");c?(m||(m=document.createElement("div"),m.className="magicx-aia-pill-bar",m.setAttribute("data-aia-pillbar",""),o.insertBefore(m,o.firstChild)),A(m,s,0,l,!0)):m&&m.remove();let g=o.querySelector(".magicx-aia-grid");t.length>0?(g||(g=document.createElement("div"),g.className="magicx-aia-grid",o.appendChild(g)),ce(g,t,i,p,a,e.listboxId)):g&&(g.innerHTML="")}function ce(o,e,t,i,n,s){let r=e.map(l=>l.text).join("\0"),p=o.dataset.optionsKey??"",a=r!==p;if(o.dataset.optionsKey=r,a){let l=document.createDocumentFragment();for(let c=0;c<e.length;c++){let d=e[c],u=de(d,c,t,i,n,s);l.appendChild(u)}o.innerHTML="",o.appendChild(l)}else{let l=o.querySelectorAll(".magicx-aia-option");for(let c=0;c<l.length;c++){let d=l[c],u=c===t;d.setAttribute("aria-selected",String(u)),u?d.classList.add("magicx-aia-option--highlighted"):d.classList.remove("magicx-aia-option--highlighted")}}}function de(o,e,t,i,n,s){let r=document.createElement("div");r.id=`${s}-option-${e}`,r.setAttribute("role","option"),r.setAttribute("data-aia-option",""),r.setAttribute("aria-selected",String(e===t)),r.tabIndex=o.is_tappable?0:-1;let p=["magicx-aia-option"];e===t&&p.push("magicx-aia-option--highlighted"),o.is_tappable?p.push("magicx-aia-option--tappable"):p.push("magicx-aia-option--non-tappable"),r.className=p.join(" ");let a=document.createElement("div");a.className="magicx-aia-streaks",r.appendChild(a);let l=document.createElement("div");l.className="magicx-aia-streaks-vert",r.appendChild(l);let c=document.createElement("span");if(c.className="magicx-aia-option-content",c.textContent=o.icon?`${o.icon} ${o.text}`:o.text,o.tag){let d=document.createElement("span");d.className="magicx-aia-option-tag",d.textContent=o.tag,c.appendChild(d)}return r.appendChild(c),o.is_tappable&&(r.addEventListener("click",()=>{r.classList.add("magicx-aia-option--pressed"),i(o),setTimeout(()=>r.classList.remove("magicx-aia-option--pressed"),400)}),r.addEventListener("mouseenter",()=>n(e))),r}function V(o,e){let t=D(e.listboxId);return o.appendChild(t),{dropdown:t}}function M(o,e,t){E(o.dropdown,{suggestions:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,onSelect:t.selectOption,onHighlight:i=>t.store.set({activeDropdownIndex:i}),onPillClick:t.setActivePill})}function W(o,e,t,i,n){let s=o.querySelector(".magicx-aia-sizer-text"),r=o.querySelector(".magicx-aia-placeholder");if(i&&n){s&&(s.style.display="none"),r||(r=document.createElement("span"),r.className="magicx-aia-placeholder",o.insertBefore(r,o.firstChild)),r.style.display="",r.textContent=`${n} `,o.dataset.segmentKey="";return}r&&(r.style.display="none"),s||(s=document.createElement("span"),s.className="magicx-aia-sizer-text",o.insertBefore(s,o.firstChild)),s.style.display="",s.className=`magicx-aia-sizer-text${t?" magicx-aia-sizer-text--visible":""}`;let p=e.map(c=>`${c.type}:${c.value}`).join("\0"),a=o.dataset.segmentKey??"",l=o.dataset.newParamId??"";if(!(p===a&&(t??"")===l)){o.dataset.segmentKey=p,o.dataset.newParamId=t??"",s.innerHTML="";for(let c of e){let d=document.createElement("span");c.type==="completed"&&(c.param.id===t?d.className="magicx-aia-shimmer-revealed magicx-aia-shimmer-sweep":d.className="magicx-aia-segment magicx-aia-segment--completed"),d.textContent=c.value,s.appendChild(d)}e.length===0&&(s.textContent="\xA0")}}var pe='<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 z(o,e){let{listboxId:t}=e,i=D(t);o.appendChild(i);let n=document.createElement("div");n.className="magicx-aia-input-wrapper",o.appendChild(n);let s=document.createElement("div");s.className="magicx-aia-editor",s.setAttribute("data-aia-editor",""),n.appendChild(s);let r=document.createElement("div");r.className="magicx-aia-sizer",r.setAttribute("aria-hidden","true"),s.appendChild(r);let p=document.createElement("span");r.appendChild(document.createTextNode(" ")),r.appendChild(p);let a=document.createElement("textarea");a.className="magicx-aia-textarea",a.rows=1,a.setAttribute("role","combobox"),a.setAttribute("aria-autocomplete","list"),a.setAttribute("aria-controls",t),a.setAttribute("data-aia-textarea",""),s.appendChild(a);let l=null,c=null;return 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=pe,n.appendChild(l),c=l):e.submitButton!==null&&(c=e.submitButton,c.hasAttribute("data-aia-submit")||c.setAttribute("data-aia-submit",""),n.appendChild(c)),n.addEventListener("click",()=>a.focus()),a.addEventListener("input",()=>{let d=a.value,m=d.length>0&&d[0]!==d[0].toUpperCase()?d[0].toUpperCase()+d.slice(1):d;e.handleChange(m)}),a.addEventListener("keydown",d=>e.handleKeyDown(d)),a.addEventListener("focus",()=>e.store.set({isFocused:!0})),a.addEventListener("blur",()=>e.store.set({isFocused:!1})),c&&c.addEventListener("click",d=>{let u=e.store.get();if(!(!!u.text||u.completedParams.length>0)||!e.onSubmit)return;d.stopPropagation();let{rawQuery:g,completedParams:b}=y(u.text,u.completedParams);e.onSubmit({query:u.text.trim(),raw_query:g,completed_params:b})}),e.autoFocus!==!1&&a.focus(),{textarea:a,dropdown:i,sizer:r,submitButton:l,inlinePillContainer:p}}function k(o,e,t){let{textarea:i,dropdown:n,sizer:s,submitButton:r,inlinePillContainer:p}=o,{pillPlacement:a,setActivePill:l,selectOption:c,store:d}=t;i.value!==e.text&&(i.value=e.text),e.placeholderText?i.placeholder=e.placeholderText:i.removeAttribute("placeholder"),i.setAttribute("aria-expanded",String(e.isDropdownOpen));let u=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(u?i.setAttribute("aria-activedescendant",u):i.removeAttribute("aria-activedescendant"),e.newParamId?i.classList.add("magicx-aia-textarea--hidden"):i.classList.remove("magicx-aia-textarea--hidden"),r){let m=!!e.text||e.completedParams.length>0;r.disabled=!m}W(s,e.segments,e.newParamId,!e.text,e.placeholderText),a==="inline"?A(p,e.actionableSuggestions,0,l):p.innerHTML="",E(n,{suggestions:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:a==="dropdown",onSelect:c,onHighlight:m=>d.set({activeDropdownIndex:m}),onPillClick:l})}function R(o){let e=o,t=new Set;return{get:()=>e,set:i=>{let n=typeof i=="function"?i(e):i,s={...e,...n},r=e;e=s;for(let p of t)p(s,r)},subscribe:i=>(t.add(i),()=>{t.delete(i)})}}var _=!1;function G(){if(_||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){_=!0;return}_=!0;let o=document.createElement("style");o.setAttribute("data-magicx-aia",""),o.textContent=ue,document.head.appendChild(o)}var ue=`/* ===================================================================
1
+ function v(o,e,t){let i=o.slice(e);if(t||e===0||o[e-1]===" ")return i;let n=i.indexOf(" ");return n===-1?"":i.slice(n+1)}function B(o,e){let t=o.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let i=t.split(" "),n=e.toLowerCase();for(let s=0;s<i.length;s++){let r=i.slice(s).join(" ");if(n.startsWith(r.toLowerCase())){let p=t.length-r.length;return o.length-p}}return 0}function C(o,e){if(!o)return[];let t=e.trimStart();if(!t)return o;let i=t.toLowerCase();return o.filter(n=>!n.is_tappable||n.text.toLowerCase().includes(i))}function L(o,e){if(!o)return null;let t=e.trim();if(!t)return null;let i=t.toLowerCase();return o.find(n=>n.is_tappable&&n.text.toLowerCase()===i)??null}var w=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 H(o,e){let t=[],i=0;for(let s of e){let r=o.indexOf(s.text,i);r!==-1&&(r>i&&t.push({type:"text",value:o.slice(i,r)}),t.push({type:"completed",value:s.text,param:s}),i=r+s.text.length)}let n=o.slice(i);return n&&t.push({type:"text",value:n}),t}function N(o,e){let t=[],i=[],n=0;for(let s of e){let r=o.indexOf(s.text,n);r===-1?i.push(s):(t.push(s),n=r+s.text.length)}return{valid:t,invalid:i}}var P=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 J="0.1.35",K=!1;function Z(){return crypto.randomUUID()}function ee(o,e){return{placeholder:o.placeholder,type:o.type,...e&&{text:o.text},kind:o.kind}}function Q(o){return o?.type==="accessToken"}function te(o){if(!(!o||Q(o)))return o}var $=new WeakMap;function ie(o){let e=$.get(o.getAccessToken);return e||(e=new P(o),$.set(o.getAccessToken,e)),e}function oe(o,e,t,i){let n=e.find(r=>r.type==="contact"&&r.metadata?.contact_account_count)?.metadata?.contact_account_count,s=typeof n=="number"?n:void 0;return{data:{raw_query:o,completed_params:e.map(r=>ee(r,t)),...s!=null&&{contact_account_count:s}},meta:{request_id:Z(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:J,session_id:i}}}function se(o){return{"Content-Type":"application/json",...o?.appIdentifier&&{"X-App-Identifier":o.appIdentifier},...o?.headers}}async function q(o,e,t,i,n){return fetch(o,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:n})}async function U(o,e,t){let i=t.apiConfig,n=!t.maskCompletedText,s=oe(o,e,n,t.sessionId),r=se(i),p=i?.endpoint??"https://api.ai-autocomplete.com/api/suggest",a=JSON.stringify(s);if(Q(i)){let u=ie(i),m=await u.getToken(),g=await q(p,r,m,a,t.signal);if(g.status===401){let b=await u.getToken(!0);g=await q(p,r,b,a,t.signal)}if(!g.ok)throw new Error(`API error: ${g.status} ${g.statusText}`);return g.json()}let l=te(i),c=l?.apiKey??"";if(!c&&!K&&(K=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),c){let u=l?.authScheme??"Bearer";r.Authorization=u==="Basic"?`Basic ${btoa(c)}`:`Bearer ${c}`}let d=await fetch(p,{method:"POST",headers:r,body:a,signal:t.signal});if(!d.ok)throw new Error(`API error: ${d.status} ${d.statusText}`);return d.json()}function y(o,e){let t=o,i={},n=[];for(let s of e){let r=(i[s.type]??0)+1;i[s.type]=r;let a=`{{${s.type.toUpperCase().replace(/\s+/g,"_")}_${r}}}`,l=t.indexOf(s.text);l!==-1&&(t=t.slice(0,l)+a+t.slice(l+s.text.length)),n.push({...s,placeholder:a})}return{rawQuery:t,completedParams:n}}function j(o,e){return e?o.map(t=>{let i=e[t.type];if(!i)return t;let n=i("");if(n.length===0)return t;let s=new Set(n.map(p=>p.text)),r=(t.options??[]).filter(p=>!s.has(p.text));return{...t,options:[...n,...r]}}):o}var ne=100,re=300,ae=2,O=class{constructor(e,t,i,n,s,r){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=n;this.getOnError=s;this.getSessionId=r;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 n=++this.fetchVersion,s=this.store.get(),r=s.text.length;s.suggestions.some(a=>a.type!=="placeholder")||this.store.set({isLoading:!0}),this.store.set({error:null});try{let a=await U(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig()});if(n!==this.fetchVersion)return;let l=j(a.data.suggestions??[],this.getOptionOverrides()),c=a.data.input??[],d=c[c.length-1],u=this.store.get().text,m,g;if(d?.state==="in_progress"){g=!0;let x=u.toLowerCase().lastIndexOf(d.text.toLowerCase());m=x!==-1?x:r}else g=!1,m=r;let h=l.filter(x=>x.type!=="placeholder")[0],f=null;if(h){let x=v(u,m,g),S=L(h.options,x);S&&(f={id:crypto.randomUUID(),placeholder:"",type:h.type,text:S.text,kind:S.kind,suggestionType:h.type,suggestionPlaceholder:h.text,options:h.options??[],metadata:S.metadata},l=l.filter(Y=>Y!==h))}this.store.set(x=>({suggestions:l,isLoading:!1,isReady:a.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:m,filterInProgress:g,...f?{completedParams:[...x.completedParams,f]}:{}}))}catch(a){if(n===this.fetchVersion){let l=a instanceof Error?a:new Error(String(a));this.store.set({error:l,isLoading:!1}),this.getOnError()?.(l)}}}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}let t=i=>{let n=this.store.get();if(!n.text&&n.completedParams.length===0)return this.doFetch("",[]),!0;let s=v(n.text,n.filterBase,n.filterInProgress),p=n.suggestions.filter(h=>h.type!=="placeholder")[0],l=(p?C(p.options,s):[]).filter(h=>h.is_tappable),c=p?L(p.options,s)!==null:!1,d=s.trim().length>0;if(l.length>0&&!c&&d)return!1;if(n.completedParams.length===0&&n.text.length>0){let h=n.suggestions.filter(f=>f.type==="placeholder").map(f=>f.text).join(" ");if(h.length>0&&h.toLowerCase().startsWith(n.text.toLowerCase()))return!1}let{rawQuery:u,completedParams:m}=y(n.text,n.completedParams),g=u.length<n.lastRawQuery.length,b=Math.abs(u.length-n.lastRawQuery.length);return g||b>=i?(this.doFetch(u,m),!0):!1};this.debounceTimer=setTimeout(()=>{t(ae)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},ne),this.slowDebounceTimer=setTimeout(()=>t(1),re)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var T=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:n}=this.ctx,s=this.getEffectiveColumns(),r=n(),p=this.getTappableIndices(s);switch(e.key){case"ArrowDown":{let a=e.target;if(!(a.selectionStart!=null&&a.selectionStart===a.value.length)&&t.activeDropdownIndex<0)break;if(e.preventDefault(),!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:p[0]??0});break}if(p.length===0)return;let c=p.indexOf(t.activeDropdownIndex),d=c<p.length-1?c+1:0;this.store.set({activeDropdownIndex:p[d]});break}case"ArrowUp":{if(p.length===0||t.activeDropdownIndex<0)break;if(e.preventDefault(),t.activeDropdownIndex<s){this.store.set({activeDropdownIndex:-1});break}let a=p.indexOf(t.activeDropdownIndex),l=a>0?a-1:p.length-1;this.store.set({activeDropdownIndex:p[l]});break}case"ArrowRight":{if(t.activeDropdownIndex<0){let l=e.target;l.selectionStart!=null&&l.selectionStart===l.value.length&&t.actionableSuggestions.length>1&&(e.preventDefault(),this.pillsSetActivePill(1));break}if(t.activeDropdownIndex%s<s-1){let l=t.activeDropdownIndex+1;l<t.filteredOptions.length&&t.filteredOptions[l]?.is_tappable&&(e.preventDefault(),this.store.set({activeDropdownIndex:l}))}break}case"ArrowLeft":{if(t.activeDropdownIndex<0)break;if(t.activeDropdownIndex%s>0){let a=t.activeDropdownIndex-1;a>=0&&t.filteredOptions[a]?.is_tappable&&(e.preventDefault(),this.store.set({activeDropdownIndex:a}))}break}case"Enter":{if(e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable)this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i);else if(r){let{rawQuery:a,completedParams:l}=y(t.text,t.completedParams);r({query:t.text.trim(),raw_query:a,completed_params:l}),this.ctx.afterSubmit?.()}break}case"Tab":{let a=!t.text&&!!t.placeholderText,l=t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable;if(a&&!l){e.preventDefault();let c=t.suggestions.find(d=>d.type==="placeholder");c?this.store.set(d=>({text:t.placeholderText,filterBase:t.placeholderText.length,completedParams:[...d.completedParams,{id:crypto.randomUUID(),placeholder:"",type:c.type,text:t.placeholderText,kind:null,suggestionType:c.type,suggestionPlaceholder:c.text,options:c.options??[]}],suggestions:d.suggestions.filter(u=>u!==c)})):this.store.set({text:t.placeholderText,filterBase:t.placeholderText.length})}else if(l)e.preventDefault(),this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i);else if(t.isDropdownOpen){let c=t.filteredOptions.findIndex(d=>d.is_tappable);c>=0&&(e.preventDefault(),this.clickOrSelect(c,t.filteredOptions,i))}break}case"Escape":this.store.set({activeDropdownIndex:-1});break}}getTappableIndices(e){let i=this.store.get().filteredOptions.map((s,r)=>s.is_tappable?r:-1).filter(s=>s!==-1),n=Array.from({length:e},()=>[]);for(let s of i)n[s%e].push(s);return n.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 n=document.getElementById(`${i}-option-${e}`);n?n.click():this.ctx.selectOption(t[e])}pillsSetActivePill(e){let t=this.store.get(),i=t.suggestions.filter(p=>p.type!=="placeholder");if(e<0||e>=i.length)return;let n=i[e],s=i.filter((p,a)=>a!==e),r=t.suggestions.filter(p=>p.type==="placeholder");this.store.set({suggestions:[...r,n,...s],pillTapped:!0,activeDropdownIndex:-1})}};var I=class{constructor(e){this.store=e}setActivePill(e){let t=this.store.get(),i=t.suggestions.filter(p=>p.type!=="placeholder");if(e<0||e>=i.length)return;let n=i[e],s=i.filter((p,a)=>a!==e),r=t.suggestions.filter(p=>p.type==="placeholder");this.store.set({suggestions:[...r,n,...s],pillTapped:!0,activeDropdownIndex:-1})}removeLastParam(){let e=this.store.get();if(e.completedParams.length===0)return;let t=e.completedParams[e.completedParams.length-1],i={type:t.suggestionType,text:t.suggestionPlaceholder,required:!0,options:t.options};this.store.set(n=>({completedParams:n.completedParams.slice(0,-1),suggestions:[i,...n.suggestions],activeDropdownIndex:-1}))}};function le(o){return o===0?.4:o===1?.3:.15}function A(o,e,t,i,n=!1){let s=o.querySelector(".magicx-aia-pill-list");s||(s=document.createElement("span"),s.className="magicx-aia-pill-list",o.appendChild(s));let r=new Map;for(let a of s.querySelectorAll(".magicx-aia-pill"))r.set(a.dataset.pillKey??"",a);let p=new Set;for(let a=0;a<e.length;a++){let l=e[a],c=`${l.type}-${l.text}`;p.add(c);let d=r.get(c);d||(d=document.createElement("button"),d.type="button",d.dataset.pillKey=c,d.setAttribute("data-aia-pill",""),d.textContent=l.text),d.className=`magicx-aia-pill${n?" magicx-aia-pill--rounded":""}${a===t?" magicx-aia-pill--active":""}`,d.style.opacity=String(le(a)),d.onclick=()=>i(a),s.children[a]!==d&&s.insertBefore(d,s.children[a]??null)}for(let[a,l]of r)p.has(a)||l.remove()}function D(o){let e=document.createElement("div");return e.id=o,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",t=>t.preventDefault()),e}function E(o,e){let{filteredOptions:t,activeIndex:i,isOpen:n,pills:s,showPills:r,onSelect:p,onHighlight:a,onPillClick:l}=e,c=r&&s.length>0;n&&t.length>0||n&&c?o.classList.add("magicx-aia-dropdown--visible"):o.classList.remove("magicx-aia-dropdown--visible");let m=o.querySelector(".magicx-aia-pill-bar");c?(m||(m=document.createElement("div"),m.className="magicx-aia-pill-bar",m.setAttribute("data-aia-pillbar",""),o.insertBefore(m,o.firstChild)),A(m,s,0,l,!0)):m&&m.remove();let g=o.querySelector(".magicx-aia-grid");t.length>0?(g||(g=document.createElement("div"),g.className="magicx-aia-grid",o.appendChild(g)),ce(g,t,i,p,a,e.listboxId)):g&&(g.innerHTML="")}function ce(o,e,t,i,n,s){let r=e.map(l=>l.text).join("\0"),p=o.dataset.optionsKey??"",a=r!==p;if(o.dataset.optionsKey=r,a){let l=document.createDocumentFragment();for(let c=0;c<e.length;c++){let d=e[c],u=de(d,c,t,i,n,s);l.appendChild(u)}o.innerHTML="",o.appendChild(l)}else{let l=o.querySelectorAll(".magicx-aia-option");for(let c=0;c<l.length;c++){let d=l[c],u=c===t;d.setAttribute("aria-selected",String(u)),u?d.classList.add("magicx-aia-option--highlighted"):d.classList.remove("magicx-aia-option--highlighted")}}}function de(o,e,t,i,n,s){let r=document.createElement("div");r.id=`${s}-option-${e}`,r.setAttribute("role","option"),r.setAttribute("data-aia-option",""),r.setAttribute("aria-selected",String(e===t)),r.tabIndex=o.is_tappable?0:-1;let p=["magicx-aia-option"];e===t&&p.push("magicx-aia-option--highlighted"),o.is_tappable?p.push("magicx-aia-option--tappable"):p.push("magicx-aia-option--non-tappable"),r.className=p.join(" ");let a=document.createElement("div");a.className="magicx-aia-streaks",r.appendChild(a);let l=document.createElement("div");l.className="magicx-aia-streaks-vert",r.appendChild(l);let c=document.createElement("span");if(c.className="magicx-aia-option-content",c.textContent=o.icon?`${o.icon} ${o.text}`:o.text,o.tag){let d=document.createElement("span");d.className="magicx-aia-option-tag",d.textContent=o.tag,c.appendChild(d)}return r.appendChild(c),o.is_tappable&&(r.addEventListener("click",()=>{r.classList.add("magicx-aia-option--pressed"),i(o),setTimeout(()=>r.classList.remove("magicx-aia-option--pressed"),400)}),r.addEventListener("mouseenter",()=>n(e))),r}function V(o,e){let t=D(e.listboxId);return o.appendChild(t),{dropdown:t}}function M(o,e,t){E(o.dropdown,{suggestions:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,onSelect:t.selectOption,onHighlight:i=>t.store.set({activeDropdownIndex:i}),onPillClick:t.setActivePill})}function W(o,e,t,i,n){let s=o.querySelector(".magicx-aia-sizer-text"),r=o.querySelector(".magicx-aia-placeholder");if(i&&n){s&&(s.style.display="none"),r||(r=document.createElement("span"),r.className="magicx-aia-placeholder",o.insertBefore(r,o.firstChild)),r.style.display="",r.textContent=`${n} `,o.dataset.segmentKey="";return}r&&(r.style.display="none"),s||(s=document.createElement("span"),s.className="magicx-aia-sizer-text",o.insertBefore(s,o.firstChild)),s.style.display="",s.className=`magicx-aia-sizer-text${t?" magicx-aia-sizer-text--visible":""}`;let p=e.map(c=>`${c.type}:${c.value}`).join("\0"),a=o.dataset.segmentKey??"",l=o.dataset.newParamId??"";if(!(p===a&&(t??"")===l)){o.dataset.segmentKey=p,o.dataset.newParamId=t??"",s.innerHTML="";for(let c of e){let d=document.createElement("span");c.type==="completed"&&(c.param.id===t?d.className="magicx-aia-shimmer-revealed magicx-aia-shimmer-sweep":d.className="magicx-aia-segment magicx-aia-segment--completed"),d.textContent=c.value,s.appendChild(d)}e.length===0&&(s.textContent="\xA0")}}var pe='<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 z(o,e){let{listboxId:t}=e,i=D(t);o.appendChild(i);let n=document.createElement("div");n.className="magicx-aia-input-wrapper",o.appendChild(n);let s=document.createElement("div");s.className="magicx-aia-editor",s.setAttribute("data-aia-editor",""),n.appendChild(s);let r=document.createElement("div");r.className="magicx-aia-sizer",r.setAttribute("aria-hidden","true"),s.appendChild(r);let p=document.createElement("span");r.appendChild(document.createTextNode(" ")),r.appendChild(p);let a=document.createElement("textarea");a.className="magicx-aia-textarea",a.rows=1,a.setAttribute("role","combobox"),a.setAttribute("aria-autocomplete","list"),a.setAttribute("aria-controls",t),a.setAttribute("data-aia-textarea",""),s.appendChild(a);let l=null,c=null;return 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=pe,n.appendChild(l),c=l):e.submitButton!==null&&(c=e.submitButton,c.hasAttribute("data-aia-submit")||c.setAttribute("data-aia-submit",""),n.appendChild(c)),n.addEventListener("click",()=>a.focus()),a.addEventListener("input",()=>{let d=a.value,m=d.length>0&&d[0]!==d[0].toUpperCase()?d[0].toUpperCase()+d.slice(1):d;e.handleChange(m)}),a.addEventListener("keydown",d=>e.handleKeyDown(d)),a.addEventListener("focus",()=>e.store.set({isFocused:!0})),a.addEventListener("blur",()=>e.store.set({isFocused:!1})),c&&c.addEventListener("click",d=>{let u=e.store.get();if(!(!!u.text||u.completedParams.length>0)||!e.onSubmit)return;d.stopPropagation();let{rawQuery:g,completedParams:b}=y(u.text,u.completedParams);e.onSubmit({query:u.text.trim(),raw_query:g,completed_params:b}),e.afterSubmit?.()}),e.autoFocus!==!1&&a.focus(),{textarea:a,dropdown:i,sizer:r,submitButton:l,inlinePillContainer:p}}function k(o,e,t){let{textarea:i,dropdown:n,sizer:s,submitButton:r,inlinePillContainer:p}=o,{pillPlacement:a,setActivePill:l,selectOption:c,store:d}=t;i.value!==e.text&&(i.value=e.text),e.placeholderText?i.placeholder=e.placeholderText:i.removeAttribute("placeholder"),i.setAttribute("aria-expanded",String(e.isDropdownOpen));let u=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(u?i.setAttribute("aria-activedescendant",u):i.removeAttribute("aria-activedescendant"),e.newParamId?i.classList.add("magicx-aia-textarea--hidden"):i.classList.remove("magicx-aia-textarea--hidden"),r){let m=!!e.text||e.completedParams.length>0;r.disabled=!m}W(s,e.segments,e.newParamId,!e.text,e.placeholderText),a==="inline"?A(p,e.actionableSuggestions,0,l):p.innerHTML="",E(n,{suggestions:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:a==="dropdown",onSelect:c,onHighlight:m=>d.set({activeDropdownIndex:m}),onPillClick:l})}function R(o){let e=o,t=new Set;return{get:()=>e,set:i=>{let n=typeof i=="function"?i(e):i,s={...e,...n},r=e;e=s;for(let p of t)p(s,r)},subscribe:i=>(t.add(i),()=>{t.delete(i)})}}var _=!1;function G(){if(_||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){_=!0;return}_=!0;let o=document.createElement("style");o.setAttribute("data-magicx-aia",""),o.textContent=ue,document.head.appendChild(o)}var ue=`/* ===================================================================
2
2
  Vanilla core styles \u2014 stable BEM class names (magicx-aia-*)
3
3
  Auto-injected at runtime on first instantiation.
4
4
  =================================================================== */
@@ -664,5 +664,5 @@ function v(o,e,t){let i=o.slice(e);if(t||e===0||o[e-1]===" ")return i;let n=i.in
664
664
  animation-duration: 0s !important;
665
665
  transition-duration: 0s !important;
666
666
  }
667
- `;var me=0;function ge(){return`:ac-${++me}:`}function X(){return{text:"",completedParams:[],suggestions:[],activeDropdownIndex:-1,newParamId:null,isLoading:!1,isReady:!1,error:null,segments:[],actionableSuggestions:[],filteredOptions:[],placeholderText:"",isDropdownOpen:!1,filterBase:0,filterInProgress:!1,pillTapped:!1,skipNextFetch:!1,lastRawQuery:"",isFocused:!1}}var F=class{constructor(e,t={}){this.store=R(X());this._listboxId=ge();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 I(this.store),this.fetchController=new O(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.opts.onError,()=>this.sessionId),this.keyboardController=new T(this.store,{columns:t.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.opts.onSubmit,selectOption:i=>this.selectOption(i)}),this.unsubscribers.push(this.store.subscribe((i,n)=>{this.recomputeDerived(i,n)})),this.unsubscribers.push(this.store.subscribe((i,n)=>{i.text!==n.text&&this.opts.onChange?.(i.text),i.completedParams!==n.completedParams&&this.opts.onParamsChange?.(i.completedParams),i.isFocused!==n.isFocused&&(i.isFocused?this.opts.onFocus?.():this.opts.onBlur?.()),this.opts.onStateChange?.(i)})),this.renderMode!=="headless"&&(G(),this.setupContainer()),this.renderMode==="full"?this.buildAndRenderFull():this.renderMode==="dropdown"&&this.buildAndRenderDropdown(),this.fetchController.start()}focus(){this.domRefs?.textarea.focus()}blur(){this.domRefs?.textarea.blur()}reset(){this.store.set({...X(),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.externalListeners.clear();for(let e of this.unsubscribers)e();this.unsubscribers=[],this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}setValue(e){this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e)}removeLastParam(){this.pillsController.removeLastParam()}clearNewParamId(){this.store.set({newParamId:null})}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}handleTextChange(e){this.handleChange(e)}handleKeyDown(e){this.keyboardController.handleKeyDown(e)}setFocused(e){this.store.get().isFocused!==e&&this.store.set({isFocused:e})}subscribe(e){return this.externalListeners.add(e),()=>{this.externalListeners.delete(e)}}getState(){return this.store.get()}get listboxId(){return this._listboxId}get isReady(){return this.store.get().isReady}on(e,t){switch(e){case"submit":return this.opts.onSubmit=t,()=>{this.opts.onSubmit=void 0};case"error":return this.opts.onError=t,()=>{this.opts.onError=void 0};case"change":return this.opts.onChange=t,()=>{this.opts.onChange=void 0};case"paramsChange":return this.opts.onParamsChange=t,()=>{this.opts.onParamsChange=void 0};case"stateChange":return this.opts.onStateChange=t,()=>{this.opts.onStateChange=void 0};case"focus":return this.opts.onFocus=t,()=>{this.opts.onFocus=void 0};case"blur":return this.opts.onBlur=t,()=>{this.opts.onBlur=void 0};default:return()=>{}}}update(e){Object.assign(this.opts,e),e.mode!==void 0&&this.modeController?.setMode(e.mode),e.optionsPosition!==void 0&&(this.container.dataset.optionsPosition=e.optionsPosition),e.animations!==void 0&&(this.container.dataset.animations=e.animations?"on":"off"),e.pillPlacement!==void 0&&(this.container.dataset.pillPlacement=e.pillPlacement,this.store.set({})),(e.dropdownTrigger!==void 0||e.closeDropdownOnBlur!==void 0)&&this.store.set({}),e.value!==void 0&&this.store.set({text:e.value}),e.completedParams!==void 0&&this.store.set({completedParams:e.completedParams})}selectOption(e){let t=this.store.get(),i=t.actionableSuggestions[0];if(!i)return;let n=t.filterBase,s=t.text.slice(0,n),r=s.length===0&&t.text.length===0,p=s.length===0&&t.text.length>0&&t.placeholderText.length>0&&t.placeholderText.toLowerCase().startsWith(t.text.toLowerCase());(r||p)&&t.placeholderText&&(s=`${t.placeholderText} `);let a=B(s,e.text);a>0&&(s=s.slice(0,s.length-a));let l=s.length>0&&s[s.length-1]!==" ",c=`${s}${l?" ":""}${e.text} `,d=(r||p)&&c.length>0?c[0].toUpperCase()+c.slice(1):c,u=d.toLowerCase().lastIndexOf(e.text.toLowerCase()),m=u>=0?d.slice(u,u+e.text.length):e.text,g={id:crypto.randomUUID(),placeholder:"",type:i.type,text:m,kind:e.kind,suggestionType:i.type,suggestionPlaceholder:i.text,options:i.options??[],metadata:e.metadata},b=t.actionableSuggestions.length-1;this.store.set(h=>({text:d,filterBase:d.length,completedParams:[...h.completedParams,g],newParamId:g.id,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:b>0})),this.suggestionRemovalTimer=window.setTimeout(()=>{this.store.set(h=>({suggestions:h.suggestions.filter(f=>f!==i)}))},400)}recomputeDerived(e,t){if(this.derivedInProgress)return;this.derivedInProgress=!0;let i=H(e.text,e.completedParams),n=e.suggestions.filter(f=>f.type!=="placeholder"),s=n[0],r=s?this.opts.optionOverrides?.[s.type]:void 0,p=Math.min(e.filterBase,e.text.length),l=e.lastRawQuery!==""||p>0?v(e.text,p,e.filterInProgress):"",c=s?r?r(l.trim()):s.options??[]:[],d=C(c,l),u=e.suggestions.filter(f=>f.type==="placeholder").map(f=>f.text).join(" "),m=this.opts.dropdownTrigger??"auto",g=this.opts.closeDropdownOnBlur??!0,b=!1;if(m==="auto"){let f=g?e.isFocused:!0;b=!e.isLoading&&d.length>0&&f}else m==="manual"&&(b=!e.isLoading&&d.length>0&&e.pillTapped);this.store.set({segments:i,actionableSuggestions:n,filteredOptions:d,placeholderText:u,isDropdownOpen:b}),this.derivedInProgress=!1;let h=this.store.get();for(let f of this.externalListeners)f(h)}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 w(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},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)};this.domRefs=z(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&k(this.domRefs,this.store.get(),t)}),k(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=V(this.container,e),this.subscribeBatchedRender(()=>{this.dropdownRefs&&M(this.dropdownRefs,this.store.get(),e)}),M(this.dropdownRefs,this.store.get(),e),this.subscribeNewParamTimer()}subscribeBatchedRender(e){let t=!1;this.unsubscribers.push(this.store.subscribe(()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,t)=>{e.newParamId&&e.newParamId!==t.newParamId&&(this.newParamTimer&&clearTimeout(this.newParamTimer),this.newParamTimer=window.setTimeout(()=>{this.store.set({newParamId:null})},650))}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:n}=N(e,t.completedParams);n.length>0&&this.store.set(s=>({completedParams:i,suggestions:[...n.map(r=>({type:r.suggestionType,text:r.suggestionPlaceholder,required:!0,options:r.options})),...s.suggestions]}))}};export{F as AIAutocomplete,R as createStore};
667
+ `;var me=0;function ge(){return`:ac-${++me}:`}function X(){return{text:"",completedParams:[],suggestions:[],activeDropdownIndex:-1,newParamId:null,isLoading:!1,isReady:!1,error:null,segments:[],actionableSuggestions:[],filteredOptions:[],placeholderText:"",isDropdownOpen:!1,filterBase:0,filterInProgress:!1,pillTapped:!1,skipNextFetch:!1,lastRawQuery:"",isFocused:!1}}var F=class{constructor(e,t={}){this.store=R(X());this._listboxId=ge();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 I(this.store),this.fetchController=new O(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.opts.onError,()=>this.sessionId),this.keyboardController=new T(this.store,{columns:t.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.opts.onSubmit,afterSubmit:this.renderMode==="full"?()=>this.reset():void 0,selectOption:i=>this.selectOption(i)}),this.unsubscribers.push(this.store.subscribe((i,n)=>{this.recomputeDerived(i,n)})),this.unsubscribers.push(this.store.subscribe((i,n)=>{i.text!==n.text&&this.opts.onChange?.(i.text),i.completedParams!==n.completedParams&&this.opts.onParamsChange?.(i.completedParams),i.isFocused!==n.isFocused&&(i.isFocused?this.opts.onFocus?.():this.opts.onBlur?.()),this.opts.onStateChange?.(i)})),this.renderMode!=="headless"&&(G(),this.setupContainer()),this.renderMode==="full"?this.buildAndRenderFull():this.renderMode==="dropdown"&&this.buildAndRenderDropdown(),this.fetchController.start()}focus(){this.domRefs?.textarea.focus()}blur(){this.domRefs?.textarea.blur()}reset(){this.store.set({...X(),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.externalListeners.clear();for(let e of this.unsubscribers)e();this.unsubscribers=[],this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}setValue(e){this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e)}removeLastParam(){this.pillsController.removeLastParam()}clearNewParamId(){this.store.set({newParamId:null})}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}handleTextChange(e){this.handleChange(e)}handleKeyDown(e){this.keyboardController.handleKeyDown(e)}setFocused(e){this.store.get().isFocused!==e&&this.store.set({isFocused:e})}subscribe(e){return this.externalListeners.add(e),()=>{this.externalListeners.delete(e)}}getState(){return this.store.get()}get listboxId(){return this._listboxId}get isReady(){return this.store.get().isReady}on(e,t){switch(e){case"submit":return this.opts.onSubmit=t,()=>{this.opts.onSubmit=void 0};case"error":return this.opts.onError=t,()=>{this.opts.onError=void 0};case"change":return this.opts.onChange=t,()=>{this.opts.onChange=void 0};case"paramsChange":return this.opts.onParamsChange=t,()=>{this.opts.onParamsChange=void 0};case"stateChange":return this.opts.onStateChange=t,()=>{this.opts.onStateChange=void 0};case"focus":return this.opts.onFocus=t,()=>{this.opts.onFocus=void 0};case"blur":return this.opts.onBlur=t,()=>{this.opts.onBlur=void 0};default:return()=>{}}}update(e){Object.assign(this.opts,e),e.mode!==void 0&&this.modeController?.setMode(e.mode),e.optionsPosition!==void 0&&(this.container.dataset.optionsPosition=e.optionsPosition),e.animations!==void 0&&(this.container.dataset.animations=e.animations?"on":"off"),e.pillPlacement!==void 0&&(this.container.dataset.pillPlacement=e.pillPlacement,this.store.set({})),(e.dropdownTrigger!==void 0||e.closeDropdownOnBlur!==void 0)&&this.store.set({}),e.value!==void 0&&this.store.set({text:e.value}),e.completedParams!==void 0&&this.store.set({completedParams:e.completedParams})}selectOption(e){let t=this.store.get(),i=t.actionableSuggestions[0];if(!i)return;let n=t.filterBase,s=t.text.slice(0,n),r=s.length===0&&t.text.length===0,p=s.length===0&&t.text.length>0&&t.placeholderText.length>0&&t.placeholderText.toLowerCase().startsWith(t.text.toLowerCase());(r||p)&&t.placeholderText&&(s=`${t.placeholderText} `);let a=B(s,e.text);a>0&&(s=s.slice(0,s.length-a));let l=s.length>0&&s[s.length-1]!==" ",c=`${s}${l?" ":""}${e.text} `,d=(r||p)&&c.length>0?c[0].toUpperCase()+c.slice(1):c,u=d.toLowerCase().lastIndexOf(e.text.toLowerCase()),m=u>=0?d.slice(u,u+e.text.length):e.text,g={id:crypto.randomUUID(),placeholder:"",type:i.type,text:m,kind:e.kind,suggestionType:i.type,suggestionPlaceholder:i.text,options:i.options??[],metadata:e.metadata},b=t.actionableSuggestions.length-1;this.store.set(h=>({text:d,filterBase:d.length,completedParams:[...h.completedParams,g],newParamId:g.id,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:b>0})),this.suggestionRemovalTimer=window.setTimeout(()=>{this.store.set(h=>({suggestions:h.suggestions.filter(f=>f!==i)}))},400)}recomputeDerived(e,t){if(this.derivedInProgress)return;this.derivedInProgress=!0;let i=H(e.text,e.completedParams),n=e.suggestions.filter(f=>f.type!=="placeholder"),s=n[0],r=s?this.opts.optionOverrides?.[s.type]:void 0,p=Math.min(e.filterBase,e.text.length),l=e.lastRawQuery!==""||p>0?v(e.text,p,e.filterInProgress):"",c=s?r?r(l.trim()):s.options??[]:[],d=C(c,l),u=e.suggestions.filter(f=>f.type==="placeholder").map(f=>f.text).join(" "),m=this.opts.dropdownTrigger??"auto",g=this.opts.closeDropdownOnBlur??!0,b=!1;if(m==="auto"){let f=g?e.isFocused:!0;b=!e.isLoading&&d.length>0&&f}else m==="manual"&&(b=!e.isLoading&&d.length>0&&e.pillTapped);this.store.set({segments:i,actionableSuggestions:n,filteredOptions:d,placeholderText:u,isDropdownOpen:b}),this.derivedInProgress=!1;let h=this.store.get();for(let f of this.externalListeners)f(h)}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 w(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:i=>this.selectOption(i),setActivePill:i=>this.pillsController.setActivePill(i),handleKeyDown:i=>this.keyboardController.handleKeyDown(i),handleChange:i=>this.handleChange(i)};this.domRefs=z(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&k(this.domRefs,this.store.get(),t)}),k(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=V(this.container,e),this.subscribeBatchedRender(()=>{this.dropdownRefs&&M(this.dropdownRefs,this.store.get(),e)}),M(this.dropdownRefs,this.store.get(),e),this.subscribeNewParamTimer()}subscribeBatchedRender(e){let t=!1;this.unsubscribers.push(this.store.subscribe(()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,t)=>{e.newParamId&&e.newParamId!==t.newParamId&&(this.newParamTimer&&clearTimeout(this.newParamTimer),this.newParamTimer=window.setTimeout(()=>{this.store.set({newParamId:null})},650))}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:n}=N(e,t.completedParams);n.length>0&&this.store.set(s=>({completedParams:i,suggestions:[...n.map(r=>({type:r.suggestionType,text:r.suggestionPlaceholder,required:!0,options:r.options})),...s.suggestions]}))}};export{F as AIAutocomplete,R as createStore};
668
668
  //# sourceMappingURL=index.mjs.map