@magicx-eng/ai-autocomplete-vanilla 0.1.14 → 0.1.15

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.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var B=Object.defineProperty;var se=Object.getOwnPropertyDescriptor;var ne=Object.getOwnPropertyNames;var re=Object.prototype.hasOwnProperty;var ae=(o,e)=>{for(var t in e)B(o,t,{get:e[t],enumerable:!0})},le=(o,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ne(e))!re.call(o,s)&&s!==t&&B(o,s,{get:()=>e[s],enumerable:!(i=se(e,s))||i.enumerable});return o};var ce=o=>le(B({},"__esModule",{value:!0}),o);var Ae={};ae(Ae,{AIAutocomplete:()=>H,createStore:()=>F});module.exports=ce(Ae);function y(o,e){let t=o,i={},s=[];for(let r of e){let n=(i[r.type]??0)+1;i[r.type]=n;let a=`{{${r.type.toUpperCase().replace(/\s+/g,"_")}_${n}}}`,l=t.indexOf(r.text);l!==-1&&(t=t.slice(0,l)+a+t.slice(l+r.text.length)),s.push({...r,placeholder:a})}return{rawQuery:t,completedParams:s}}function v(o,e,t){let i=o.slice(e);if(t||e===0||o[e-1]===" ")return i;let s=i.indexOf(" ");return s===-1?"":i.slice(s+1)}function Q(o,e){let t=o.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let i=t.split(" "),s=e.toLowerCase();for(let r=0;r<i.length;r++){let n=i.slice(r).join(" ");if(s.startsWith(n.toLowerCase())){let c=t.length-n.length;return o.length-c}}return 0}function w(o,e){if(!o)return[];let t=e.trimStart();if(!t)return o;let i=t.toLowerCase();return o.filter(s=>!s.is_tappable||s.text.toLowerCase().includes(i))}function N(o,e){if(!o)return null;let t=e.trim();if(!t)return null;let i=t.toLowerCase();return o.find(s=>s.is_tappable&&s.text.toLowerCase()===i)??null}var P=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 U(o,e){let t=[],i=0;for(let r of e){let n=o.indexOf(r.text,i);n!==-1&&(n>i&&t.push({type:"text",value:o.slice(i,n)}),t.push({type:"completed",value:r.text,param:r}),i=n+r.text.length)}let s=o.slice(i);return s&&t.push({type:"text",value:s}),t}function j(o,e){let t=[],i=[],s=0;for(let r of e){let n=o.indexOf(r.text,s);n===-1?i.push(r):(t.push(r),s=n+r.text.length)}return{valid:t,invalid:i}}var T=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 de="https://api.ai-autocomplete.com",O=`${de}/api/suggest`,V=new WeakMap;function C(o){return o?.type==="accessToken"}function pe(o){if(!(!o||C(o)))return o}function I(o){let e=V.get(o.getAccessToken);return e||(e=new T(o),V.set(o.getAccessToken,e)),e}function A(o){return{"Content-Type":"application/json",...o?.appIdentifier&&{"X-App-Identifier":o.appIdentifier},...o?.headers}}function E(o){let e=pe(o),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}function ue(o){return(o??O).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function me(o){return C(o)?`Bearer ${await I(o).getToken()}`:E(o)}async function G(o){try{let e=ue(o.apiConfig?.endpoint),t=A(o.apiConfig),i=await me(o.apiConfig);i&&(t.Authorization=i);let s=JSON.stringify({source:o.source,session_id:o.sessionId,type:o.type,at:new Date().toISOString(),query_data:o.queryData});await fetch(e,{method:"POST",headers:t,body:s})}catch{}}var ge="0.1.38",W=!1;function he(){return crypto.randomUUID()}function fe(o,e){return{placeholder:o.placeholder,type:o.type,...e&&{text:o.text},kind:o.kind}}function xe(o,e,t,i){let s=e.find(n=>n.type==="contact"&&n.metadata?.contact_account_count)?.metadata?.contact_account_count,r=typeof s=="number"?s:void 0;return{data:{raw_query:o,completed_params:e.map(n=>fe(n,t)),...r!=null&&{contact_account_count:r}},meta:{request_id:he(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:ge,session_id:i}}}async function z(o,e,t,i,s){return fetch(o,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:s})}async function X(o,e,t){let i=t.apiConfig,s=!t.maskCompletedText,r=xe(o,e,s,t.sessionId),n=A(i),c=i?.endpoint??O,a=JSON.stringify(r);if(C(i)){let p=I(i),m=await p.getToken(),u=await z(c,n,m,a,t.signal);if(u.status===401){let h=await p.getToken(!0);u=await z(c,n,h,a,t.signal)}if(!u.ok)throw new Error(`API error: ${u.status} ${u.statusText}`);return u.json()}let l=E(i);!l&&!W&&(W=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),l&&(n.Authorization=l);let d=await fetch(c,{method:"POST",headers:n,body:a,signal:t.signal});if(!d.ok)throw new Error(`API error: ${d.status} ${d.statusText}`);return d.json()}function Y(o,e){return e?o.map(t=>{let i=e[t.type];if(!i)return t;let s=i("");if(s.length===0)return t;let r=new Set(s.map(c=>c.text)),n=(t.options??[]).filter(c=>!r.has(c.text));return{...t,options:[...s,...n]}}):o}var be=100,ye=300,Se=2,D=class{constructor(e,t,i,s,r,n,c={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=s;this.getOnError=r;this.getSessionId=n;this.callbacks=c;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 s=++this.fetchVersion,r=this.store.get(),n=r.text.length;r.suggestions.some(a=>a.type!=="placeholder")||this.store.set({isLoading:!0}),this.store.set({error:null});try{let a=await X(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig()});if(s!==this.fetchVersion)return;let l=Y(a.data.suggestions??[],this.getOptionOverrides()),d=a.data.input??[],p=d[d.length-1],m=this.store.get().text,u,h;if(p?.state==="in_progress"){h=!0;let b=m.toLowerCase().lastIndexOf(p.text.toLowerCase());u=b!==-1?b:n}else h=!1,u=n;let f=l.filter(b=>b.type!=="placeholder")[0],g=null;if(f){let b=v(m,u,h),S=N(f.options,b);S&&(g={id:crypto.randomUUID(),placeholder:"",type:f.type,text:S.text,kind:S.kind,suggestionType:f.type,suggestionPlaceholder:f.text,options:f.options??[],metadata:S.metadata},l=l.filter(oe=>oe!==f),this.callbacks.onAutoMatch?.({active:f,matched:S,rawQuery:e}))}this.store.set(b=>({suggestions:l,isLoading:!1,isReady:a.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:u,filterInProgress:h,...g?{completedParams:[...b.completedParams,g]}:{}}))}catch(a){if(s===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 s=this.store.get();if(!s.text&&s.completedParams.length===0)return this.doFetch("",[]),!0;let r=v(s.text,s.filterBase,s.filterInProgress),c=s.suggestions.filter(f=>f.type!=="placeholder")[0],l=(c?w(c.options,r):[]).filter(f=>f.is_tappable),d=c?N(c.options,r)!==null:!1,p=r.trim().length>0;if(l.length>0&&!d&&p)return!1;if(s.completedParams.length===0&&s.text.length>0){let f=s.suggestions.filter(g=>g.type==="placeholder").map(g=>g.text).join(" ");if(f.length>0&&f.toLowerCase().startsWith(s.text.toLowerCase()))return!1}let{rawQuery:m,completedParams:u}=y(s.text,s.completedParams),h=m.length<s.lastRawQuery.length,x=Math.abs(m.length-s.lastRawQuery.length);return h||x>=i?(this.doFetch(m,u),!0):!1};this.debounceTimer=setTimeout(()=>{t(Se)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},be),this.slowDebounceTimer=setTimeout(()=>t(1),ye)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var k=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:s}=this.ctx,r=this.getEffectiveColumns(),n=s(),c=this.getTappableIndices(r);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:c[0]??0});break}if(c.length===0)return;let d=c.indexOf(t.activeDropdownIndex),p=d<c.length-1?d+1:0;this.store.set({activeDropdownIndex:c[p]});break}case"ArrowUp":{if(c.length===0||t.activeDropdownIndex<0)break;if(e.preventDefault(),t.activeDropdownIndex<r){this.store.set({activeDropdownIndex:-1});break}let a=c.indexOf(t.activeDropdownIndex),l=a>0?a-1:c.length-1;this.store.set({activeDropdownIndex:c[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%r<r-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%r>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(n){let{rawQuery:a,completedParams:l}=y(t.text,t.completedParams);n({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 d=t.suggestions.find(p=>p.type==="placeholder");d?this.store.set(p=>({text:t.placeholderText,filterBase:t.placeholderText.length,completedParams:[...p.completedParams,{id:crypto.randomUUID(),placeholder:"",type:d.type,text:t.placeholderText,kind:null,suggestionType:d.type,suggestionPlaceholder:d.text,options:d.options??[]}],suggestions:p.suggestions.filter(m=>m!==d)})):this.store.set({text:t.placeholderText,filterBase:t.placeholderText.length})}else if(l)e.preventDefault(),this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i);else if(t.isDropdownOpen){let d=t.filteredOptions.findIndex(p=>p.is_tappable);d>=0&&(e.preventDefault(),this.clickOrSelect(d,t.filteredOptions,i))}break}case"Escape":this.store.set({activeDropdownIndex:-1});break}}getTappableIndices(e){let i=this.store.get().filteredOptions.map((r,n)=>r.is_tappable?n:-1).filter(r=>r!==-1),s=Array.from({length:e},()=>[]);for(let r of i)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 i=getComputedStyle(t).gridTemplateColumns.split(" ").filter(Boolean).length;return i>0?i:this.ctx.columns}clickOrSelect(e,t,i){let s=document.getElementById(`${i}-option-${e}`);s?s.click():this.ctx.selectOption(t[e])}pillsSetActivePill(e){let t=this.store.get(),i=t.suggestions.filter(c=>c.type!=="placeholder");if(e<0||e>=i.length)return;let s=i[e],r=i.filter((c,a)=>a!==e),n=t.suggestions.filter(c=>c.type==="placeholder");this.store.set({suggestions:[...n,s,...r],pillTapped:!0,activeDropdownIndex:-1})}};var M=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),i=t.suggestions.filter(c=>c.type!=="placeholder");if(e<0||e>=i.length)return;let s=i[e],r=i.filter((c,a)=>a!==e),n=t.suggestions.filter(c=>c.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:c}=y(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:c,selectedPill:s.text,otherPills:r.map(a=>a.text)})}this.store.set({suggestions:[...n,s,...r],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(s=>({completedParams:s.completedParams.slice(0,-1),suggestions:[i,...s.suggestions],activeDropdownIndex:-1}))}};function ve(o){return o===0?.4:o===1?.3:.15}function L(o,e,t,i,s=!1){let r=o.querySelector(".magicx-aia-pill-list");r||(r=document.createElement("span"),r.className="magicx-aia-pill-list",o.appendChild(r));let n=new Map;for(let a of r.querySelectorAll(".magicx-aia-pill"))n.set(a.dataset.pillKey??"",a);let c=new Set;for(let a=0;a<e.length;a++){let l=e[a],d=`${l.type}-${l.text}`;c.add(d);let p=n.get(d);p||(p=document.createElement("button"),p.type="button",p.dataset.pillKey=d,p.setAttribute("data-aia-pill",""),p.textContent=l.text),p.className=`magicx-aia-pill${s?" magicx-aia-pill--rounded":""}${a===t?" magicx-aia-pill--active":""}`,p.style.opacity=String(ve(a)),p.onclick=()=>i(a),r.children[a]!==p&&r.insertBefore(p,r.children[a]??null)}for(let[a,l]of n)c.has(a)||l.remove()}function R(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 _(o,e){let{filteredOptions:t,activeIndex:i,isOpen:s,pills:r,showPills:n,onSelect:c,onHighlight:a,onPillClick:l}=e,d=n&&r.length>0;s&&t.length>0||s&&d?o.classList.add("magicx-aia-dropdown--visible"):o.classList.remove("magicx-aia-dropdown--visible");let u=o.querySelector(".magicx-aia-pill-bar");d?(u||(u=document.createElement("div"),u.className="magicx-aia-pill-bar",u.setAttribute("data-aia-pillbar",""),o.insertBefore(u,o.firstChild)),L(u,r,0,l,!0)):u&&u.remove();let h=o.querySelector(".magicx-aia-grid");t.length>0?(h||(h=document.createElement("div"),h.className="magicx-aia-grid",o.appendChild(h)),Ce(h,t,i,c,a,e.listboxId)):h&&(h.innerHTML="")}function Ce(o,e,t,i,s,r){let n=e.map(l=>l.text).join("\0"),c=o.dataset.optionsKey??"",a=n!==c;if(o.dataset.optionsKey=n,a){let l=document.createDocumentFragment();for(let d=0;d<e.length;d++){let p=e[d],m=we(p,d,t,i,s,r);l.appendChild(m)}o.innerHTML="",o.appendChild(l)}else{let l=o.querySelectorAll(".magicx-aia-option");for(let d=0;d<l.length;d++){let p=l[d],m=d===t;p.setAttribute("aria-selected",String(m)),m?p.classList.add("magicx-aia-option--highlighted"):p.classList.remove("magicx-aia-option--highlighted")}}}function we(o,e,t,i,s,r){let n=document.createElement("div");n.id=`${r}-option-${e}`,n.setAttribute("role","option"),n.setAttribute("data-aia-option",""),n.setAttribute("aria-selected",String(e===t)),n.tabIndex=o.is_tappable?0:-1;let c=["magicx-aia-option"];e===t&&c.push("magicx-aia-option--highlighted"),o.is_tappable?c.push("magicx-aia-option--tappable"):c.push("magicx-aia-option--non-tappable"),n.className=c.join(" ");let a=document.createElement("div");a.className="magicx-aia-streaks",n.appendChild(a);let l=document.createElement("div");l.className="magicx-aia-streaks-vert",n.appendChild(l);let d=document.createElement("span");if(d.className="magicx-aia-option-content",d.textContent=o.icon?`${o.icon} ${o.text}`:o.text,o.tag){let p=document.createElement("span");p.className="magicx-aia-option-tag",p.textContent=o.tag,d.appendChild(p)}return n.appendChild(d),o.is_tappable&&(n.addEventListener("click",()=>{n.classList.add("magicx-aia-option--pressed"),i(o),setTimeout(()=>n.classList.remove("magicx-aia-option--pressed"),400)}),n.addEventListener("mouseenter",()=>s(e))),n}function J(o,e){let t=R(e.listboxId);return o.appendChild(t),{dropdown:t}}function K(o,e,t){_(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 Z(o,e,t,i,s){let r=o.querySelector(".magicx-aia-sizer-text"),n=o.querySelector(".magicx-aia-placeholder");if(i&&s){r&&(r.style.display="none"),n||(n=document.createElement("span"),n.className="magicx-aia-placeholder",o.insertBefore(n,o.firstChild)),n.style.display="",n.textContent=`${s} `,o.dataset.segmentKey="";return}n&&(n.style.display="none"),r||(r=document.createElement("span"),r.className="magicx-aia-sizer-text",o.insertBefore(r,o.firstChild)),r.style.display="",r.className=`magicx-aia-sizer-text${t?" magicx-aia-sizer-text--visible":""}`;let c=e.map(d=>`${d.type}:${d.value}`).join("\0"),a=o.dataset.segmentKey??"",l=o.dataset.newParamId??"";if(!(c===a&&(t??"")===l)){o.dataset.segmentKey=c,o.dataset.newParamId=t??"",r.innerHTML="";for(let d of e){let p=document.createElement("span");d.type==="completed"&&(d.param.id===t?p.className="magicx-aia-shimmer-revealed magicx-aia-shimmer-sweep":p.className="magicx-aia-segment magicx-aia-segment--completed"),p.textContent=d.value,r.appendChild(p)}e.length===0&&(r.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 ee(o,e){let{listboxId:t}=e,i=R(t);o.appendChild(i);let s=document.createElement("div");s.className="magicx-aia-input-wrapper",o.appendChild(s);let r=document.createElement("div");r.className="magicx-aia-editor",r.setAttribute("data-aia-editor",""),s.appendChild(r);let n=document.createElement("div");n.className="magicx-aia-sizer",n.setAttribute("aria-hidden","true"),r.appendChild(n);let c=document.createElement("span");n.appendChild(document.createTextNode(" ")),n.appendChild(c);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",""),r.appendChild(a);let l=null,d=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,s.appendChild(l),d=l):e.submitButton!==null&&(d=e.submitButton,d.hasAttribute("data-aia-submit")||d.setAttribute("data-aia-submit",""),s.appendChild(d)),s.addEventListener("click",()=>a.focus()),a.addEventListener("input",()=>{let p=a.value,u=p.length>0&&p[0]!==p[0].toUpperCase()?p[0].toUpperCase()+p.slice(1):p;e.handleChange(u)}),a.addEventListener("keydown",p=>e.handleKeyDown(p)),a.addEventListener("focus",()=>e.store.set({isFocused:!0})),a.addEventListener("blur",()=>e.store.set({isFocused:!1})),d&&d.addEventListener("click",p=>{let m=e.store.get();if(!(!!m.text||m.completedParams.length>0)||!e.onSubmit)return;p.stopPropagation();let{rawQuery:h,completedParams:x}=y(m.text,m.completedParams);e.onSubmit({query:m.text.trim(),raw_query:h,completed_params:x}),e.afterSubmit?.()}),e.autoFocus!==!1&&a.focus(),{textarea:a,dropdown:i,sizer:n,submitButton:l,inlinePillContainer:c}}function $(o,e,t){let{textarea:i,dropdown:s,sizer:r,submitButton:n,inlinePillContainer:c}=o,{pillPlacement:a,setActivePill:l,selectOption:d,store:p}=t;i.value!==e.text&&(i.value=e.text),e.placeholderText?i.placeholder=e.placeholderText:i.removeAttribute("placeholder"),i.setAttribute("aria-expanded",String(e.isDropdownOpen));let m=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(m?i.setAttribute("aria-activedescendant",m):i.removeAttribute("aria-activedescendant"),e.newParamId?i.classList.add("magicx-aia-textarea--hidden"):i.classList.remove("magicx-aia-textarea--hidden"),n){let u=!!e.text||e.completedParams.length>0;n.disabled=!u}Z(r,e.segments,e.newParamId,!e.text,e.placeholderText),a==="inline"?L(c,e.actionableSuggestions,0,l):c.innerHTML="",_(s,{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:d,onHighlight:u=>p.set({activeDropdownIndex:u}),onPillClick:l})}function F(o){let e=o,t=new Set;return{get:()=>e,set:i=>{let s=typeof i=="function"?i(e):i,r={...e,...s},n=e;e=r;for(let c of t)c(r,n)},subscribe:i=>(t.add(i),()=>{t.delete(i)})}}var q=!1;function te(){if(q||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){q=!0;return}q=!0;let o=document.createElement("style");o.setAttribute("data-magicx-aia",""),o.textContent=Te,document.head.appendChild(o)}var Te=`/* ===================================================================
1
+ "use strict";var z=Object.defineProperty;var Ce=Object.getOwnPropertyDescriptor;var we=Object.getOwnPropertyNames;var Ee=Object.prototype.hasOwnProperty;var Oe=(i,e)=>{for(var t in e)z(i,t,{get:e[t],enumerable:!0})},Ie=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of we(e))!Ee.call(i,s)&&s!==t&&z(i,s,{get:()=>e[s],enumerable:!(n=Ce(e,s))||n.enumerable});return i};var Ae=i=>Ie(z({},"__esModule",{value:!0}),i);var Ze={};Oe(Ze,{AIAutocomplete:()=>G,createStore:()=>j});module.exports=Ae(Ze);function P(i,e){let t=i,n={},s=[];for(let r of e){let o=(n[r.type]??0)+1;n[r.type]=o;let c=`{{${r.type.toUpperCase().replace(/\s+/g,"_")}_${o}}}`,l=t.indexOf(r.text);l!==-1&&(t=t.slice(0,l)+c+t.slice(l+r.text.length)),s.push({...r,placeholder:c})}return{rawQuery:t,completedParams:s}}function I(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 ee(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 A(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 te(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 ne(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 De="https://api.ai-autocomplete.com",R=`${De}/api/suggest`,ie=new WeakMap;function D(i){return i?.type==="accessToken"}function Le(i){if(!(!i||D(i)))return i}function _(i){let e=ie.get(i.getAccessToken);return e||(e=new k(i),ie.set(i.getAccessToken,e)),e}function N(i){return{"Content-Type":"application/json",...i?.appIdentifier&&{"X-App-Identifier":i.appIdentifier},...i?.headers}}function H(i){let e=Le(i),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}function Me(i){return(i??R).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function ke(i){return D(i)?`Bearer ${await _(i).getToken()}`:H(i)}async function oe(i){try{let e=Me(i.apiConfig?.endpoint),t=N(i.apiConfig),n=await ke(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 Re="0.1.39",se=!1;function _e(){return crypto.randomUUID()}function Ne(i,e){return{placeholder:i.placeholder,type:i.type,...e&&{text:i.text},kind:i.kind}}function He(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=>Ne(o,t)),...r!=null&&{contact_account_count:r}},meta:{request_id:_e(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:Re,session_id:n}}}async function re(i,e,t,n,s){return fetch(i,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:n,signal:s})}async function ae(i,e,t){let n=t.apiConfig,s=!t.maskCompletedText,r=He(i,e,s,t.sessionId),o=N(n),a=n?.endpoint??R,c=JSON.stringify(r);if(D(n)){let d=_(n),u=await d.getToken(),x=await re(a,o,u,c,t.signal);if(x.status===401){let f=await d.getToken(!0);x=await re(a,o,f,c,t.signal)}if(!x.ok)throw new Error(`API error: ${x.status} ${x.statusText}`);return x.json()}let l=H(n);!l&&!se&&(se=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),l&&(o.Authorization=l);let p=await fetch(a,{method:"POST",headers:o,body:c,signal:t.signal});if(!p.ok)throw new Error(`API error: ${p.status} ${p.statusText}`);return p.json()}function le(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 Fe=100,Be=300,Ke=2,F=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 ae(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:n.signal,apiConfig:this.getApiConfig()});if(s!==this.fetchVersion)return;let a=le(o.data.suggestions??[],this.getOptionOverrides()),c=o.data.input??[],l=c[c.length-1],p=this.store.get().text,d,u;if(l?.state==="in_progress"){u=!0;let h=p.toLowerCase().lastIndexOf(l.text.toLowerCase());d=h!==-1?h:r}else u=!1,d=r;let f=a.filter(h=>h.type!=="placeholder")[0],b=null;if(f){let h=w(p,d,u),m=E(f.options,h);m&&(b={id:crypto.randomUUID(),placeholder:"",type:f.type,text:m.text,kind:m.kind,suggestionType:f.type,suggestionPlaceholder:f.text,options:f.options??[],metadata:m.metadata},a=a.filter(g=>g!==f),this.callbacks.onAutoMatch?.({active:f,matched:m,rawQuery:e}))}this.store.set(h=>({suggestions:a,isLoading:!1,isReady:o.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:d,filterInProgress:u,...b?{completedParams:[...h.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=I(s.text,s.filterBase,r),a=w(s.text,o,s.filterInProgress),l=s.suggestions.filter(g=>g.type!=="placeholder")[0],d=(l?A(l.options,a):[]).filter(g=>g.is_tappable),u=l?E(l.options,a)!==null:!1,x=a.trim().length>0;if(d.length>0&&!u&&x||s.completedParams.length===0&&s.text.length>0&&r.length>0&&r.toLowerCase().startsWith(s.text.toLowerCase()))return!1;let{rawQuery:f,completedParams:b}=P(s.text,s.completedParams),h=f.length<s.lastRawQuery.length,m=Math.abs(f.length-s.lastRawQuery.length);return h||m>=n?(this.doFetch(f,b),!0):!1};this.debounceTimer=setTimeout(()=>{t(Ke)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},Fe),this.slowDebounceTimer=setTimeout(()=>t(1),Be)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var de='[contenteditable="false"]',O;function qe(){if(O!==void 0)return O;let i=globalThis.Intl.Segmenter;if(!i)return O=null,null;try{O=new i(void 0,{granularity:"grapheme"})}catch{O=null}return O??null}function B(i,e){let t=i;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(de))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 V(i){let e=K(i),t="",n=e.nextNode();for(;n;)t+=n.data,n=e.nextNode();return t}function pe(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+ce(s,i)}return t.nodeType!==Node.TEXT_NODE||B(t,i)?null:ce(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(de))return 0;let n=0;for(let s of Array.from(t.childNodes))n+=ue(s,e);return n}function ce(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,pe(i))),r=K(i),o=0,a=null,c=0,l=r.nextNode(),p=null;for(;l;){let u=l.data.length;if(s<o+u){a=l,c=s-o;break}if(s===o+u){let x=r.nextNode();x?(a=x,c=0):(a=l,c=u);break}o+=u,p=l,l=r.nextNode()}let d=t.createRange();if(a){let u=a.parentElement?.closest('strong[data-seg="completed"]');u&&u!==i&&i.contains(u)?c===0?d.setStartBefore(u):c===a.data.length?d.setStartAfter(u):d.setStart(a,c):d.setStart(a,c)}else p?d.setStart(p,p.data.length):d.setStart(i,0);d.collapse(!0),n.removeAllRanges(),n.addRange(d)}function me(i){let e=C(i);return e==null?!1:e>=pe(i)}function ge(i,e){if(e<=0)return 0;let t=qe();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 he(i){return i instanceof HTMLTextAreaElement||i instanceof HTMLInputElement?i.selectionStart!=null&&i.selectionStart===i.value.length:i instanceof HTMLElement&&i.hasAttribute("data-aia-input")?me(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 c=he(e.target),l=!!t.editingParam;if(!c&&!l&&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 p=a.indexOf(t.activeDropdownIndex),d=p<a.length-1?p+1:0;this.store.set({activeDropdownIndex:a[d]});break}case"ArrowUp":{if(a.length===0||t.activeDropdownIndex<0)break;if(e.preventDefault(),t.activeDropdownIndex<r){this.store.set({activeDropdownIndex:-1});break}let c=a.indexOf(t.activeDropdownIndex),l=c>0?c-1:a.length-1;this.store.set({activeDropdownIndex:a[l]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%r<r-1){let p=t.activeDropdownIndex+1;p<t.filteredOptions.length&&t.filteredOptions[p]?.is_tappable&&this.store.set({activeDropdownIndex:p})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let l=e.target.closest("[data-aia-input]")??e.target,p=t.editingTail;this.ctx.exitEditMode?.(),S(l,p);break}he(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 c=t.activeDropdownIndex-1;c>=0&&t.filteredOptions[c]?.is_tappable&&this.store.set({activeDropdownIndex:c})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let c=e.target.closest("[data-aia-input]")??e.target,l=t.editingAnchor;this.ctx.exitEditMode?.(),S(c,l);break}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let c=$e(e.target);if(c==null)break;this.ctx.removeParamAtCaret(c)&&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:c,completedParams:l}=P(t.text,t.completedParams);o({query:t.text.trim(),raw_query:c,completed_params:l}),this.ctx.afterSubmit?.()}break}case"Tab":{let c=!t.text&&!!t.placeholderText,l=t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable;if(c&&!l){e.preventDefault();let p=t.placeholderText;if(this.store.set(d=>({text:p,filterBase:p.length,suggestions:d.suggestions.filter(u=>u.type!=="placeholder")})),e.target instanceof HTMLElement){let d=e.target.closest("[data-aia-input]")??e.target;queueMicrotask(()=>S(d,p.length))}}else if(l)e.preventDefault(),this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,n);else if(t.isDropdownOpen){let p=t.filteredOptions.findIndex(d=>d.is_tappable);p>=0&&(e.preventDefault(),this.clickOrSelect(p,t.filteredOptions,n))}break}case"Escape":{if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){let c=e.target.closest("[data-aia-input]")??e.target,l=t.editingTail;this.ctx.exitEditMode?.(),S(c,l)}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,c)=>c!==e),o=t.suggestions.filter(a=>a.type==="placeholder");this.store.set({suggestions:[...o,s,...r],pillTapped:!0,activeDropdownIndex:-1})}};var $=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,c)=>c!==e),o=t.suggestions.filter(a=>a.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:a}=P(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:a,selectedPill:s.text,otherPills:r.map(c=>c.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 fe=[125,69];function xe(i){return i===0?.4:i===1?.3:.15}function Q(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){o.setAttribute("data-aia-pill-list-loading",""),o.innerHTML="";for(let l=0;l<fe.length;l++){let p=fe[l],d=document.createElement("span");d.setAttribute("data-aia-pill-skeleton",""),d.className=`magicx-aia-pill magicx-aia-pill--skeleton${s?" magicx-aia-pill--rounded":""}`,d.style.width=`${p}px`,d.style.opacity=String(xe(l)),o.appendChild(d)}return}o.removeAttribute("data-aia-pill-list-loading");let a=new Map;for(let l of o.querySelectorAll(".magicx-aia-pill"))a.set(l.dataset.pillKey??"",l);let c=new Set;for(let l=0;l<e.length;l++){let p=e[l],d=`${p.type}-${p.text}`;c.add(d);let u=a.get(d);(!u||u.tagName!=="BUTTON")&&(u?.remove(),u=document.createElement("button"),u.type="button",u.tabIndex=-1,u.dataset.pillKey=d,u.setAttribute("data-aia-pill",""),u.setAttribute("contenteditable","false"),u.textContent=p.text,u.addEventListener("mousedown",x=>x.preventDefault())),u.className=`magicx-aia-pill${s?" magicx-aia-pill--rounded":""}${l===t?" magicx-aia-pill--active":""}`,u.style.width="",u.style.opacity=String(xe(l)),u.onclick=()=>n(l),o.children[l]!==u&&o.insertBefore(u,o.children[l]??null)}for(let[l,p]of a)c.has(l)||p.remove();for(let l of o.querySelectorAll("[data-aia-pill-skeleton]"))l.remove()}function X(i){i.querySelector(".magicx-aia-pill-list")?.remove()}var Qe=[159,119,164],Ue=[115,122];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:c,onHighlight:l,onPillClick:p}=e,d=a&&o.length>0,u=s&&t.length>0;s&&(r||u||d)?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 f=i.querySelector(".magicx-aia-skeleton");if(r){if(i.querySelector(".magicx-aia-pill-bar")?.remove(),i.querySelector(".magicx-aia-grid")?.remove(),!f)f=We(a),i.appendChild(f);else{let m=f.querySelector(".magicx-aia-skeleton-pills");a&&!m?f.insertBefore(be(),f.firstChild):!a&&m&&m.remove()}return}f&&f.remove();let b=i.querySelector(".magicx-aia-pill-bar");d?(b||(b=document.createElement("div"),b.className="magicx-aia-pill-bar",b.setAttribute("data-aia-pillbar",""),i.insertBefore(b,i.firstChild)),Q(b,o,0,p,!0)):b&&b.remove();let h=i.querySelector(".magicx-aia-grid");t.length>0?(h||(h=document.createElement("div"),h.className="magicx-aia-grid",i.appendChild(h)),je(h,t,n,c,l,e.listboxId)):h&&(h.innerHTML="")}function We(i){let e=document.createElement("div");e.className="magicx-aia-skeleton",e.setAttribute("data-aia-skeleton",""),i&&e.appendChild(be());let t=document.createElement("div");t.className="magicx-aia-skeleton-bars";for(let n of Qe){let s=document.createElement("span");s.className="magicx-aia-skeleton-bar",s.style.width=`${n}px`,t.appendChild(s)}return e.appendChild(t),e}function be(){let i=document.createElement("div");i.className="magicx-aia-skeleton-pills",i.setAttribute("data-aia-skeleton-pills","");for(let e of Ue){let t=document.createElement("span");t.className="magicx-aia-skeleton-pill",t.style.width=`${e}px`,i.appendChild(t)}return i}function je(i,e,t,n,s,r){let o=e.map(l=>l.text).join("\0"),a=i.dataset.optionsKey??"",c=o!==a;if(i.dataset.optionsKey=o,c){let l=document.createDocumentFragment();for(let p=0;p<e.length;p++){let d=e[p],u=Ge(d,p,t,n,s,r);l.appendChild(u)}i.innerHTML="",i.appendChild(l)}else{let l=i.querySelectorAll(".magicx-aia-option");for(let p=0;p<l.length;p++){let d=l[p],u=p===t;d.setAttribute("aria-selected",String(u)),u?d.classList.add("magicx-aia-option--highlighted"):d.classList.remove("magicx-aia-option--highlighted")}}}function Ge(i,e,t,n,s,r){let o=document.createElement("div");o.id=`${r}-option-${e}`,o.setAttribute("role","option"),o.setAttribute("data-aia-option",""),o.setAttribute("aria-selected",String(e===t)),o.tabIndex=i.is_tappable?0:-1;let a=["magicx-aia-option"];e===t&&a.push("magicx-aia-option--highlighted"),i.is_tappable?a.push("magicx-aia-option--tappable"):a.push("magicx-aia-option--non-tappable"),o.className=a.join(" ");let c=document.createElement("div");c.className="magicx-aia-streaks",o.appendChild(c);let l=document.createElement("div");l.className="magicx-aia-streaks-vert",o.appendChild(l);let p=document.createElement("span");if(p.className="magicx-aia-option-content",p.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,p.appendChild(d)}return o.appendChild(p),i.is_tappable&&(o.addEventListener("click",()=>{o.classList.add("magicx-aia-option--pressed"),n(i),setTimeout(()=>o.classList.remove("magicx-aia-option--pressed"),400)}),o.addEventListener("mouseenter",()=>s(e))),o}function ye(i,e){let t=U(e.listboxId);return i.appendChild(t),{dropdown:t}}function J(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,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,onSelect:t.selectOption,onHighlight:n=>t.store.set({activeDropdownIndex:n}),onPillClick:t.setActivePill})}function ve(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 c=t.map(h=>`${h.type}:${h.value}`).join("\0"),l=e.dataset.segKey??"",p=e.dataset.newParamId??"",d=e.dataset.editingParamId??"";if(c===l&&(n??"")===p&&(s??"")===d)return;let u=o?C(e):null;e.dataset.segKey=c,e.dataset.newParamId=n??"",e.dataset.editingParamId=s??"";let x=e.ownerDocument??document,f=x.createDocumentFragment(),b=0;for(let h of t)if(b+=h.value.length,h.type==="completed"){let m=x.createElement("strong");m.dataset.seg="completed",m.dataset.paramId=h.param.id;let g=h.param.id===n,y=h.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"),m.className=v.join(" "),m.textContent=h.value,f.appendChild(m)}else f.appendChild(x.createTextNode(h.value));e.replaceChildren(f),e.dataset.aiaTextLength=String(b),u!=null&&S(e,Math.max(0,Math.min(u,b)))}var ze='<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 Ve(){let i=document.createElement("div");return i.setAttribute("contenteditable","plaintext-only"),i.contentEditable==="plaintext-only"}function Se(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",Ve()?"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 c=null,l=null;e.submitButton===void 0?(c=document.createElement("button"),c.type="button",c.className="magicx-aia-submit",c.setAttribute("aria-label","Submit"),c.setAttribute("data-aia-submit",""),c.innerHTML=ze,s.appendChild(c),l=c):e.submitButton!==null&&(l=e.submitButton,l.hasAttribute("data-aia-submit")||l.setAttribute("data-aia-submit",""),s.appendChild(l));let p=new AbortController,{signal:d}=p,u=!1,x=0,f=()=>{let m=V(o),y=m.length>0&&m[0]!==m[0].toUpperCase()?m[0].toUpperCase()+m.slice(1):m;e.handleChange(y)},b=()=>{let m=(o.ownerDocument??document).getSelection();if(!m||m.rangeCount===0)return null;let g=m.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",m=>{m.target?.closest("[data-aia-pill]")||o.focus()},{signal:d}),o.addEventListener("input",()=>{u||(x=performance.now(),f(),e.handleCaretAfterInput(C(o)))},{signal:d});let h=o.ownerDocument??document;return h.addEventListener("selectionchange",()=>{let m=h.getSelection();if(!m||m.rangeCount===0||!o.contains(m.anchorNode))return;let g=b(),y=e.store.get().editingParam?.id??null;if(g&&g!==y){e.startEditingParam(g);return}performance.now()-x<50||e.handleCaretMove(C(o))},{signal:d}),o.addEventListener("compositionstart",()=>{u=!0},{signal:d}),o.addEventListener("compositionend",()=>{u=!1,f()},{signal:d}),o.addEventListener("beforeinput",m=>{let g=m,y=g.inputType;if(y==="insertParagraph"||y==="insertLineBreak"||y==="insertFromDrop"){m.preventDefault();return}if(y.startsWith("insert")||y.startsWith("delete")){let v=y.startsWith("delete")?"":g.data??"";e.replaceEditingRange(v)&&m.preventDefault()}},{signal:d}),o.addEventListener("paste",m=>{m.preventDefault();let g=(m.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 T=v.getRangeAt(0);if(!o.contains(T.startContainer))return;T.deleteContents();let L=y.createTextNode(g);T.insertNode(L),T.setStartAfter(L),T.collapse(!0),v.removeAllRanges(),v.addRange(T),f()},{signal:d}),o.addEventListener("keydown",m=>e.handleKeyDown(m),{signal:d}),o.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:d}),o.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:d}),l&&l.addEventListener("click",m=>{let g=e.store.get();if(!(!!g.text||g.completedParams.length>0)||!e.onSubmit)return;m.stopPropagation();let{rawQuery:v,completedParams:T}=P(g.text,g.completedParams);e.onSubmit({query:g.text.trim(),raw_query:v,completed_params:T}),e.afterSubmit?.()},{signal:d}),e.autoFocus!==!1&&o.focus(),{input:o,inlinePillContainer:a,dropdown:n,submitButton:c,abort:p}}function Y(i,e,t){let{input:n,inlinePillContainer:s,dropdown:r,submitButton:o}=i,{pillPlacement:a,setActivePill:c,selectOption:l,store:p}=t;n.setAttribute("aria-expanded",String(e.isDropdownOpen));let d=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(d?n.setAttribute("aria-activedescendant",d):n.removeAttribute("aria-activedescendant"),o){let h=!!e.text||e.completedParams.length>0;o.disabled=!h}let u=n.dataset.newParamId??"",x=e.newParamId!==null&&e.newParamId!==u;if(ve({input:n,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused}),a==="inline"){let h=e.isLoading&&!e.editingParam;h||e.actionableSuggestions.length>0?Q(s,e.actionableSuggestions,0,c,!1,h):X(s)}else X(s);x?(n.focus(),S(n,e.caretOffset??e.text.length)):e.isFocused&&V(n)!==e.text&&S(n,e.text.length);let f=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:null,b=f??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,listboxId:t.listboxId,pills:f?[f]:e.actionableSuggestions,showPills:a==="dropdown",onSelect:l,onHighlight:h=>p.set({activeDropdownIndex:h}),onPillClick:c})}function j(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 Z=!1;function Pe(){if(Z||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){Z=!0;return}Z=!0;let i=document.createElement("style");i.setAttribute("data-magicx-aia",""),i.textContent=Xe,document.head.appendChild(i)}var Xe=`/* ===================================================================
2
2
  Vanilla core styles \u2014 stable BEM class names (magicx-aia-*)
3
3
  Auto-injected at runtime on first instantiation.
4
4
  =================================================================== */
@@ -6,7 +6,10 @@
6
6
  /* --- Container --- */
7
7
  .magicx-aia {
8
8
  position: relative;
9
- font-family: "IBM Plex Sans", sans-serif;
9
+ /* Inherits the host page's font by default. Consumers can pin a specific
10
+ font on the library via \`--aia-font-family: 'Custom Font'\` without
11
+ affecting the surrounding page. */
12
+ font-family: var(--aia-font-family, inherit);
10
13
  container-type: inline-size;
11
14
  }
12
15
 
@@ -22,71 +25,89 @@
22
25
  gap: 0px;
23
26
  }
24
27
 
25
- /* --- Editor area (overlay + textarea) --- */
28
+ /* --- Editor area (wraps the editable input + inline pill list sibling) --- */
26
29
  .magicx-aia-editor {
27
30
  position: relative;
28
31
  flex: 1;
29
32
  min-width: 0;
30
- }
31
-
32
- /* --- Sizer (overlay for sizing + segment display) --- */
33
- .magicx-aia-sizer {
34
- position: relative;
35
- z-index: 1;
36
- pointer-events: none;
37
- white-space: pre-wrap;
38
- word-break: break-word;
33
+ min-height: 38px;
34
+ line-height: 38px;
39
35
  font-family: inherit;
40
36
  font-size: var(--aia-written-text-font-size, 19px);
41
- line-height: 38px;
37
+ white-space: pre-wrap;
38
+ word-break: break-word;
39
+ overflow-wrap: anywhere;
42
40
  }
43
41
 
44
- .magicx-aia-sizer-text {
45
- color: transparent;
42
+ /* --- Editable input (contentEditable; inline so pills flow alongside) --- */
43
+ .magicx-aia-input {
44
+ display: inline;
45
+ outline: none;
46
+ background: transparent;
47
+ color: var(--aia-written-text-color, var(--aia-color-text-default, #fff));
48
+ caret-color: var(
49
+ --aia-caret-color,
50
+ var(--aia-written-text-color, var(--aia-color-text-default, #fff))
51
+ );
52
+ font-weight: 200;
46
53
  }
47
54
 
48
- .magicx-aia-sizer-text--visible {
49
- color: var(--aia-written-text-color, var(--aia-color-text-default, #fff));
50
- font-size: var(--aia-written-text-font-size, inherit);
55
+ /* Empty inline contentEditables don't have an inline box, so the browser has
56
+ nowhere to render the caret. Switching to inline-block gives it presence;
57
+ the min-width is just wide enough for the caret line. */
58
+ .magicx-aia-input[data-aia-empty="true"] {
59
+ display: inline-block;
60
+ min-width: 1px;
61
+ vertical-align: top;
51
62
  }
52
63
 
53
- /* --- Placeholder --- */
54
- .magicx-aia-placeholder {
55
- color: var(--aia-color-text-muted, #c1c4cb);
56
- opacity: 0.7;
64
+ /* Completed params render as inline bold runs. Specificity stays at (0,2,0)
65
+ so consumers can override with \`.magicx-aia-input strong\`. */
66
+ :where(.magicx-aia-input) strong {
67
+ font-weight: 500;
68
+ letter-spacing: -0.01em;
57
69
  }
58
70
 
59
- /* --- Textarea --- */
60
- .magicx-aia-textarea {
61
- position: absolute;
62
- top: 0;
63
- left: 0;
64
- width: 100%;
65
- height: 100%;
66
- padding: 0;
67
- border: none;
71
+ /* Re-edit highlight \u2014 applied to the bold param being re-edited. The DOM
72
+ keeps a Selection range over the strong so the browser still handles
73
+ typing / backspace as a range replacement; we hide the native selection
74
+ paint and the caret so the only visual cue is this outline. */
75
+ :where(.magicx-aia-input) strong.magicx-aia-segment--editing {
76
+ outline: 1.5px solid var(--aia-edit-outline, currentColor);
77
+ outline-offset: 1px;
78
+ border-radius: 4px;
79
+ caret-color: transparent;
80
+ }
81
+
82
+ :where(.magicx-aia-input) strong.magicx-aia-segment--editing::selection {
68
83
  background: transparent;
69
- color: var(--aia-written-text-color, var(--aia-color-text-default, #fff));
70
- caret-color: var(
71
- --aia-caret-color,
72
- var(--aia-written-text-color, var(--aia-color-text-default, #fff))
73
- );
74
- font-family: inherit;
75
- font-size: var(--aia-written-text-font-size, 19px);
76
- line-height: 38px;
77
- white-space: pre-wrap;
78
- word-break: break-word;
79
- outline: none;
80
- resize: none;
81
- overflow: hidden;
84
+ color: inherit;
85
+ }
86
+ :where(.magicx-aia-input) strong.magicx-aia-segment--editing::-moz-selection {
87
+ background: transparent;
88
+ color: inherit;
82
89
  }
83
90
 
84
- .magicx-aia-textarea::placeholder {
91
+ /* Placeholder via ::before so it doesn't enter the editable DOM. */
92
+ .magicx-aia-input[data-aia-empty="true"][data-placeholder]::before {
93
+ content: attr(data-placeholder);
85
94
  color: var(--aia-color-text-muted, #c1c4cb);
95
+ opacity: 0.7;
96
+ pointer-events: none;
86
97
  }
87
98
 
88
- .magicx-aia-textarea--hidden {
89
- color: transparent !important;
99
+ /* Inline pill list container \u2014 a non-editable sibling of the editable that
100
+ flows immediately after it on the same line. The leading margin gives the
101
+ pills a visible gap from the typed text. */
102
+ .magicx-aia-pill-list-container {
103
+ display: inline;
104
+ margin-left: 8px;
105
+ }
106
+
107
+ /* Hide the leading margin when there are no pills so an empty container
108
+ doesn't bias the cursor's resting position to the right. */
109
+ .magicx-aia-pill-list-container:empty {
110
+ margin-left: 0;
90
111
  }
91
112
 
92
113
  /* --- Submit button --- */
@@ -110,7 +131,7 @@
110
131
  opacity: 0.85;
111
132
  }
112
133
 
113
- /* --- Dropdown --- */
134
+ /* --- Dropdown (glassmorphism \u2014 matches the React build) --- */
114
135
  .magicx-aia-dropdown {
115
136
  position: absolute;
116
137
  left: 0;
@@ -118,24 +139,27 @@
118
139
  top: 100%;
119
140
  max-width: 516px;
120
141
  margin-top: 6px;
121
- border-radius: 1rem;
142
+ display: flex;
143
+ flex-direction: column;
122
144
  overflow: hidden;
145
+ container-type: inline-size;
123
146
  z-index: 10;
124
147
  opacity: 0;
125
148
  pointer-events: none;
126
149
  transition: opacity 400ms cubic-bezier(0.4, 0, 0.2, 1);
127
- background:
128
- linear-gradient(hsla(0, 0%, 100%, 0.8), hsla(0, 0%, 100%, 0.8)) padding-box,
129
- linear-gradient(
130
- 98deg,
131
- hsla(0, 0%, 75%, 1),
132
- hsla(0, 0%, 90%, 1) 3%,
133
- hsla(0, 0%, 100%, 0) 50%,
134
- hsla(0, 0%, 90%, 1) 97%,
135
- hsla(0, 0%, 75%, 1) 100%
136
- )
137
- border-box;
138
- border: 1.5px solid transparent;
150
+ box-shadow:
151
+ hsla(0, 0%, 100%, 1) -3.2px -3.2px 3.2px -3.2px inset,
152
+ hsla(0, 0%, 100%, 1) 6.4px 6.4px 1.6px -8px inset,
153
+ var(--aia-dropdown-bg, transparent) -6.4px 6.4px 1.6px -8px inset,
154
+ var(--aia-dropdown-bg, transparent) 6.4px -6.4px 1.6px -8px inset,
155
+ hsla(0, 0%, 100%, 0.15) -1.6px 0px 0px -1.6px inset,
156
+ hsla(0, 0%, 100%, 0.15) 0px -1.6px 0px -1.6px inset,
157
+ hsla(0, 0%, 100%, 0.3) 0px 1.6px 0px 0px inset,
158
+ hsla(0, 0%, 100%, 0.3) 1.6px 0px 0px 0px inset,
159
+ inset 0 0 30px 5px hsla(0, 0%, 0%, 0.05),
160
+ hsla(0, 0%, 0%, 0.08) 0px 0px 30px 2px;
161
+ backdrop-filter: blur(30px);
162
+ border-radius: 28px;
139
163
  }
140
164
 
141
165
  .magicx-aia-dropdown--visible {
@@ -148,6 +172,66 @@
148
172
  padding: 27px 27px 0px 27px;
149
173
  }
150
174
 
175
+ /* --- Loading skeleton (inside dropdown) --- */
176
+ .magicx-aia-skeleton {
177
+ display: flex;
178
+ flex-direction: column;
179
+ gap: 20px;
180
+ padding: 25px;
181
+ }
182
+
183
+ .magicx-aia-skeleton-pills {
184
+ display: flex;
185
+ gap: 5px;
186
+ align-items: center;
187
+ }
188
+
189
+ .magicx-aia-skeleton-pill {
190
+ display: inline-block;
191
+ height: 30px;
192
+ border-radius: 999px;
193
+ background: var(--aia-skeleton-bg, var(--aia-pill-bg, rgba(189, 189, 189, 0.51)));
194
+ opacity: 0.5;
195
+ animation: magicx-aia-skeleton-pulse 1.4s ease-in-out infinite;
196
+ }
197
+
198
+ .magicx-aia-skeleton-pills .magicx-aia-skeleton-pill:nth-child(2) {
199
+ opacity: 0.3;
200
+ }
201
+
202
+ .magicx-aia-skeleton-bars {
203
+ display: flex;
204
+ flex-direction: column;
205
+ gap: 20px;
206
+ }
207
+
208
+ .magicx-aia-skeleton-bar {
209
+ display: block;
210
+ height: 19px;
211
+ border-radius: 999px;
212
+ background: var(--aia-skeleton-bg, var(--aia-pill-bg, rgba(189, 189, 189, 0.51)));
213
+ opacity: 0.5;
214
+ animation: magicx-aia-skeleton-pulse 1.4s ease-in-out infinite;
215
+ }
216
+
217
+ .magicx-aia-skeleton-bar:nth-child(2) {
218
+ animation-delay: 150ms;
219
+ }
220
+
221
+ .magicx-aia-skeleton-bar:nth-child(3) {
222
+ animation-delay: 300ms;
223
+ }
224
+
225
+ @keyframes magicx-aia-skeleton-pulse {
226
+ 0%,
227
+ 100% {
228
+ opacity: 0.5;
229
+ }
230
+ 50% {
231
+ opacity: 0.25;
232
+ }
233
+ }
234
+
151
235
  /* --- Pill list --- */
152
236
  .magicx-aia-pill-list {
153
237
  position: relative;
@@ -176,7 +260,7 @@
176
260
  transparent
177
261
  );
178
262
  color: var(--aia-pill-color, var(--aia-color-text-muted, #c1c4cb));
179
- font-family: "IBM Plex Sans", sans-serif;
263
+ font-family: inherit;
180
264
  font-size: var(--aia-pill-font-size, 19px);
181
265
  line-height: 30px;
182
266
  cursor: pointer;
@@ -208,6 +292,31 @@
208
292
  outline: 1px solid #5a5b8a;
209
293
  }
210
294
 
295
+ .magicx-aia-pill--skeleton {
296
+ pointer-events: none;
297
+ cursor: default;
298
+ height: 30px;
299
+ padding: 0;
300
+ background: var(--aia-skeleton-bg, var(--aia-pill-bg, rgba(189, 189, 189, 0.51)));
301
+ box-shadow: none;
302
+ backdrop-filter: none;
303
+ animation: magicx-aia-pill-skeleton-pulse 1.4s ease-in-out infinite;
304
+ }
305
+
306
+ .magicx-aia-pill--skeleton:hover {
307
+ filter: none;
308
+ }
309
+
310
+ @keyframes magicx-aia-pill-skeleton-pulse {
311
+ 0%,
312
+ 100% {
313
+ filter: brightness(1);
314
+ }
315
+ 50% {
316
+ filter: brightness(0.7);
317
+ }
318
+ }
319
+
211
320
  @keyframes magicx-aia-fadeIn {
212
321
  from {
213
322
  opacity: 0;
@@ -218,6 +327,9 @@
218
327
  .magicx-aia-grid {
219
328
  display: grid;
220
329
  grid-template-columns: minmax(0, 250px);
330
+ /* Pack rows from the top instead of stretching to fill the grid container. */
331
+ grid-auto-rows: min-content;
332
+ align-content: start;
221
333
  justify-content: start;
222
334
  padding: 8px 8px;
223
335
  max-height: 192px;
@@ -250,8 +362,10 @@
250
362
  position: relative;
251
363
  overflow: visible;
252
364
  display: flex;
253
- align-items: center;
254
- font-family: "IBM Plex Sans", sans-serif;
365
+ /* Top-align so single-line and multi-line options in the same row share
366
+ the same baseline at the top edge of the cell. */
367
+ align-items: flex-start;
368
+ font-family: inherit;
255
369
  font-size: var(--aia-option-font-size, 19px);
256
370
  line-height: 24px;
257
371
  color: var(--aia-option-color, var(--aia-color-text-muted, #c1c4cb));
@@ -616,6 +730,8 @@
616
730
 
617
731
  --aia-color-text-muted: #6b7280;
618
732
 
733
+ --aia-skeleton-bg: rgba(189, 189, 189, 0.51);
734
+
619
735
  --aia-streak-rgb: 99, 102, 241;
620
736
  --aia-streak-glass-bg: rgba(99, 102, 241, 0.1);
621
737
  }
@@ -640,6 +756,8 @@
640
756
 
641
757
  --aia-color-text-muted: #c1c4cb;
642
758
 
759
+ --aia-skeleton-bg: #333539;
760
+
643
761
  --aia-streak-rgb: 255, 255, 255;
644
762
  --aia-streak-glass-bg: rgba(255, 255, 255, 0.1);
645
763
  }
@@ -664,5 +782,5 @@
664
782
  animation-duration: 0s !important;
665
783
  transition-duration: 0s !important;
666
784
  }
667
- `;var Oe=0;function Ie(){return`:ac-${++Oe}:`}function ie(){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 H=class{constructor(e,t={}){this.store=F(ie());this._listboxId=Ie();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 M(this.store,{onPillSelected:({rawQuery:i,selectedPill:s,otherPills:r})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:s,other_pills:r})}}),this.fetchController=new D(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.opts.onError,()=>this.sessionId,{onAutoMatch:({active:i,matched:s,rawQuery:r})=>{this.fireTelemetry("option",{raw_query:r,selected_option:s.text,other_options:(i.options??[]).filter(n=>n.text!==s.text).map(n=>n.text)})}}),this.keyboardController=new k(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,s)=>{this.recomputeDerived(i,s)})),this.unsubscribers.push(this.store.subscribe((i,s)=>{i.text!==s.text&&this.opts.onChange?.(i.text),i.completedParams!==s.completedParams&&this.opts.onParamsChange?.(i.completedParams),i.isFocused!==s.isFocused&&(i.isFocused?this.opts.onFocus?.():this.opts.onBlur?.()),this.opts.onStateChange?.(i)})),this.renderMode!=="headless"&&(te(),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({...ie(),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{rawQuery:s}=y(t.text,t.completedParams);this.fireTelemetry("option",{raw_query:s,selected_option:e.text,other_options:t.filteredOptions.filter(g=>g.text!==e.text).map(g=>g.text)});let r=t.filterBase,n=t.text.slice(0,r),c=n.length===0&&t.text.length===0,a=n.length===0&&t.text.length>0&&t.placeholderText.length>0&&t.placeholderText.toLowerCase().startsWith(t.text.toLowerCase());(c||a)&&t.placeholderText&&(n=`${t.placeholderText} `);let l=Q(n,e.text);l>0&&(n=n.slice(0,n.length-l));let d=n.length>0&&n[n.length-1]!==" ",p=`${n}${d?" ":""}${e.text} `,m=(c||a)&&p.length>0?p[0].toUpperCase()+p.slice(1):p,u=m.toLowerCase().lastIndexOf(e.text.toLowerCase()),h=u>=0?m.slice(u,u+e.text.length):e.text,x={id:crypto.randomUUID(),placeholder:"",type:i.type,text:h,kind:e.kind,suggestionType:i.type,suggestionPlaceholder:i.text,options:i.options??[],metadata:e.metadata},f=t.actionableSuggestions.length-1;this.store.set(g=>({text:m,filterBase:m.length,completedParams:[...g.completedParams,x],newParamId:x.id,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:f>0})),this.suggestionRemovalTimer=window.setTimeout(()=>{this.store.set(g=>({suggestions:g.suggestions.filter(b=>b!==i)}))},400)}fireTelemetry(e,t){let i=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");G({source:i,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}recomputeDerived(e,t){if(this.derivedInProgress)return;this.derivedInProgress=!0;let i=U(e.text,e.completedParams),s=e.suggestions.filter(g=>g.type!=="placeholder"),r=s[0],n=r?this.opts.optionOverrides?.[r.type]:void 0,c=Math.min(e.filterBase,e.text.length),l=e.lastRawQuery!==""||c>0?v(e.text,c,e.filterInProgress):"",d=r?n?n(l.trim()):r.options??[]:[],p=w(d,l),m=e.suggestions.filter(g=>g.type==="placeholder").map(g=>g.text).join(" "),u=this.opts.dropdownTrigger??"auto",h=this.opts.closeDropdownOnBlur??!0,x=!1;if(u==="auto"){let g=h?e.isFocused:!0;x=!e.isLoading&&p.length>0&&g}else u==="manual"&&(x=!e.isLoading&&p.length>0&&e.pillTapped);this.store.set({segments:i,actionableSuggestions:s,filteredOptions:p,placeholderText:m,isDropdownOpen:x}),this.derivedInProgress=!1;let f=this.store.get();for(let g of this.externalListeners)g(f)}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 P(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=ee(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&$(this.domRefs,this.store.get(),t)}),$(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=J(this.container,e),this.subscribeBatchedRender(()=>{this.dropdownRefs&&K(this.dropdownRefs,this.store.get(),e)}),K(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:s}=j(e,t.completedParams);s.length>0&&this.store.set(r=>({completedParams:i,suggestions:[...s.map(n=>({type:n.suggestionType,text:n.suggestionPlaceholder,required:!0,options:n.options})),...r.suggestions]}))}};0&&(module.exports={AIAutocomplete,createStore});
785
+ `;var Je=0;function Ye(){return`:ac-${++Je}:`}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}}var G=class{constructor(e,t={}){this.store=j(Te());this._listboxId=Ye();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 $(this.store,{onPillSelected:({rawQuery:n,selectedPill:s,otherPills:r})=>{this.fireTelemetry("pill",{raw_query:n,selected_pill:s,other_pills:r})}}),this.fetchController=new F(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"&&(Pe(),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.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],c=n.indexOf(a.text,r);if(c===-1)continue;let l=c,p=c+a.text.length;if(e>l&&e<=p){let d=ge(n,e),u=n.slice(0,d)+n.slice(e),x=s.filter((f,b)=>b!==o);return this.store.set(f=>({text:u,filterBase:Math.min(f.filterBase,u.length),completedParams:x,pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(d),!0}r=p}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(c=>c.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(c=>({text:o,completedParams:c.completedParams.filter(l=>l.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}=P(t.text,t.completedParams);this.fireTelemetry("option",{raw_query:s,selected_option:e.text,other_options:t.filteredOptions.filter(m=>m.text!==e.text).map(m=>m.text)});let r=t.filterBase,o=t.text.slice(0,r),a=o.length===0&&t.text.length===0,c=o.length===0&&t.text.length>0&&t.placeholderText.length>0&&t.placeholderText.toLowerCase().startsWith(t.text.toLowerCase());(a||c)&&t.placeholderText&&(o=`${t.placeholderText} `);let l=ee(o,e.text);l>0&&(o=o.slice(0,o.length-l));let p=o.length>0&&o[o.length-1]!==" ",d=`${o}${p?" ":""}${e.text} `,u=(a||c)&&d.length>0?d[0].toUpperCase()+d.slice(1):d,x=u.toLowerCase().lastIndexOf(e.text.toLowerCase()),f=x>=0?u.slice(x,x+e.text.length):e.text,b={id:crypto.randomUUID(),placeholder:"",type:n.type,text:f,kind:e.kind,suggestionType:n.type,suggestionPlaceholder:n.text,options:n.options??[],metadata:e.metadata},h=t.actionableSuggestions.length-1;this.store.set(m=>({text:u,filterBase:u.length,completedParams:[...m.completedParams,b],newParamId:b.id,caretOffset:u.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:h>0})),this.suggestionRemovalTimer=window.setTimeout(()=>{this.store.set(m=>({suggestions:m.suggestions.filter(g=>g!==n)}))},400)}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:P(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:n.options.filter(m=>m.text!==e.text).map(m=>m.text)});let o=t.text.slice(0,s),a=t.text.slice(r),c=s===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,l=a.length===0||a[0]!==" ",p=l?`${c} `:c,d=o+p+a,u=s+p.length+(l?0:1),x={id:crypto.randomUUID(),placeholder:"",type:n.suggestionType,text:c,kind:e.kind,suggestionType:n.suggestionType,suggestionPlaceholder:n.suggestionPlaceholder,options:n.options,metadata:e.metadata},f=t.completedParams.findIndex(m=>m.id===n.id),b=t.completedParams.filter(m=>m.id!==n.id),h=f>=0?Math.min(f,b.length):b.length;b.splice(h,0,x),this.store.set({text:d,completedParams:b,newParamId:x.id,filterBase:u,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:u,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0}),this.scheduleSetCursor(u)}fireTelemetry(e,t){let n=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");oe({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=te(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(" "),c=I(e.text,Math.min(e.filterBase,e.text.length),a),p=e.lastRawQuery!==""||c>0?w(e.text,c,e.filterInProgress):"",d=r?o?o(p.trim()):r.options??[]:[],u=e.editingParam!=null&&e.editingAnchor!=null,x;if(u&&e.editingParam&&e.editingAnchor!=null){let g=e.editingParam.id,y=e.completedParams.some(L=>L.id===g),v=e.caretOffset??e.editingAnchor,T=y?"":e.text.slice(e.editingAnchor,v);x=A(e.editingParam.options,T)}else x=A(d,p);let f=this.opts.dropdownTrigger??"auto",b=this.opts.closeDropdownOnBlur??!0,h=!1;if(u){let g=b?e.isFocused:!0;h=x.length>0&&g}else if(f==="auto"){let g=b?e.isFocused:!0,y=e.text.replace(/\s+$/,"").length,v=e.caretOffset==null||e.caretOffset>=y;h=(x.length>0||e.isLoading)&&g&&v}else f==="manual"&&(h=(x.length>0||e.isLoading)&&e.pillTapped);this.store.set({segments:n,actionableSuggestions:s,filteredOptions:x,placeholderText:a,isDropdownOpen:h}),this.derivedInProgress=!1;let m=this.store.get();for(let g of this.externalListeners)g(m)}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=Se(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&Y(this.domRefs,this.store.get(),t)}),Y(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=ye(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.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}=ne(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=I(e,t.filterBase,r),a=w(e,o,t.filterInProgress),c=E(s.options,a);if(!c)return;let l=c.text.toLowerCase(),p=e.toLowerCase().lastIndexOf(l),d=p>=0?p:Math.max(0,e.length-c.text.length),u=d+c.text.length,x=e.slice(d,u),f=e,h=u<e.length&&e[u]===" "?u+1:u,m={id:crypto.randomUUID(),placeholder:"",type:s.type,text:x,kind:c.kind,suggestionType:s.type,suggestionPlaceholder:s.text,options:s.options??[],metadata:c.metadata};this.store.set(g=>({text:f,completedParams:[...g.completedParams,m],suggestions:g.suggestions.filter(y=>y!==s),filterBase:h,newParamId:m.id,caretOffset:h,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(),c=r.toLowerCase().lastIndexOf(a),l=n+Math.max(0,c),p=l+o.text.length,d=e.text.slice(l,p),u=e.text,f=p<e.text.length&&e.text[p]===" "?p+1:p,b={id:crypto.randomUUID(),placeholder:"",type:t.suggestionType,text:d,kind:o.kind,suggestionType:t.suggestionType,suggestionPlaceholder:t.suggestionPlaceholder,options:t.options,metadata:o.metadata},h=e.completedParams.length,m=0;for(let y=0;y<e.completedParams.length;y++){let v=u.indexOf(e.completedParams[y].text,m);if(v!==-1){if(v>=f){h=y;break}m=v+e.completedParams[y].text.length}}let g=[...e.completedParams];g.splice(h,0,b),this.store.set(()=>({text:u,completedParams:g,newParamId:b.id,filterBase:f,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:f,activeDropdownIndex:-1})),this.scheduleSetCursor(f)}};0&&(module.exports={AIAutocomplete,createStore});
668
786
  //# sourceMappingURL=index.js.map