@magicx-eng/ai-autocomplete-vanilla 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var L=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;this.inFlightRefresh=null;e.accessToken&&(this.current=e.accessToken)}async getToken(e=!1){if(!e&&this.current&&!this.isExpired())return this.current;if(!e&&this.inFlightRefresh)return this.inFlightRefresh;this.inFlightRefresh=this.refresh();try{return await this.inFlightRefresh}finally{this.inFlightRefresh=null}}async refresh(){let e=await this.config.getAccessToken();return this.current=e.accessToken,this.expiresAt=e.expiresAt??null,this.current}isExpired(){return this.expiresAt==null?!1:Date.now()>=this.expiresAt-3e4}};var _e="https://api.ai-autocomplete.com",k=`${_e}/api/suggest`,de=new WeakMap;function D(n){return n?.type==="accessToken"}function Ne(n){if(!(!n||D(n)))return n}function R(n){let e=de.get(n.getAccessToken);return e||(e=new L(n),de.set(n.getAccessToken,e)),e}function _(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function N(n){let e=Ne(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}var Fe="0.2.0",ce=!1;function He(){return crypto.randomUUID()}function Be(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.text},kind:n.kind}}function Ke(n,e,t,i){let r=e.find(o=>o.type==="contact"&&o.metadata?.contact_account_count)?.metadata?.contact_account_count,s=typeof r=="number"?r:void 0;return{data:{raw_query:n,completed_params:e.map(o=>Be(o,t)),...s!=null&&{contact_account_count:s}},meta:{request_id:He(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:Fe,session_id:i}}}async function pe(n,e,t,i,r){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:r})}async function ue(n,e,t){let i=t.apiConfig,r=!t.maskCompletedText,s=Ke(n,e,r,t.sessionId),o=_(i),a=i?.endpoint??k,l=JSON.stringify(s);if(D(i)){let c=R(i),m=await c.getToken(),b=await pe(a,o,m,l,t.signal);if(b.status===401){let g=await c.getToken(!0);b=await pe(a,o,g,l,t.signal)}if(!b.ok)throw new Error(`API error: ${b.status} ${b.statusText}`);return b.json()}let d=N(i);!d&&!ce&&(ce=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),d&&(o.Authorization=d);let p=await fetch(a,{method:"POST",headers:o,body:l,signal:t.signal});if(!p.ok)throw new Error(`API error: ${p.status} ${p.statusText}`);return p.json()}function v(n,e){let t=n,i={},r=[];for(let s of e){let o=(i[s.type]??0)+1;i[s.type]=o;let l=`{{${s.type.toUpperCase().replace(/\s+/g,"_")}_${o}}}`,d=t.indexOf(s.text);d!==-1&&(t=t.slice(0,d)+l+t.slice(d+s.text.length)),r.push({...s,placeholder:l})}return{rawQuery:t,completedParams:r}}function A(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function w(n,e,t){let i=n.slice(e);if(t||e===0||n[e-1]===" ")return i;let r=i.indexOf(" ");return r===-1?"":i.slice(r+1)}function me(n,e){let t=n.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let i=t.split(" "),r=e.toLowerCase();for(let s=0;s<i.length;s++){let o=i.slice(s).join(" ");if(r.startsWith(o.toLowerCase())){let a=t.length-o.length;return n.length-a}}return 0}function E(n,e){if(!n)return[];let t=e.trimStart();if(!t)return n;let i=t.toLowerCase();return n.filter(r=>!r.is_tappable||r.text.toLowerCase().includes(i))}function I(n,e){if(!n)return null;let t=e.trim();if(!t)return null;let i=t.toLowerCase();return n.find(r=>r.is_tappable&&r.text.toLowerCase()===i)??null}function ge(n,e){return e?n.map(t=>{let i=e[t.type];if(!i)return t;let r=i("");if(r.length===0)return t;let s=new Set(r.map(a=>a.text)),o=(t.options??[]).filter(a=>!s.has(a.text));return{...t,options:[...r,...o]}}):n}var Qe=100,$e=300,Ue=2,F=class{constructor(e,t,i,r,s,o,a={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=r;this.getOnError=s;this.getSessionId=o;this.callbacks=a;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null}start(){this.doFetch("",[]);let e=this.store.get().text,t=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(i=>{(i.text!==e||i.completedParams!==t)&&(e=i.text,t=i.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let i=new AbortController;this.abortController=i;let r=++this.fetchVersion,s=this.store.get().text.length;this.store.set({isLoading:!0,error:null});try{let o=await ue(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig()});if(r!==this.fetchVersion)return;let a=ge(o.data.suggestions??[],this.getOptionOverrides()),l=o.data.input??[],d=l[l.length-1],p=this.store.get().text,c,m;if(d?.state==="in_progress"){m=!0;let f=p.toLowerCase().lastIndexOf(d.text.toLowerCase());c=f!==-1?f:s}else m=!1,c=s;let g=a.filter(f=>f.type!=="placeholder")[0],h=null;if(g){let f=w(p,c,m),u=I(g.options,f);u&&(h={id:crypto.randomUUID(),placeholder:"",type:g.type,text:u.text,kind:u.kind,suggestionType:g.type,suggestionPlaceholder:g.text,options:g.options??[],metadata:u.metadata},a=a.filter(x=>x!==g),this.callbacks.onAutoMatch?.({active:g,matched:u,rawQuery:e}))}this.store.set(f=>({suggestions:a,isLoading:!1,isReady:o.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:c,filterInProgress:m,...h?{completedParams:[...f.completedParams,h]}:{}}))}catch(o){if(r===this.fetchVersion){let a=o instanceof Error?o:new Error(String(o));this.store.set({error:a,isLoading:!1}),this.getOnError()?.(a)}}}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}let t=i=>{let r=this.store.get();if(!r.text&&r.completedParams.length===0)return this.doFetch("",[]),!0;let s=r.suggestions.filter(x=>x.type==="placeholder").map(x=>x.text).join(" "),o=A(r.text,r.filterBase,s),a=w(r.text,o,r.filterInProgress),d=r.suggestions.filter(x=>x.type!=="placeholder")[0],c=(d?E(d.options,a):[]).filter(x=>x.is_tappable),m=d?I(d.options,a)!==null:!1,b=a.trim().length>0;if(c.length>0&&!m&&b||r.completedParams.length===0&&r.text.length>0&&s.length>0&&s.toLowerCase().startsWith(r.text.toLowerCase()))return!1;let{rawQuery:g,completedParams:h}=v(r.text,r.completedParams),f=g.length<r.lastRawQuery.length,u=Math.abs(g.length-r.lastRawQuery.length);return f||u>=i?(this.doFetch(g,h),!0):!1};this.debounceTimer=setTimeout(()=>{t(Ue)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},Qe),this.slowDebounceTimer=setTimeout(()=>t(1),$e)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var he='[contenteditable="false"]',O;function qe(){if(O!==void 0)return O;let n=globalThis.Intl.Segmenter;if(!n)return O=null,null;try{O=new n(void 0,{granularity:"grapheme"})}catch{O=null}return O??null}function H(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(he))return!0;t=t.parentNode}return!1}function B(n){return(n.ownerDocument??document).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return H(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function K(n){let e=B(n),t="",i=e.nextNode();for(;i;)t+=i.data,i=e.nextNode();return t}function Y(n){let e=B(n),t=0,i=e.nextNode();for(;i;)t+=i.data.length,i=e.nextNode();return t}function T(n){let e=(n.ownerDocument??document).getSelection();if(!e||e.rangeCount===0)return null;let t=e.anchorNode,i=e.anchorOffset;if(!t||!n.contains(t))return null;if(t.nodeType===Node.ELEMENT_NODE){let r=t;if(H(r,n)&&r!==n)return null;let s=0;for(let o=0;o<i&&o<r.childNodes.length;o++)s+=xe(r.childNodes[o],n);return s+fe(r,n)}return t.nodeType!==Node.TEXT_NODE||H(t,n)?null:fe(t,n)+i}function xe(n,e){if(n.nodeType===Node.TEXT_NODE)return H(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(he))return 0;let i=0;for(let r of Array.from(t.childNodes))i+=xe(r,e);return i}function fe(n,e){let t=B(e),i=0,r=t.nextNode();for(;r;){if(r===n||n.nodeType===Node.ELEMENT_NODE&&n.contains(r))return i;i+=r.data.length,r=t.nextNode()}return i}function P(n,e){let t=n.ownerDocument??document,i=t.getSelection();if(!i)return;let r=Math.max(0,Math.min(e,Y(n))),s=B(n),o=0,a=null,l=0,d=s.nextNode(),p=null;for(;d;){let m=d.data.length;if(r<o+m){a=d,l=r-o;break}if(r===o+m){let b=s.nextNode();b?(a=b,l=0):(a=d,l=m);break}o+=m,p=d,d=s.nextNode()}let c=t.createRange();if(a){let m=a.parentElement?.closest('strong[data-seg="completed"]');m&&m!==n&&n.contains(m)?l===0?c.setStartBefore(m):l===a.data.length?c.setStartAfter(m):c.setStart(a,l):c.setStart(a,l)}else p?c.setStart(p,p.data.length):c.setStart(n,0);c.collapse(!0),i.removeAllRanges(),i.addRange(c)}function J(n){let e=T(n);return e==null?!1:e>=Y(n)}function Z(n,e){if(e<=0)return 0;let t=qe();if(!t)return e-1;let i=n.slice(0,e),r=0;for(let{index:s}of t.segment(i))s<e&&(r=s);return r}function ee(n){return n instanceof HTMLTextAreaElement||n instanceof HTMLInputElement?n.selectionStart!=null&&n.selectionStart===n.value.length:n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?J(n):!1}function We(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?T(n):null}var Q=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:r}=this.ctx,s=this.getEffectiveColumns(),o=r(),a=this.getTappableIndices(s);if((e.shiftKey||e.metaKey||e.ctrlKey||e.altKey)&&(e.key==="ArrowDown"||e.key==="ArrowUp"||e.key==="ArrowLeft"||e.key==="ArrowRight"))return;let l=this.ctx.getOptionsPosition()==="above";switch(e.key){case"ArrowDown":{let d=ee(e.target),p=!!t.editingParam;if(!d&&!p&&t.activeDropdownIndex<0)break;if(t.activeDropdownIndex<0){if(l)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;this.store.set({activeDropdownIndex:a[0]});break}if(e.preventDefault(),a.length===0)return;if(t.filteredOptions.length>0){let b=Math.floor((t.filteredOptions.length-1)/s);if(Math.floor(t.activeDropdownIndex/s)===b){this.store.set({activeDropdownIndex:-1});break}}let c=a.indexOf(t.activeDropdownIndex),m=c<a.length-1?c+1:0;this.store.set({activeDropdownIndex:a[m]});break}case"ArrowUp":{if(t.activeDropdownIndex<0){if(!l)break;let c=ee(e.target),m=!!t.editingParam;if(!c&&!m)break;e.preventDefault();let b=this.firstTappableInBottomRow(s)??a[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:b});break}if(a.length===0)return;this.store.set({activeDropdownIndex:b});break}if(a.length===0)break;if(e.preventDefault(),t.activeDropdownIndex<s){this.store.set({activeDropdownIndex:-1});break}let d=a.indexOf(t.activeDropdownIndex),p=d>0?d-1:a.length-1;this.store.set({activeDropdownIndex:a[p]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%s<s-1){let c=t.activeDropdownIndex+1;c<t.filteredOptions.length&&t.filteredOptions[c]?.is_tappable&&this.store.set({activeDropdownIndex:c})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let p=e.target.closest("[data-aia-input]")??e.target,c=t.editingTail;this.ctx.exitEditMode?.(),P(p,c);break}ee(e.target)&&t.actionableSuggestions.length>1&&(e.preventDefault(),this.pillsSetActivePill(1));break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%s>0){let d=t.activeDropdownIndex-1;d>=0&&t.filteredOptions[d]?.is_tappable&&this.store.set({activeDropdownIndex:d})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let d=e.target.closest("[data-aia-input]")??e.target,p=t.editingAnchor;this.ctx.exitEditMode?.(),P(d,p);break}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let d=We(e.target);if(d==null)break;this.ctx.removeParamAtCaret(d)&&e.preventDefault();break}case"Enter":{if(e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable)this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i);else if(o){let{rawQuery:d,completedParams:p}=v(t.text,t.completedParams);o({query:t.text.trim(),raw_query:d,completed_params:p}),this.ctx.afterSubmit?.()}break}case"Tab":{let d=!t.text&&!!t.placeholderText,p=t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable;if(d&&!p){e.preventDefault();let c=t.placeholderText;if(this.store.set(m=>({text:c,filterBase:c.length,suggestions:m.suggestions.filter(b=>b.type!=="placeholder")})),e.target instanceof HTMLElement){let m=e.target.closest("[data-aia-input]")??e.target;queueMicrotask(()=>P(m,c.length))}}else if(p)e.preventDefault(),this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i);else if(t.isDropdownOpen){let c=t.filteredOptions.findIndex(m=>m.is_tappable);c>=0&&(e.preventDefault(),this.clickOrSelect(c,t.filteredOptions,i))}break}case"Escape":{if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){let d=e.target.closest("[data-aia-input]")??e.target,p=t.editingTail;this.ctx.exitEditMode?.(),P(d,p)}this.store.set({activeDropdownIndex:-1});break}}}firstTappableInBottomRow(e){let t=this.store.get();if(t.filteredOptions.length===0)return null;let r=Math.floor((t.filteredOptions.length-1)/e)*e;for(let s=r;s<t.filteredOptions.length;s++)if(t.filteredOptions[s]?.is_tappable)return s;return null}getTappableIndices(e){let i=this.store.get().filteredOptions.map((s,o)=>s.is_tappable?o:-1).filter(s=>s!==-1),r=Array.from({length:e},()=>[]);for(let s of i)r[s%e].push(s);return r.flat()}getEffectiveColumns(){let t=document.getElementById(`${this.ctx.listboxId}-option-0`)?.parentElement;if(!t)return this.ctx.columns;let i=getComputedStyle(t).gridTemplateColumns.split(" ").filter(Boolean).length;return i>0?i:this.ctx.columns}clickOrSelect(e,t,i){let r=document.getElementById(`${i}-option-${e}`);r?r.click():this.ctx.selectOption(t[e])}pillsSetActivePill(e){let t=this.store.get(),i=t.suggestions.filter(a=>a.type!=="placeholder");if(e<0||e>=i.length)return;let r=i[e],s=i.filter((a,l)=>l!==e),o=t.suggestions.filter(a=>a.type==="placeholder");this.store.set({suggestions:[...o,r,...s],pillTapped:!0,activeDropdownIndex:-1})}};var $=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),i=t.suggestions.filter(a=>a.type!=="placeholder");if(e<0||e>=i.length)return;let r=i[e],s=i.filter((a,l)=>l!==e),o=t.suggestions.filter(a=>a.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:a}=v(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:a,selectedPill:r.text,otherPills:s.map(l=>l.text)})}this.store.set({suggestions:[...o,r,...s],pillTapped:!0,activeDropdownIndex:-1})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};function be(n,e){let t=[],i=0;for(let s of e){let o=n.indexOf(s.text,i);o!==-1&&(o>i&&t.push({type:"text",value:n.slice(i,o)}),t.push({type:"completed",value:s.text,param:s}),i=o+s.text.length)}let r=n.slice(i);return r&&t.push({type:"text",value:r}),t}function ye(n,e){let t=[],i=[],r=0;for(let s of e){let o=n.indexOf(s.text,r);o===-1?i.push(s):(t.push(s),r=o+s.text.length)}return{valid:t,invalid:i}}function Se(n,e){let t=e.dropdownTrigger??"auto",i=e.closeDropdownOnBlur??!0,r=n.filteredOptionsLength>0;if(n.inEditMode){let s=i?n.isFocused:!0;return r&&s}if(t==="auto"){let s=i?n.isFocused:!0,o=n.text.replace(/\s+$/,"").length,a=n.caretOffset==null||n.caretOffset>=o;return(r||n.isLoading)&&s&&a}return t==="manual"?(r||n.isLoading)&&n.pillTapped:!1}function ve(n,e){let t=be(n.text,n.completedParams),i=n.suggestions.filter(g=>g.type!=="placeholder"),r=i[0],s=r?e.optionOverrides?.[r.type]:void 0,o=n.suggestions.filter(g=>g.type==="placeholder").map(g=>g.text).join(" "),a=A(n.text,Math.min(n.filterBase,n.text.length),o),d=n.lastRawQuery!==""||a>0?w(n.text,a,n.filterInProgress):"",p=r?s?s(d.trim()):r.options??[]:[],c=n.editingParam!=null&&n.editingAnchor!=null,m;if(c&&n.editingParam&&n.editingAnchor!=null){let g=n.editingParam.id,h=n.completedParams.some(x=>x.id===g),f=n.caretOffset??n.editingAnchor,u=h?"":n.text.slice(n.editingAnchor,f);m=E(n.editingParam.options,u)}else m=E(p,d);e.showNonTappableOptions===!1&&(m=m.filter(g=>g.is_tappable));let b=Se({inEditMode:c,filteredOptionsLength:m.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading,pillTapped:n.pillTapped},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur});return{segments:t,actionableSuggestions:i,filteredOptions:m,placeholderText:o,isDropdownOpen:b}}function U(n){return n.mode==="fresh"?Ge(n):je(n)}function Ge(n){let{text:e,completedParams:t,suggestions:i,filterBase:r,filterInProgress:s}=n,a=i.filter(S=>S.type!=="placeholder")[0];if(!a?.options)return null;let l=i.filter(S=>S.type==="placeholder").map(S=>S.text).join(" "),d=A(e,r,l),p=w(e,d,s),c=I(a.options,p);if(!c)return null;let m=c.text.toLowerCase(),b=e.toLowerCase().lastIndexOf(m),g=b>=0?b:Math.max(0,e.length-c.text.length),h=g+c.text.length,f=e.slice(g,h),x=h<e.length&&e[h]===" "?h+1:h,y={id:crypto.randomUUID(),placeholder:"",type:a.type,text:f,kind:c.kind,suggestionType:a.type,suggestionPlaceholder:a.text,options:a.options??[],metadata:c.metadata};return{patch:{text:e,completedParams:[...t,y],suggestions:i.filter(S=>S!==a),filterBase:x,newParamId:y.id,caretOffset:x,activeDropdownIndex:-1},caretPos:x}}function je(n){let{text:e,completedParams:t,editingParam:i,editingAnchor:r,editingTail:s}=n;if(t.some(y=>y.id===i.id))return null;let o=e.slice(r,s),a=I(i.options,o);if(!a)return null;let l=a.text.toLowerCase(),d=o.toLowerCase().lastIndexOf(l),p=r+Math.max(0,d),c=p+a.text.length,m=e.slice(p,c),g=c<e.length&&e[c]===" "?c+1:c,h={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:m,kind:a.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:a.metadata},f=t.length,u=0;for(let y=0;y<t.length;y++){let S=e.indexOf(t[y].text,u);if(S!==-1){if(S>=g){f=y;break}u=S+t[y].text.length}}let x=[...t];return x.splice(f,0,h),{patch:{text:e,completedParams:x,newParamId:h.id,filterBase:g,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:g,activeDropdownIndex:-1},caretPos:g}}var q=class{constructor(e){this.deps=e}start(e){let t=this.deps.store.get();if(t.editingParam?.id===e)return;let i=t.completedParams.find(o=>o.id===e);if(!i)return;let r=0,s=-1;for(let o of t.completedParams){let a=t.text.indexOf(o.text,r);if(a!==-1){if(o.id===e){s=a;break}r=a+o.text.length}}s<0||this.deps.store.set({editingParam:i,editingAnchor:s,editingTail:s+i.text.length,caretOffset:s+i.text.length,activeDropdownIndex:-1})}exit(){this.deps.store.get().editingParam&&this.deps.store.set({editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1})}replaceRange(e){let t=this.deps.store.get(),i=t.editingParam,r=t.editingAnchor,s=t.editingTail;if(!i||r==null||s==null||!t.completedParams.some(l=>l.id===i.id))return!1;let o=t.text.slice(0,r)+e+t.text.slice(s),a=r+e.length;return this.deps.store.set(l=>({text:o,completedParams:l.completedParams.filter(d=>d.id!==i.id),editingTail:a,caretOffset:a,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(a),this.tryPromote(),!0}caretAfterInput(e){let t=this.deps.store.get(),i={caretOffset:e};t.editingParam&&t.editingAnchor!=null&&e!=null&&(e<t.editingAnchor?(i.editingParam=null,i.editingAnchor=null,i.editingTail=null,i.activeDropdownIndex=-1):t.editingTail!=null&&(i.editingTail=Math.max(t.editingTail,e))),this.deps.store.set(i),this.tryPromote()}caretMove(e){let t=this.deps.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null&&e!=null&&(e<t.editingAnchor||e>t.editingTail)){this.deps.store.set({caretOffset:e,editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1});return}this.deps.store.set({caretOffset:e})}selectOption(e){let t=this.deps.store.get(),i=t.editingParam,r=t.editingAnchor,s=t.editingTail;if(!i||r==null||s==null)return;this.deps.fireTelemetry("option",{raw_query:v(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:i.options.filter(u=>u.text!==e.text).map(u=>u.text)});let o=t.text.slice(0,r),a=t.text.slice(s),l=r===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,d=a.length===0||a[0]!==" ",p=d?`${l} `:l,c=o+p+a,m=r+p.length+(d?0:1),b={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:l,kind:e.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:e.metadata},g=t.completedParams.findIndex(u=>u.id===i.id),h=t.completedParams.filter(u=>u.id!==i.id),f=g>=0?Math.min(g,h.length):h.length;h.splice(f,0,b),this.deps.store.set({text:c,completedParams:h,newParamId:b.id,filterBase:m,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:m,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.deps.startSelectionAnimationTimer(),this.deps.scheduleSetCursor(m)}tryPromote(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let t=U({mode:"edit",text:e.text,completedParams:e.completedParams,editingParam:e.editingParam,editingAnchor:e.editingAnchor,editingTail:e.editingTail});t&&(this.deps.store.set(t.patch),this.deps.scheduleSetCursor(t.caretPos))}};var Pe="data-aia-key";function W(n,e,t){let i=new Map;for(let o of Array.from(n.children)){let a=o.getAttribute(Pe);a!=null&&i.set(a,o)}let r=new Set,s=[];for(let o=0;o<e.length;o++){let a=e[o],l=t.keyOf(a,o);r.add(l);let d=i.get(l);d||(d=t.create(a,o),d.setAttribute(Pe,l)),t.update?.(d,a,o),n.children[o]!==d&&n.insertBefore(d,n.children[o]??null),s.push(d)}for(let[o,a]of i)r.has(o)||a.remove();return s}var Te=[125,69];function Ce(n){return n===0?.4:n===1?.3:.15}function G(n,e,t,i,r=!1,s=!1){let o=n.querySelector(".magicx-aia-pill-list");if(o||(o=document.createElement("span"),o.className="magicx-aia-pill-list",n.appendChild(o)),s&&e.length===0){o.setAttribute("data-aia-pill-list-loading",""),o.innerHTML="";for(let a=0;a<Te.length;a++){let l=Te[a],d=document.createElement("span");d.setAttribute("data-aia-pill-skeleton",""),d.className=`magicx-aia-pill magicx-aia-pill--skeleton${r?" magicx-aia-pill--rounded":""}`,d.style.width=`${l}px`,d.style.opacity=String(Ce(a)),o.appendChild(d)}return}s?o.setAttribute("data-aia-pill-list-loading",""):o.removeAttribute("data-aia-pill-list-loading");for(let a of o.querySelectorAll("[data-aia-pill-skeleton]"))a.remove();W(o,e,{keyOf:a=>`${a.type}-${a.text}`,create:a=>{let l=document.createElement("button");return l.type="button",l.tabIndex=-1,l.setAttribute("data-aia-pill",""),l.setAttribute("contenteditable","false"),l.textContent=a.text,l.addEventListener("mousedown",d=>d.preventDefault()),l},update:(a,l,d)=>{let p=a,c=["magicx-aia-pill"];r&&c.push("magicx-aia-pill--rounded"),d===t&&!s&&c.push("magicx-aia-pill--active"),s&&c.push("magicx-aia-pill--skeleton"),p.className=c.join(" "),p.style.width="",p.style.opacity=String(Ce(d)),s?(p.setAttribute("data-aia-loading",""),p.disabled=!0,p.onclick=null):(p.removeAttribute("data-aia-loading"),p.disabled=!1,p.onclick=()=>i(d))}})}function te(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var Ve=[159,119,164];function j(n){let e=document.createElement("div");return e.id=n,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",t=>t.preventDefault()),e}function V(n,e){let{filteredOptions:t,activeIndex:i,isOpen:r,isLoading:s,pills:o,showPills:a,onSelect:l,onHighlight:d,onPillClick:p}=e,c=a&&o.length>0,m=t.length>0;r&&(m||c||s)?n.classList.add("magicx-aia-dropdown--visible"):n.classList.remove("magicx-aia-dropdown--visible"),s?n.setAttribute("data-aia-loading",""):n.removeAttribute("data-aia-loading");let g=c||s&&a,h=n.querySelector(".magicx-aia-pill-bar");g?(h||(h=document.createElement("div"),h.className="magicx-aia-pill-bar",h.setAttribute("data-aia-pillbar",""),n.insertBefore(h,n.firstChild)),G(h,o,0,p,!0,s)):h&&h.remove();let f=n.querySelector(".magicx-aia-grid");m?(f||(f=document.createElement("div"),f.className="magicx-aia-grid",n.appendChild(f)),ze(f,t,i,l,d,e.listboxId,s)):f&&f.remove();let u=n.querySelector(".magicx-aia-skeleton-bars");if(s&&!m){if(!u){u=document.createElement("div"),u.className="magicx-aia-skeleton-bars",u.setAttribute("data-aia-skeleton-bars","");for(let x of Ve){let y=document.createElement("span");y.className="magicx-aia-skeleton-bar",y.style.width=`${x}px`,u.appendChild(y)}n.appendChild(u)}}else u&&u.remove()}function ze(n,e,t,i,r,s,o){let a=o?"1":"0";W(n,e,{keyOf:l=>`${l.text}\0${a}`,create:l=>Xe(l,o),update:(l,d,p)=>{let c=p===t&&!o;l.id=`${s}-option-${p}`,l.dataset.aiaIndex=String(p),l.setAttribute("aria-selected",String(c)),l.classList.toggle("magicx-aia-option--highlighted",c),!o&&d.is_tappable?(l.onclick=()=>{l.classList.add("magicx-aia-option--pressed"),i(d),setTimeout(()=>l.classList.remove("magicx-aia-option--pressed"),500)},l.onmouseenter=()=>{let m=Number.parseInt(l.dataset.aiaIndex??"-1",10);m>=0&&r(m)}):(l.onclick=null,l.onmouseenter=null)}})}function Xe(n,e){let t=document.createElement("div");t.setAttribute("role","option"),t.setAttribute("data-aia-option",""),e&&t.setAttribute("data-aia-loading",""),t.tabIndex=e||!n.is_tappable?-1:0;let i=["magicx-aia-option"];n.is_tappable?i.push("magicx-aia-option--tappable"):i.push("magicx-aia-option--non-tappable"),t.className=i.join(" ");let r=document.createElement("div");r.className="magicx-aia-streaks",t.appendChild(r);let s=document.createElement("div");s.className="magicx-aia-streaks-vert",t.appendChild(s);let o=document.createElement("span");o.className="magicx-aia-option-content";let a=document.createElement("span");if(a.className="magicx-aia-option-text",a.textContent=n.icon?`${n.icon} ${n.text}`:n.text,o.appendChild(a),n.tag){let l=document.createElement("span");l.className="magicx-aia-option-tag",l.textContent=n.tag,o.appendChild(l)}return t.appendChild(o),t}function we(n,e){let t=j(e.listboxId);return n.appendChild(t),{dropdown:t}}function ne(n,e,t){V(n.dropdown,{suggestions:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,onSelect:t.selectOption,onHighlight:i=>t.store.set({activeDropdownIndex:i}),onPillClick:t.setActivePill})}function ie(n){let{input:e,segments:t,newParamId:i,editingParamId:r,placeholderText:s,isFocused:o}=n,a=t.length===0;e.dataset.aiaEmpty=a?"true":"false",a&&s?e.dataset.placeholder=s:delete e.dataset.placeholder;let l=t.map(f=>`${f.type}:${f.value}`).join("\0"),d=e.dataset.segKey??"",p=e.dataset.newParamId??"",c=e.dataset.editingParamId??"";if(l===d&&(i??"")===p&&(r??"")===c)return;let m=o?T(e):null;e.dataset.segKey=l,e.dataset.newParamId=i??"",e.dataset.editingParamId=r??"";let b=e.ownerDocument??document,g=b.createDocumentFragment(),h=0;for(let f of t)if(h+=f.value.length,f.type==="completed"){let u=b.createElement("strong");u.dataset.seg="completed",u.dataset.paramId=f.param.id;let x=f.param.id===i,y=f.param.id===r,S=["magicx-aia-segment","magicx-aia-segment--completed"];x&&S.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),y&&S.push("magicx-aia-segment--editing"),u.className=S.join(" "),u.textContent=f.value,g.appendChild(u)}else g.appendChild(b.createTextNode(f.value));e.replaceChildren(g),e.dataset.aiaTextLength=String(h),m!=null&&P(e,Math.max(0,Math.min(m,h)))}var Ye='<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 Je(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function Ee(n,e){let t=e.firstElementChild;if(!t){e.removeAttribute("data-aia-pill-wrapped");return}if(n.dataset.aiaEmpty==="true"){e.setAttribute("data-aia-pill-wrapped","");return}let i=t.getBoundingClientRect(),r=n.getBoundingClientRect();i.top>=r.bottom-2?e.setAttribute("data-aia-pill-wrapped",""):e.removeAttribute("data-aia-pill-wrapped")}function Ae(n,e){let{listboxId:t}=e,i=j(t);n.appendChild(i);let r=document.createElement("div");r.className="magicx-aia-input-wrapper",n.appendChild(r);let s=document.createElement("div");s.className="magicx-aia-editor",s.setAttribute("data-aia-editor",""),r.appendChild(s);let o=document.createElement("div");o.className="magicx-aia-input",o.setAttribute("data-aia-input",""),o.setAttribute("contenteditable",Je()?"plaintext-only":"true"),o.setAttribute("role","combobox"),o.setAttribute("aria-autocomplete","list"),o.setAttribute("aria-haspopup","listbox"),o.setAttribute("aria-controls",t),o.setAttribute("aria-expanded","false"),o.setAttribute("spellcheck","true"),o.setAttribute("enterkeyhint","send"),s.appendChild(o);let a=document.createElement("span");a.className="magicx-aia-pill-list-container",a.setAttribute("data-aia-pill-list-container",""),s.appendChild(a);let l=null,d=null;e.submitButton===void 0?(l=document.createElement("button"),l.type="button",l.className="magicx-aia-submit",l.setAttribute("aria-label","Submit"),l.setAttribute("data-aia-submit",""),l.innerHTML=Ye,r.appendChild(l),d=l):e.submitButton!==null&&(d=e.submitButton,d.hasAttribute("data-aia-submit")||d.setAttribute("data-aia-submit",""),r.appendChild(d));let p=new AbortController,{signal:c}=p,m=!1,b=0,g=()=>{let u=K(o),y=u.length>0&&u[0]!==u[0].toUpperCase()?u[0].toUpperCase()+u.slice(1):u;e.handleChange(y)},h=()=>{let u=(o.ownerDocument??document).getSelection();if(!u||u.rangeCount===0)return null;let x=u.anchorNode;return!x||!o.contains(x)?null:(x.nodeType===Node.ELEMENT_NODE?x:x.parentElement)?.closest('strong[data-seg="completed"][data-param-id]')?.dataset.paramId??null};r.addEventListener("click",u=>{u.target?.closest("[data-aia-pill]")||o.focus()},{signal:c}),o.addEventListener("input",()=>{m||(b=performance.now(),g(),e.handleCaretAfterInput(T(o)))},{signal:c});let f=o.ownerDocument??document;if(f.addEventListener("selectionchange",()=>{let u=f.getSelection();if(!u||u.rangeCount===0||!o.contains(u.anchorNode))return;let x=h(),y=e.store.get().editingParam?.id??null;if(x&&x!==y){e.startEditingParam(x);return}performance.now()-b<50||e.handleCaretMove(T(o))},{signal:c}),o.addEventListener("compositionstart",()=>{m=!0},{signal:c}),o.addEventListener("compositionend",()=>{m=!1,g()},{signal:c}),o.addEventListener("beforeinput",u=>{let x=u,y=x.inputType;if(y==="insertParagraph"||y==="insertLineBreak"||y==="insertFromDrop"){u.preventDefault();return}if(y.startsWith("insert")||y.startsWith("delete")){let S=y.startsWith("delete")?"":x.data??"";e.replaceEditingRange(S)&&u.preventDefault()}},{signal:c}),o.addEventListener("paste",u=>{u.preventDefault();let x=(u.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!x)return;let y=o.ownerDocument??document,S=y.getSelection();if(!S||S.rangeCount===0)return;let C=S.getRangeAt(0);if(!o.contains(C.startContainer))return;C.deleteContents();let le=y.createTextNode(x);C.insertNode(le),C.setStartAfter(le),C.collapse(!0),S.removeAllRanges(),S.addRange(C),g()},{signal:c}),o.addEventListener("keydown",u=>e.handleKeyDown(u),{signal:c}),o.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:c}),o.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:c}),d&&d.addEventListener("click",u=>{let x=e.store.get();if(!(!!x.text||x.completedParams.length>0)||!e.onSubmit)return;u.stopPropagation();let{rawQuery:S,completedParams:C}=v(x.text,x.completedParams);e.onSubmit({query:x.text.trim(),raw_query:S,completed_params:C}),e.afterSubmit?.()},{signal:c}),e.autoFocus!==!1&&o.focus(),typeof ResizeObserver<"u"){let u=new ResizeObserver(()=>Ee(o,a));u.observe(o),p.signal.addEventListener("abort",()=>u.disconnect(),{once:!0})}return{input:o,inlinePillContainer:a,dropdown:i,submitButton:l,abort:p}}function re(n,e,t){let{input:i,inlinePillContainer:r,dropdown:s,submitButton:o}=n,{pillPlacement:a,setActivePill:l,selectOption:d,store:p}=t;i.setAttribute("aria-expanded",String(e.isDropdownOpen));let c=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(c?i.setAttribute("aria-activedescendant",c):i.removeAttribute("aria-activedescendant"),o){let f=!!e.text||e.completedParams.length>0;o.disabled=!f}let m=i.dataset.newParamId??"",b=e.newParamId!==null&&e.newParamId!==m;if(ie({input:i,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused}),a==="inline"){let f=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;f||e.actionableSuggestions.length>0?G(r,e.actionableSuggestions,0,l,!1,f):te(r)}else te(r);Ee(i,r),b?(i.focus(),P(i,e.caretOffset??e.text.length)):e.isFocused&&K(i)!==e.text&&P(i,e.text.length);let g=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:null,h=g??e.actionableSuggestions[0];V(s,{suggestions:h?[{...h,options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation,listboxId:t.listboxId,pills:g?[g]:e.actionableSuggestions,showPills:a==="dropdown",onSelect:d,onHighlight:f=>p.set({activeDropdownIndex:f}),onPillClick:l})}function Ie(n,e){let t=n.actionableSuggestions[0];if(!t)return null;let i=n.filterBase,r=n.text.slice(0,i),s=r.length===0&&n.text.length===0,o=r.length===0&&n.text.length>0&&n.placeholderText.length>0&&n.placeholderText.toLowerCase().startsWith(n.text.toLowerCase());(s||o)&&n.placeholderText&&(r=`${n.placeholderText} `);let a=me(r,e.text);a>0&&(r=r.slice(0,r.length-a));let l=r.length>0&&r[r.length-1]!==" ",d=`${r}${l?" ":""}${e.text} `,p=(s||o)&&d.length>0?d[0].toUpperCase()+d.slice(1):d,c=p.toLowerCase().lastIndexOf(e.text.toLowerCase()),m=c>=0?p.slice(c,c+e.text.length):e.text,b={id:crypto.randomUUID(),placeholder:"",type:t.type,text:m,kind:e.kind,suggestionType:t.type,suggestionPlaceholder:t.text,options:t.options??[],metadata:e.metadata},g=n.actionableSuggestions.length-1;return{patch:{text:p,filterBase:p.length,completedParams:[...n.completedParams,b],newParamId:b.id,caretOffset:p.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:g>0,inSelectionAnimation:!0},telemetry:{selectedOption:e.text,otherOptions:n.filteredOptions.filter(h=>h.text!==e.text).map(h=>h.text)},consumedSuggestion:t,remainingActionable:g}}function oe(n){let e=n,t=new Set;return{get:()=>e,set:i=>{let r=typeof i=="function"?i(e):i,s={...e,...r},o=e;e=s;for(let a of t)a(s,o)},subscribe:i=>(t.add(i),()=>{t.delete(i)})}}function Oe(n,e){let t,i,r=s=>(s!==t&&(t=s,i=e(s)),i);return{get:()=>{let s=n.get();return{...s,...r(s)}},set:s=>{typeof s=="function"?n.set(o=>{let a={...o,...r(o)};return s(a)}):n.set(s)},subscribe:s=>n.subscribe((o,a)=>{let l={...a,...r(a)},d={...o,...r(o)};s(d,l)})}}var se=!1;function De(){if(se||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){se=!0;return}se=!0;let n=document.createElement("style");n.setAttribute("data-magicx-aia",""),n.textContent=Ze,document.head.appendChild(n)}var Ze=`@layer layout {
1
+ 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 Fe="https://api.ai-autocomplete.com",L=`${Fe}/api/suggest`,ce=new WeakMap;function D(n){return n?.type==="accessToken"}function Be(n){if(!(!n||D(n)))return n}function R(n){let e=ce.get(n.getAccessToken);return e||(e=new k(n),ce.set(n.getAccessToken,e)),e}function N(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function _(n){let e=Be(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}var Ke="0.3.0",pe=!1;function Qe(){return crypto.randomUUID()}function qe(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.text},kind:n.kind}}function $e(n,e,t,i){let r=e.find(o=>o.type==="contact"&&o.metadata?.contact_account_count)?.metadata?.contact_account_count,s=typeof r=="number"?r:void 0;return{data:{raw_query:n,completed_params:e.map(o=>qe(o,t)),...s!=null&&{contact_account_count:s}},meta:{request_id:Qe(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:Ke,session_id:i}}}async function ue(n,e,t,i,r){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:r})}async function me(n,e,t){let i=t.apiConfig,r=!t.maskCompletedText,s=$e(n,e,r,t.sessionId),o=N(i),a=i?.endpoint??L,d=JSON.stringify(s);if(D(i)){let c=R(i),g=await c.getToken(),b=await ue(a,o,g,d,t.signal);if(b.status===401){let u=await c.getToken(!0);b=await ue(a,o,u,d,t.signal)}if(!b.ok)throw new Error(`API error: ${b.status} ${b.statusText}`);return b.json()}let l=_(i);!l&&!pe&&(pe=!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:d,signal:t.signal});if(!p.ok)throw new Error(`API error: ${p.status} ${p.statusText}`);return p.json()}function S(n,e){let t=n,i={},r=[];for(let s of e){let o=(i[s.type]??0)+1;i[s.type]=o;let d=`{{${s.type.toUpperCase().replace(/\s+/g,"_")}_${o}}}`,l=t.indexOf(s.text);l!==-1&&(t=t.slice(0,l)+d+t.slice(l+s.text.length)),r.push({...s,placeholder:d})}return{rawQuery:t,completedParams:r}}function A(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function E(n,e,t){let i=n.slice(e);if(t||e===0||n[e-1]===" ")return i;let r=i.indexOf(" ");return r===-1?"":i.slice(r+1)}function ge(n,e){let t=n.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let i=t.split(" "),r=e.toLowerCase();for(let s=0;s<i.length;s++){let o=i.slice(s).join(" ");if(r.startsWith(o.toLowerCase())){let a=t.length-o.length;return n.length-a}}return 0}function w(n,e){if(!n)return[];let t=e.trimStart();if(!t)return n;let i=t.toLowerCase();return n.filter(r=>!r.is_tappable||r.text.toLowerCase().includes(i))}function I(n,e){if(!n)return null;let t=e.trim();if(!t)return null;let i=t.toLowerCase();return n.find(r=>r.is_tappable&&r.text.toLowerCase()===i)??null}function fe(n,e){return e?n.map(t=>{let i=e[t.type];if(!i)return t;let r=i("");if(r.length===0)return t;let s=new Set(r.map(a=>a.text)),o=(t.options??[]).filter(a=>!s.has(a.text));return{...t,options:[...r,...o]}}):n}var Ue=100,Ge=300,We=2,H=class{constructor(e,t,i,r,s,o,a={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=r;this.getOnError=s;this.getSessionId=o;this.callbacks=a;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null}start(){this.doFetch("",[]);let e=this.store.get().text,t=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(i=>{(i.text!==e||i.completedParams!==t)&&(e=i.text,t=i.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let i=new AbortController;this.abortController=i;let r=++this.fetchVersion,s=this.store.get().text.length;this.store.set({isLoading:!0,error:null});try{let o=await me(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig()});if(r!==this.fetchVersion)return;let a=fe(o.data.suggestions??[],this.getOptionOverrides()),d=o.data.input??[],l=d[d.length-1],p=this.store.get().text,c,g;if(l?.state==="in_progress"){g=!0;let f=p.toLowerCase().lastIndexOf(l.text.toLowerCase());c=f!==-1?f:s}else g=!1,c=s;let u=a.filter(f=>f.type!=="placeholder")[0],x=null;if(u){let f=E(p,c,g),m=I(u.options,f);m&&(x={id:crypto.randomUUID(),placeholder:"",type:u.type,text:m.text,kind:m.kind,suggestionType:u.type,suggestionPlaceholder:u.text,options:u.options??[],metadata:m.metadata},a=a.filter(h=>h!==u),this.callbacks.onAutoMatch?.({active:u,matched:m,rawQuery:e}))}this.store.set(f=>({suggestions:a,isLoading:!1,isReady:o.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:c,filterInProgress:g,...x?{completedParams:[...f.completedParams,x]}:{}}))}catch(o){if(r===this.fetchVersion){let a=o instanceof Error?o:new Error(String(o));this.store.set({error:a,isLoading:!1}),this.getOnError()?.(a)}}}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}let t=i=>{let r=this.store.get();if(!r.text&&r.completedParams.length===0)return this.doFetch("",[]),!0;let s=r.suggestions.filter(h=>h.type==="placeholder").map(h=>h.text).join(" "),o=A(r.text,r.filterBase,s),a=E(r.text,o,r.filterInProgress),l=r.suggestions.filter(h=>h.type!=="placeholder")[0],c=(l?w(l.options,a):[]).filter(h=>h.is_tappable),g=l?I(l.options,a)!==null:!1,b=a.trim().length>0;if(c.length>0&&!g&&b||r.completedParams.length===0&&r.text.length>0&&s.length>0&&s.toLowerCase().startsWith(r.text.toLowerCase()))return!1;let{rawQuery:u,completedParams:x}=S(r.text,r.completedParams),f=u.length<r.lastRawQuery.length,m=Math.abs(u.length-r.lastRawQuery.length);return f||m>=i?(this.doFetch(u,x),!0):!1};this.debounceTimer=setTimeout(()=>{t(We)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},Ue),this.slowDebounceTimer=setTimeout(()=>t(1),Ge)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var be='[contenteditable="false"]',O;function je(){if(O!==void 0)return O;let n=globalThis.Intl.Segmenter;if(!n)return O=null,null;try{O=new n(void 0,{granularity:"grapheme"})}catch{O=null}return O??null}function F(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(be))return!0;t=t.parentNode}return!1}function B(n){return(n.ownerDocument??document).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return F(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function K(n){let e=B(n),t="",i=e.nextNode();for(;i;)t+=i.data,i=e.nextNode();return t}function Y(n){let e=B(n),t=0,i=e.nextNode();for(;i;)t+=i.data.length,i=e.nextNode();return t}function C(n){let e=(n.ownerDocument??document).getSelection();if(!e||e.rangeCount===0)return null;let t=e.anchorNode,i=e.anchorOffset;if(!t||!n.contains(t))return null;if(t.nodeType===Node.ELEMENT_NODE){let r=t;if(F(r,n)&&r!==n)return null;let s=0;for(let o=0;o<i&&o<r.childNodes.length;o++)s+=xe(r.childNodes[o],n);return s+he(r,n)}return t.nodeType!==Node.TEXT_NODE||F(t,n)?null:he(t,n)+i}function xe(n,e){if(n.nodeType===Node.TEXT_NODE)return F(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(be))return 0;let i=0;for(let r of Array.from(t.childNodes))i+=xe(r,e);return i}function he(n,e){let t=B(e),i=0,r=t.nextNode();for(;r;){if(r===n||n.nodeType===Node.ELEMENT_NODE&&n.contains(r))return i;i+=r.data.length,r=t.nextNode()}return i}function T(n,e){let t=n.ownerDocument??document,i=t.getSelection();if(!i)return;let r=Math.max(0,Math.min(e,Y(n))),s=B(n),o=0,a=null,d=0,l=s.nextNode(),p=null;for(;l;){let g=l.data.length;if(r<o+g){a=l,d=r-o;break}if(r===o+g){let b=s.nextNode();b?(a=b,d=0):(a=l,d=g);break}o+=g,p=l,l=s.nextNode()}let c=t.createRange();if(a){let g=a.parentElement?.closest('strong[data-seg="completed"]');g&&g!==n&&n.contains(g)?d===0?c.setStartBefore(g):d===a.data.length?c.setStartAfter(g):c.setStart(a,d):c.setStart(a,d)}else p?c.setStart(p,p.data.length):c.setStart(n,0);c.collapse(!0),i.removeAllRanges(),i.addRange(c)}function J(n){let e=C(n);return e==null?!1:e>=Y(n)}function Z(n,e){if(e<=0)return 0;let t=je();if(!t)return e-1;let i=n.slice(0,e),r=0;for(let{index:s}of t.segment(i))s<e&&(r=s);return r}function ee(n){return n instanceof HTMLTextAreaElement||n instanceof HTMLInputElement?n.selectionStart!=null&&n.selectionStart===n.value.length:n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?J(n):!1}function Ve(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?C(n):null}var Q=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:r}=this.ctx,s=this.getEffectiveColumns(),o=r(),a=this.getTappableIndices(s);if((e.shiftKey||e.metaKey||e.ctrlKey||e.altKey)&&(e.key==="ArrowDown"||e.key==="ArrowUp"||e.key==="ArrowLeft"||e.key==="ArrowRight"))return;let d=this.ctx.getOptionsPosition()==="above";switch(e.key){case"ArrowDown":{let l=ee(e.target),p=!!t.editingParam;if(!l&&!p&&t.activeDropdownIndex<0)break;if(t.activeDropdownIndex<0){if(d)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;this.store.set({activeDropdownIndex:a[0]});break}if(e.preventDefault(),a.length===0)return;if(t.filteredOptions.length>0){let b=Math.floor((t.filteredOptions.length-1)/s);if(Math.floor(t.activeDropdownIndex/s)===b){this.store.set({activeDropdownIndex:-1});break}}let c=a.indexOf(t.activeDropdownIndex),g=c<a.length-1?c+1:0;this.store.set({activeDropdownIndex:a[g]});break}case"ArrowUp":{if(t.activeDropdownIndex<0){if(!d)break;let c=ee(e.target),g=!!t.editingParam;if(!c&&!g)break;e.preventDefault();let b=this.firstTappableInBottomRow(s)??a[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:b});break}if(a.length===0)return;this.store.set({activeDropdownIndex:b});break}if(a.length===0)break;if(e.preventDefault(),t.activeDropdownIndex<s){this.store.set({activeDropdownIndex:-1});break}let l=a.indexOf(t.activeDropdownIndex),p=l>0?l-1:a.length-1;this.store.set({activeDropdownIndex:a[p]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%s<s-1){let c=t.activeDropdownIndex+1;c<t.filteredOptions.length&&t.filteredOptions[c]?.is_tappable&&this.store.set({activeDropdownIndex:c})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let p=e.target.closest("[data-aia-input]")??e.target,c=t.editingTail;this.ctx.exitEditMode?.(),T(p,c);break}ee(e.target)&&t.actionableSuggestions.length>=1&&(e.preventDefault(),this.removeActivePill());break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%s>0){let l=t.activeDropdownIndex-1;l>=0&&t.filteredOptions[l]?.is_tappable&&this.store.set({activeDropdownIndex:l})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let l=e.target.closest("[data-aia-input]")??e.target,p=t.editingAnchor;this.ctx.exitEditMode?.(),T(l,p);break}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let l=Ve(e.target);if(l==null)break;this.ctx.removeParamAtCaret(l)&&e.preventDefault();break}case"Enter":{if(e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable)this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i);else if(o){let{rawQuery:l,completedParams:p}=S(t.text,t.completedParams);o({query:t.text.trim(),raw_query:l,completed_params:p}),this.ctx.afterSubmit?.()}break}case"Tab":{let l=t.filteredOptions.map((g,b)=>g.is_tappable?b:-1).filter(g=>g!==-1);if(l.length===0)break;if(!t.isDropdownOpen){if(t.actionableSuggestions.length===0)break;e.preventDefault();let g=e.shiftKey?l[l.length-1]:l[0];this.store.set({pillTapped:!0,activeDropdownIndex:g,hasTabbedToHighlight:!0});break}e.preventDefault();let p=l.indexOf(t.activeDropdownIndex),c;if(p<0)c=e.shiftKey?l.length-1:0;else{let g=e.shiftKey?-1:1;c=(p+g+l.length)%l.length}this.store.set({activeDropdownIndex:l[c],hasTabbedToHighlight:!0});break}case"Escape":{if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){let l=e.target.closest("[data-aia-input]")??e.target,p=t.editingTail;this.ctx.exitEditMode?.(),T(l,p)}this.store.set({activeDropdownIndex:-1});break}}}firstTappableInBottomRow(e){let t=this.store.get();if(t.filteredOptions.length===0)return null;let r=Math.floor((t.filteredOptions.length-1)/e)*e;for(let s=r;s<t.filteredOptions.length;s++)if(t.filteredOptions[s]?.is_tappable)return s;return null}getTappableIndices(e){let i=this.store.get().filteredOptions.map((s,o)=>s.is_tappable?o:-1).filter(s=>s!==-1),r=Array.from({length:e},()=>[]);for(let s of i)r[s%e].push(s);return r.flat()}getEffectiveColumns(){let e=document.getElementById(this.ctx.listboxId);if(!e)return this.ctx.columns;let i=document.getElementById(`${this.ctx.listboxId}-option-0`)?.parentElement??null;for(;i;){let r=getComputedStyle(i).gridTemplateColumns;if(r&&r!=="none"){let s=r.split(" ").filter(Boolean).length;if(s>0)return s}if(i===e)break;i=i.parentElement}return this.ctx.columns}clickOrSelect(e,t,i){let r=document.getElementById(`${i}-option-${e}`);r?r.click():this.ctx.selectOption(t[e])}removeActivePill(){let e=this.store.get(),t=e.suggestions.filter(s=>s.type==="placeholder"),i=e.suggestions.filter(s=>s.type!=="placeholder");if(i.length===0)return;let r=i.slice(1);this.store.set({suggestions:[...t,...r],pillTapped:r.length>0,activeDropdownIndex:-1})}};var q=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),i=t.suggestions.filter(a=>a.type!=="placeholder");if(e<0||e>=i.length)return;let r=i[e],s=i.filter((a,d)=>d!==e),o=t.suggestions.filter(a=>a.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:a}=S(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:a,selectedPill:r.text,otherPills:s.map(d=>d.text)})}this.store.set({suggestions:[...o,r,...s],pillTapped:!0,activeDropdownIndex:-1})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};function ye(n,e){let t=[],i=0;for(let s of e){let o=n.indexOf(s.text,i);o!==-1&&(o>i&&t.push({type:"text",value:n.slice(i,o)}),t.push({type:"completed",value:s.text,param:s}),i=o+s.text.length)}let r=n.slice(i);return r&&t.push({type:"text",value:r}),t}function ve(n,e){let t=[],i=[],r=0;for(let s of e){let o=n.indexOf(s.text,r);o===-1?i.push(s):(t.push(s),r=o+s.text.length)}return{valid:t,invalid:i}}function Se(n,e){let t=e.dropdownTrigger??"auto",i=e.closeDropdownOnBlur??!0,r=n.filteredOptionsLength>0;if(n.inEditMode){let s=i?n.isFocused:!0;return r&&s}if(t==="auto"){let s=i?n.isFocused:!0,o=n.text.replace(/\s+$/,"").length,a=n.caretOffset==null||n.caretOffset>=o;return(r||n.isLoading)&&s&&a}return t==="manual"?(r||n.isLoading)&&n.pillTapped:!1}function Pe(n,e){let t=ye(n.text,n.completedParams),i=n.suggestions.filter(u=>u.type!=="placeholder"),r=i[0],s=r?e.optionOverrides?.[r.type]:void 0,o=n.suggestions.filter(u=>u.type==="placeholder").map(u=>u.text).join(" "),a=A(n.text,Math.min(n.filterBase,n.text.length),o),l=n.lastRawQuery!==""||a>0?E(n.text,a,n.filterInProgress):"",p=r?s?s(l.trim()):r.options??[]:[],c=n.editingParam!=null&&n.editingAnchor!=null,g;if(c&&n.editingParam&&n.editingAnchor!=null){let u=n.editingParam.id,x=n.completedParams.some(h=>h.id===u),f=n.caretOffset??n.editingAnchor,m=x?"":n.text.slice(n.editingAnchor,f);g=w(n.editingParam.options,m)}else g=w(p,l);e.showNonTappableOptions===!1&&(g=g.filter(u=>u.is_tappable));let b=Se({inEditMode:c,filteredOptionsLength:g.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading,pillTapped:n.pillTapped},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur});return{segments:t,actionableSuggestions:i,filteredOptions:g,placeholderText:o,isDropdownOpen:b}}function $(n){return n.mode==="fresh"?ze(n):Xe(n)}function ze(n){let{text:e,completedParams:t,suggestions:i,filterBase:r,filterInProgress:s}=n,a=i.filter(v=>v.type!=="placeholder")[0];if(!a?.options)return null;let d=i.filter(v=>v.type==="placeholder").map(v=>v.text).join(" "),l=A(e,r,d),p=E(e,l,s),c=I(a.options,p);if(!c)return null;let g=c.text.toLowerCase(),b=e.toLowerCase().lastIndexOf(g),u=b>=0?b:Math.max(0,e.length-c.text.length),x=u+c.text.length,f=e.slice(u,x),h=x<e.length&&e[x]===" "?x+1:x,y={id:crypto.randomUUID(),placeholder:"",type:a.type,text:f,kind:c.kind,suggestionType:a.type,suggestionPlaceholder:a.text,options:a.options??[],metadata:c.metadata};return{patch:{text:e,completedParams:[...t,y],suggestions:i.filter(v=>v!==a),filterBase:h,newParamId:y.id,caretOffset:h,activeDropdownIndex:-1},caretPos:h}}function Xe(n){let{text:e,completedParams:t,editingParam:i,editingAnchor:r,editingTail:s}=n;if(t.some(y=>y.id===i.id))return null;let o=e.slice(r,s),a=I(i.options,o);if(!a)return null;let d=a.text.toLowerCase(),l=o.toLowerCase().lastIndexOf(d),p=r+Math.max(0,l),c=p+a.text.length,g=e.slice(p,c),u=c<e.length&&e[c]===" "?c+1:c,x={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:g,kind:a.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:a.metadata},f=t.length,m=0;for(let y=0;y<t.length;y++){let v=e.indexOf(t[y].text,m);if(v!==-1){if(v>=u){f=y;break}m=v+t[y].text.length}}let h=[...t];return h.splice(f,0,x),{patch:{text:e,completedParams:h,newParamId:x.id,filterBase:u,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:u,activeDropdownIndex:-1},caretPos:u}}var U=class{constructor(e){this.deps=e}start(e){let t=this.deps.store.get();if(t.editingParam?.id===e)return;let i=t.completedParams.find(o=>o.id===e);if(!i)return;let r=0,s=-1;for(let o of t.completedParams){let a=t.text.indexOf(o.text,r);if(a!==-1){if(o.id===e){s=a;break}r=a+o.text.length}}s<0||this.deps.store.set({editingParam:i,editingAnchor:s,editingTail:s+i.text.length,caretOffset:s+i.text.length,activeDropdownIndex:-1})}exit(){this.deps.store.get().editingParam&&this.deps.store.set({editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1})}replaceRange(e){let t=this.deps.store.get(),i=t.editingParam,r=t.editingAnchor,s=t.editingTail;if(!i||r==null||s==null||!t.completedParams.some(d=>d.id===i.id))return!1;let o=t.text.slice(0,r)+e+t.text.slice(s),a=r+e.length;return this.deps.store.set(d=>({text:o,completedParams:d.completedParams.filter(l=>l.id!==i.id),editingTail:a,caretOffset:a,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(a),this.tryPromote(),!0}caretAfterInput(e){let t=this.deps.store.get(),i={caretOffset:e};t.editingParam&&t.editingAnchor!=null&&e!=null&&(e<t.editingAnchor?(i.editingParam=null,i.editingAnchor=null,i.editingTail=null,i.activeDropdownIndex=-1):t.editingTail!=null&&(i.editingTail=Math.max(t.editingTail,e))),this.deps.store.set(i),this.tryPromote()}caretMove(e){let t=this.deps.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null&&e!=null&&(e<t.editingAnchor||e>t.editingTail)){this.deps.store.set({caretOffset:e,editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1});return}this.deps.store.set({caretOffset:e})}selectOption(e){let t=this.deps.store.get(),i=t.editingParam,r=t.editingAnchor,s=t.editingTail;if(!i||r==null||s==null)return;this.deps.fireTelemetry("option",{raw_query:S(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:i.options.filter(m=>m.text!==e.text).map(m=>m.text)});let o=t.text.slice(0,r),a=t.text.slice(s),d=r===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,l=a.length===0||a[0]!==" ",p=l?`${d} `:d,c=o+p+a,g=r+p.length+(l?0:1),b={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:d,kind:e.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:e.metadata},u=t.completedParams.findIndex(m=>m.id===i.id),x=t.completedParams.filter(m=>m.id!==i.id),f=u>=0?Math.min(u,x.length):x.length;x.splice(f,0,b),this.deps.store.set({text:c,completedParams:x,newParamId:b.id,filterBase:g,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:g,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.deps.startSelectionAnimationTimer(),this.deps.scheduleSetCursor(g)}tryPromote(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let t=$({mode:"edit",text:e.text,completedParams:e.completedParams,editingParam:e.editingParam,editingAnchor:e.editingAnchor,editingTail:e.editingTail});t&&(this.deps.store.set(t.patch),this.deps.scheduleSetCursor(t.caretPos))}};function te(n,e){return e?{key:"enter",hint:"to proceed"}:n?{key:"\u2192",hint:"to skip"}:{key:"tab",hint:"to select"}}var Te="data-aia-key";function G(n,e,t){let i=new Map;for(let o of Array.from(n.children)){let a=o.getAttribute(Te);a!=null&&i.set(a,o)}let r=new Set,s=[];for(let o=0;o<e.length;o++){let a=e[o],d=t.keyOf(a,o);r.add(d);let l=i.get(d);l||(l=t.create(a,o),l.setAttribute(Te,d)),t.update?.(l,a,o),n.children[o]!==l&&n.insertBefore(l,n.children[o]??null),s.push(l)}for(let[o,a]of i)r.has(o)||a.remove();return s}var Ce=[125,69];function Ee(n){return n===0?1:n===1?.4:.2}function W(n,e,t,i,r=!1,s=!1){let o=n.querySelector(".magicx-aia-pill-list");if(o||(o=document.createElement("span"),o.className="magicx-aia-pill-list",n.appendChild(o)),s&&e.length===0){o.setAttribute("data-aia-pill-list-loading",""),o.innerHTML="";for(let a=0;a<Ce.length;a++){let d=Ce[a],l=document.createElement("span");l.setAttribute("data-aia-pill-skeleton",""),l.className=`magicx-aia-pill magicx-aia-pill--skeleton${r?" magicx-aia-pill--rounded":""}`,l.style.width=`${d}px`,l.style.opacity=String(Ee(a)),o.appendChild(l)}return}s?o.setAttribute("data-aia-pill-list-loading",""):o.removeAttribute("data-aia-pill-list-loading");for(let a of o.querySelectorAll("[data-aia-pill-skeleton]"))a.remove();G(o,e,{keyOf:a=>`${a.type}-${a.text}`,create:a=>{let d=document.createElement("button");return d.type="button",d.tabIndex=-1,d.setAttribute("data-aia-pill",""),d.setAttribute("contenteditable","false"),d.textContent=a.text,d.addEventListener("mousedown",l=>l.preventDefault()),d},update:(a,d,l)=>{let p=a,c=["magicx-aia-pill"];r&&c.push("magicx-aia-pill--rounded"),l===t&&!s&&c.push("magicx-aia-pill--active"),s&&c.push("magicx-aia-pill--skeleton"),p.className=c.join(" "),p.style.width="",p.style.opacity=String(Ee(l)),s?(p.setAttribute("data-aia-loading",""),p.disabled=!0,p.onclick=null):(p.removeAttribute("data-aia-loading"),p.disabled=!1,p.onclick=()=>i(l))}})}function ne(n){n.querySelector(".magicx-aia-pill-list")?.remove()}function we(n,e,t,i,r,s,o){let a=n.querySelector(".aia-grid");if(e.length===0){a?.remove();return}a||(a=document.createElement("div"),a.className="aia-grid magicx-aia-grid",a.setAttribute("data-scroll",""),a.style.setProperty("--aia-grid-min","250px"),a.style.setProperty("--aia-grid-max","250px"),a.style.setProperty("--aia-grid-gap","0"),n.appendChild(a)),Ye(a,e,t,i,r,s,o)}function Ye(n,e,t,i,r,s,o){let a=o?"1":"0";G(n,e,{keyOf:d=>`${d.text}\0${a}`,create:d=>Je(d,o),update:(d,l,p)=>{let c=p===t&&!o;d.id=`${s}-option-${p}`,d.dataset.aiaIndex=String(p),d.setAttribute("aria-selected",String(c)),d.classList.toggle("magicx-aia-option--highlighted",c),!o&&l.is_tappable?(d.onclick=()=>{d.classList.add("magicx-aia-option--pressed"),i(l),setTimeout(()=>d.classList.remove("magicx-aia-option--pressed"),500)},d.onmouseenter=()=>{let g=Number.parseInt(d.dataset.aiaIndex??"-1",10);g>=0&&r(g)}):(d.onclick=null,d.onmouseenter=null)}})}function Je(n,e){let t=document.createElement("div");t.setAttribute("role","option"),t.setAttribute("data-aia-option",""),e&&t.setAttribute("data-aia-loading",""),t.tabIndex=e||!n.is_tappable?-1:0;let i=["magicx-aia-option"];n.is_tappable?i.push("magicx-aia-option--tappable"):i.push("magicx-aia-option--non-tappable"),t.className=i.join(" ");let r=document.createElement("div");r.className="magicx-aia-streaks",t.appendChild(r);let s=document.createElement("div");s.className="magicx-aia-streaks-vert",t.appendChild(s);let o=document.createElement("span");o.className="magicx-aia-option-content";let a=document.createElement("span");if(a.className="magicx-aia-option-text",a.textContent=n.icon?`${n.icon} ${n.text}`:n.text,o.appendChild(a),n.tag){let d=document.createElement("span");d.className="magicx-aia-option-tag",d.textContent=n.tag,o.appendChild(d)}return t.appendChild(o),t}var Ze=[159,119,164];function j(n){let e=document.createElement("div");return e.id=n,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",t=>t.preventDefault()),e}function V(n,e){let{filteredOptions:t,activeIndex:i,isOpen:r,isLoading:s,pills:o,showPills:a,onSelect:d,onHighlight:l,onPillClick:p}=e,c=a&&o.length>0,g=t.length>0;r&&(g||c||s)?n.classList.add("magicx-aia-dropdown--visible"):n.classList.remove("magicx-aia-dropdown--visible"),s?n.setAttribute("data-aia-loading",""):n.removeAttribute("data-aia-loading");let u=n.querySelector(".aia-stack");u||(u=document.createElement("div"),u.className="aia-stack",u.style.setProperty("--aia-stack-space","14px"),n.appendChild(u));let x=c||s&&a,f=u.querySelector(".magicx-aia-pill-bar");x?(f||(f=document.createElement("div"),f.className="magicx-aia-pill-bar aia-cluster",f.setAttribute("data-nowrap",""),f.setAttribute("data-aia-pillbar",""),u.insertBefore(f,u.firstChild)),W(f,o,0,p,!0,s)):f&&f.remove(),we(u,t,i,d,l,e.listboxId,s);let m=u.querySelector(".magicx-aia-skeleton-bars");if(s&&!g){if(!m){m=document.createElement("div"),m.className="magicx-aia-skeleton-bars",m.setAttribute("data-aia-skeleton-bars","");for(let v of Ze){let P=document.createElement("span");P.className="magicx-aia-skeleton-bar",P.style.width=`${v}px`,m.appendChild(P)}u.appendChild(m)}}else m&&m.remove();let h=u.querySelector(".magicx-aia-footer")??tt(),y=i>=0&&!!t[i]?.is_tappable;et(h,te(e.hasTabbedToHighlight,y)),u.lastElementChild!==h&&u.appendChild(h)}function et(n,{key:e,hint:t}){let i=n.querySelector(".magicx-aia-footer-key"),r=n.querySelector(".magicx-aia-footer-hint");!i||!r||(i.textContent!==e&&(i.textContent=e),r.textContent!==t&&(r.textContent=t))}function tt(){let n=document.createElement("footer");n.className="magicx-aia-footer",n.setAttribute("data-aia-footer","");let e=document.createElement("div");e.className="magicx-aia-footer-divider";let t=document.createElement("div");t.className="aia-cluster",t.setAttribute("data-align","center"),t.setAttribute("data-justify","between"),t.setAttribute("data-nowrap","");let i=document.createElement("div");i.className="aia-cluster",i.setAttribute("data-align","center"),i.style.setProperty("--aia-cluster-gap","5px");let r=document.createElement("kbd");r.className="magicx-aia-footer-key",r.textContent="tab";let s=document.createElement("span");s.className="magicx-aia-footer-hint",s.textContent="to select",i.append(r,s);let o=document.createElement("a");o.className="aia-cluster magicx-aia-footer-brand-link",o.setAttribute("data-align","center"),o.href="https://ai-autocomplete.com",o.target="_blank",o.rel="noopener noreferrer",o.style.setProperty("--aia-cluster-gap","2px");let a=document.createElement("span");a.className="magicx-aia-footer-brand",a.textContent="AI";let d=document.createElement("span");return d.className="magicx-aia-footer-badge",d.textContent="Autocomplete",o.append(a,d),t.append(i,o),n.append(e,t),n}function Ae(n,e){let t=j(e.listboxId);return n.appendChild(t),{dropdown:t}}function ie(n,e,t){V(n.dropdown,{suggestions:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,hasTabbedToHighlight:e.hasTabbedToHighlight,onSelect:t.selectOption,onHighlight:i=>t.store.set({activeDropdownIndex:i}),onPillClick:t.setActivePill})}function re(n){let{input:e,segments:t,newParamId:i,editingParamId:r,placeholderText:s,isFocused:o}=n,a=t.length===0;e.dataset.aiaEmpty=a?"true":"false",a&&s?e.dataset.placeholder=s:delete e.dataset.placeholder;let d=t.map(f=>`${f.type}:${f.value}`).join("\0"),l=e.dataset.segKey??"",p=e.dataset.newParamId??"",c=e.dataset.editingParamId??"";if(d===l&&(i??"")===p&&(r??"")===c)return;let g=o?C(e):null;e.dataset.segKey=d,e.dataset.newParamId=i??"",e.dataset.editingParamId=r??"";let b=e.ownerDocument??document,u=b.createDocumentFragment(),x=0;for(let f of t)if(x+=f.value.length,f.type==="completed"){let m=b.createElement("strong");m.dataset.seg="completed",m.dataset.paramId=f.param.id;let h=f.param.id===i,y=f.param.id===r,v=["magicx-aia-segment","magicx-aia-segment--completed"];h&&v.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),y&&v.push("magicx-aia-segment--editing"),m.className=v.join(" "),m.textContent=f.value,u.appendChild(m)}else u.appendChild(b.createTextNode(f.value));e.replaceChildren(u),e.dataset.aiaTextLength=String(x),g!=null&&T(e,Math.max(0,Math.min(g,x)))}var nt='<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 Ie(){let n=document.createElement("button");return n.type="button",n.className="magicx-aia-submit",n.setAttribute("aria-label","Submit"),n.setAttribute("data-aia-submit",""),n.innerHTML=nt,n}function it(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function Oe(n,e){let t=e.firstElementChild;if(!t){e.removeAttribute("data-aia-pill-wrapped");return}let i=t.getBoundingClientRect(),r=n.getBoundingClientRect();i.top>=r.bottom-2?e.setAttribute("data-aia-pill-wrapped",""):e.removeAttribute("data-aia-pill-wrapped")}function De(n,e){let{listboxId:t}=e,i=j(t);n.appendChild(i);let r=document.createElement("div");r.className="magicx-aia-input-wrapper",n.appendChild(r);let s=document.createElement("div");s.className="magicx-aia-editor",s.setAttribute("data-aia-editor",""),r.appendChild(s);let o=document.createElement("div");o.className="magicx-aia-input",o.setAttribute("data-aia-input",""),o.setAttribute("contenteditable",it()?"plaintext-only":"true"),o.setAttribute("role","combobox"),o.setAttribute("aria-autocomplete","list"),o.setAttribute("aria-haspopup","listbox"),o.setAttribute("aria-controls",t),o.setAttribute("aria-expanded","false"),o.setAttribute("spellcheck","true"),o.setAttribute("enterkeyhint","send"),s.appendChild(o);let a=document.createElement("span");a.className="magicx-aia-pill-list-container",a.setAttribute("data-aia-pill-list-container",""),s.appendChild(a);let d=null,l=null;e.submitButton===void 0?(d=Ie(),r.appendChild(d),l=d):e.submitButton!==null&&(l=e.submitButton,l.hasAttribute("data-aia-submit")||l.setAttribute("data-aia-submit",""),r.appendChild(l));let p=new AbortController,{signal:c}=p,g=!1,b=0,u=()=>{let m=K(o),y=m.length>0&&m[0]!==m[0].toUpperCase()?m[0].toUpperCase()+m.slice(1):m;e.handleChange(y)},x=()=>{let m=(o.ownerDocument??document).getSelection();if(!m||m.rangeCount===0)return null;let h=m.anchorNode;return!h||!o.contains(h)?null:(h.nodeType===Node.ELEMENT_NODE?h:h.parentElement)?.closest('strong[data-seg="completed"][data-param-id]')?.dataset.paramId??null};r.addEventListener("click",m=>{m.target?.closest("[data-aia-pill]")||o.focus()},{signal:c}),o.addEventListener("input",()=>{g||(b=performance.now(),u(),e.handleCaretAfterInput(C(o)))},{signal:c});let f=o.ownerDocument??document;if(f.addEventListener("selectionchange",()=>{let m=f.getSelection();if(!m||m.rangeCount===0||!o.contains(m.anchorNode))return;let h=x(),y=e.store.get().editingParam?.id??null;if(h&&h!==y){e.startEditingParam(h);return}performance.now()-b<50||e.handleCaretMove(C(o))},{signal:c}),o.addEventListener("compositionstart",()=>{g=!0},{signal:c}),o.addEventListener("compositionend",()=>{g=!1,u()},{signal:c}),o.addEventListener("beforeinput",m=>{let h=m,y=h.inputType;if(y==="insertParagraph"||y==="insertLineBreak"||y==="insertFromDrop"){m.preventDefault();return}if(y.startsWith("insert")||y.startsWith("delete")){let v=y.startsWith("delete")?"":h.data??"";e.replaceEditingRange(v)&&m.preventDefault()}},{signal:c}),o.addEventListener("paste",m=>{m.preventDefault();let h=(m.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!h)return;let y=o.ownerDocument??document,v=y.getSelection();if(!v||v.rangeCount===0)return;let P=v.getRangeAt(0);if(!o.contains(P.startContainer))return;P.deleteContents();let de=y.createTextNode(h);P.insertNode(de),P.setStartAfter(de),P.collapse(!0),v.removeAllRanges(),v.addRange(P),u()},{signal:c}),o.addEventListener("keydown",m=>e.handleKeyDown(m),{signal:c}),o.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:c}),o.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:c}),l&&l.addEventListener("click",m=>{let h=e.store.get();if(!(!!h.text||h.completedParams.length>0)||!e.onSubmit)return;m.stopPropagation();let{rawQuery:v,completedParams:P}=S(h.text,h.completedParams);e.onSubmit({query:h.text.trim(),raw_query:v,completed_params:P}),e.afterSubmit?.()},{signal:c}),e.autoFocus!==!1&&o.focus(),typeof ResizeObserver<"u"){let m=new ResizeObserver(()=>Oe(o,a));m.observe(o),p.signal.addEventListener("abort",()=>m.disconnect(),{once:!0})}return{input:o,inlinePillContainer:a,dropdown:i,submitButton:d,abort:p}}function oe(n,e,t){let{input:i,inlinePillContainer:r,dropdown:s,submitButton:o}=n,{pillPlacement:a,setActivePill:d,selectOption:l,store:p}=t;i.setAttribute("aria-expanded",String(e.isDropdownOpen));let c=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(c?i.setAttribute("aria-activedescendant",c):i.removeAttribute("aria-activedescendant"),o){let f=!!e.text||e.completedParams.length>0;o.disabled=!f}let g=i.dataset.newParamId??"",b=e.newParamId!==null&&e.newParamId!==g;if(re({input:i,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused}),a==="inline"){let f=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;f||e.actionableSuggestions.length>0?W(r,e.actionableSuggestions,0,d,!1,f):ne(r)}else ne(r);Oe(i,r),b?(i.focus(),T(i,e.caretOffset??e.text.length)):e.isFocused&&K(i)!==e.text&&T(i,e.text.length);let u=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:null,x=u??e.actionableSuggestions[0];V(s,{suggestions:x?[{...x,options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation,listboxId:t.listboxId,pills:u?[u]:e.actionableSuggestions,showPills:a==="dropdown",hasTabbedToHighlight:e.hasTabbedToHighlight,onSelect:l,onHighlight:f=>p.set({activeDropdownIndex:f}),onPillClick:d})}function Me(n,e){let t=n.actionableSuggestions[0];if(!t)return null;let i=n.filterBase,r=n.text.slice(0,i),s=r.length===0&&n.text.length===0,o=r.length===0&&n.text.length>0&&n.placeholderText.length>0&&n.placeholderText.toLowerCase().startsWith(n.text.toLowerCase());(s||o)&&n.placeholderText&&(r=`${n.placeholderText} `);let a=ge(r,e.text);a>0&&(r=r.slice(0,r.length-a));let d=r.length>0&&r[r.length-1]!==" ",l=`${r}${d?" ":""}${e.text} `,p=(s||o)&&l.length>0?l[0].toUpperCase()+l.slice(1):l,c=p.toLowerCase().lastIndexOf(e.text.toLowerCase()),g=c>=0?p.slice(c,c+e.text.length):e.text,b={id:crypto.randomUUID(),placeholder:"",type:t.type,text:g,kind:e.kind,suggestionType:t.type,suggestionPlaceholder:t.text,options:t.options??[],metadata:e.metadata},u=n.actionableSuggestions.length-1;return{patch:{text:p,filterBase:p.length,completedParams:[...n.completedParams,b],newParamId:b.id,caretOffset:p.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:u>0,inSelectionAnimation:!0},telemetry:{selectedOption:e.text,otherOptions:n.filteredOptions.filter(x=>x.text!==e.text).map(x=>x.text)},consumedSuggestion:t,remainingActionable:u}}function se(n){let e=n,t=new Set;return{get:()=>e,set:i=>{let r=typeof i=="function"?i(e):i,s={...e,...r},o=e;e=s;for(let a of t)a(s,o)},subscribe:i=>(t.add(i),()=>{t.delete(i)})}}function ke(n,e){let t,i,r=s=>(s!==t&&(t=s,i=e(s)),i);return{get:()=>{let s=n.get();return{...s,...r(s)}},set:s=>{typeof s=="function"?n.set(o=>{let a={...o,...r(o)};return s(a)}):n.set(s)},subscribe:s=>n.subscribe((o,a)=>{let d={...a,...r(a)},l={...o,...r(o)};s(l,d)})}}var ae=!1;function Le(){if(ae||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){ae=!0;return}ae=!0;let n=document.createElement("style");n.setAttribute("data-magicx-aia",""),n.textContent=rt,document.head.appendChild(n)}var rt=`@layer layout {
2
2
  .aia-stack {
3
3
  display: flex;
4
4
  flex-direction: column;
@@ -57,9 +57,35 @@ var L=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;t
57
57
  @layer layout {
58
58
  .aia-grid {
59
59
  display: grid;
60
- grid-template-columns: repeat(auto-fit, minmax(min(var(--aia-grid-min), 100%), 1fr));
60
+ grid-template-columns: repeat(
61
+ auto-fit,
62
+ minmax(min(var(--aia-grid-min), 100%), var(--aia-grid-max, 1fr))
63
+ );
61
64
  gap: var(--aia-grid-gap, 0);
62
65
  }
66
+
67
+ /* Scrollable variant \u2014 capped height with a styled thin scrollbar. Rows pack
68
+ from the top instead of stretching to fill the container. */
69
+ .aia-grid[data-scroll] {
70
+ grid-auto-rows: min-content;
71
+ align-content: start;
72
+ justify-content: start;
73
+ padding: var(--aia-grid-scroll-pad, 0);
74
+ max-height: var(--aia-grid-max-height, 192px);
75
+ overflow-y: auto;
76
+ scrollbar-width: thin;
77
+ scrollbar-color: var(--aia-scrollbar-thumb, rgba(255, 255, 255, 0.3)) transparent;
78
+ }
79
+ .aia-grid[data-scroll]::-webkit-scrollbar {
80
+ width: 6px;
81
+ }
82
+ .aia-grid[data-scroll]::-webkit-scrollbar-track {
83
+ background: transparent;
84
+ }
85
+ .aia-grid[data-scroll]::-webkit-scrollbar-thumb {
86
+ background: var(--aia-scrollbar-thumb, rgba(255, 255, 255, 0.3));
87
+ border-radius: 3px;
88
+ }
63
89
  }
64
90
 
65
91
  /* ===================================================================
@@ -79,14 +105,14 @@ var L=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;t
79
105
 
80
106
  /* --- Input wrapper --- */
81
107
  .magicx-aia-input-wrapper {
82
- padding: 20px;
83
- border: 1px solid var(--aia-color-border-default, #9ea5b2);
84
- border-radius: 23px;
85
- background: transparent;
108
+ padding: 19px 15px 20px 25px;
109
+ border: 1px solid var(--aia-border, #b0b0b0);
110
+ border-radius: 30px;
111
+ background: var(--aia-surface, #ffffff);
86
112
  overflow: hidden;
87
113
  display: flex;
88
114
  align-items: center;
89
- gap: 0px;
115
+ gap: 4px;
90
116
  }
91
117
 
92
118
  /* --- Editor area (wraps the editable input + inline pill list sibling) --- */
@@ -125,7 +151,6 @@ var L=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;t
125
151
  .magicx-aia-input[data-aia-empty="true"] {
126
152
  display: inline-block;
127
153
  min-width: 1px;
128
- vertical-align: top;
129
154
  }
130
155
 
131
156
  /* Completed params render as inline bold runs. Specificity stays at (0,2,0)
@@ -222,12 +247,24 @@ var L=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;t
222
247
  margin-top: 6px;
223
248
  display: flex;
224
249
  flex-direction: column;
250
+ box-sizing: border-box;
251
+ padding: 15px 0;
225
252
  overflow: hidden;
226
253
  container-type: inline-size;
227
254
  z-index: 10;
228
255
  opacity: 0;
229
256
  pointer-events: none;
230
257
  transition: opacity 400ms cubic-bezier(0.4, 0, 0.2, 1);
258
+ /* Solid surface is the default (matches the Figma components). Opt into the
259
+ frosted-glass look with data-aia-surface="glass". */
260
+ background: var(--aia-surface, #ffffff);
261
+ border: 1px solid var(--aia-border, #b0b0b0);
262
+ border-radius: 25px;
263
+ }
264
+
265
+ .magicx-aia-dropdown[data-aia-surface="glass"] {
266
+ background: transparent;
267
+ border-color: transparent;
231
268
  box-shadow:
232
269
  hsla(0, 0%, 100%, 1) -3.2px -3.2px 3.2px -3.2px inset,
233
270
  hsla(0, 0%, 100%, 1) 6.4px 6.4px 1.6px -8px inset,
@@ -240,7 +277,6 @@ var L=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;t
240
277
  inset 0 0 30px 5px hsla(0, 0%, 0%, 0.05),
241
278
  hsla(0, 0%, 0%, 0.08) 0px 0px 30px 2px;
242
279
  backdrop-filter: blur(30px);
243
- border-radius: 28px;
244
280
  }
245
281
 
246
282
  .magicx-aia-dropdown--visible {
@@ -248,9 +284,11 @@ var L=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;t
248
284
  pointer-events: auto;
249
285
  }
250
286
 
251
- /* --- Pill bar (inside dropdown) --- */
287
+ /* --- Pill bar (inside dropdown) ---
288
+ The dropdown pads only vertically; each child insets its own 15px so option
289
+ highlights can span the full dropdown width. */
252
290
  .magicx-aia-pill-bar {
253
- padding: 27px 27px 0px 27px;
291
+ padding: 0 15px;
254
292
  }
255
293
 
256
294
  /* --- Fallback loading skeleton bars (only when no cached options) --- */
@@ -258,7 +296,7 @@ var L=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;t
258
296
  display: flex;
259
297
  flex-direction: column;
260
298
  gap: 20px;
261
- padding: 25px;
299
+ padding: 10px 15px;
262
300
  }
263
301
 
264
302
  .magicx-aia-skeleton-bar {
@@ -288,6 +326,73 @@ var L=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;t
288
326
  }
289
327
  }
290
328
 
329
+ /* --- Footer (keyboard hint + AI-Autocomplete branding) ---
330
+ The footer insets its own 15px horizontally (the dropdown only pads
331
+ vertically), so the divider spans the full footer width yet still stays clear
332
+ of the dropdown's rounded edges. */
333
+ .magicx-aia-footer {
334
+ display: flex;
335
+ flex-direction: column;
336
+ gap: 12px;
337
+ padding: 0 15px;
338
+ }
339
+
340
+ .magicx-aia-footer-divider {
341
+ border-top: 0.5px solid var(--aia-footer-divider, rgba(176, 176, 176, 0.4));
342
+ }
343
+
344
+ .magicx-aia-footer-key {
345
+ display: inline-flex;
346
+ align-items: center;
347
+ justify-content: center;
348
+ min-width: 30px;
349
+ height: 22px;
350
+ padding: 2px 6px;
351
+ border: 0.5px solid var(--aia-footer-hint-color, #505050);
352
+ border-radius: 5px;
353
+ font-family: inherit;
354
+ font-size: 12px;
355
+ line-height: 18px;
356
+ color: var(--aia-footer-hint-color, #505050);
357
+ }
358
+
359
+ .magicx-aia-footer-hint {
360
+ font-family: inherit;
361
+ font-size: 12px;
362
+ line-height: 18px;
363
+ color: var(--aia-footer-hint-color, #505050);
364
+ }
365
+
366
+ .magicx-aia-footer-brand-link {
367
+ text-decoration: none;
368
+ cursor: pointer;
369
+ transition: opacity 150ms ease-out;
370
+ }
371
+
372
+ .magicx-aia-footer-brand-link:hover {
373
+ opacity: 0.7;
374
+ }
375
+
376
+ .magicx-aia-footer-brand {
377
+ font-family: inherit;
378
+ font-size: 10px;
379
+ line-height: 18px;
380
+ color: var(--aia-footer-brand-color, #b0b0b0);
381
+ }
382
+
383
+ .magicx-aia-footer-badge {
384
+ display: inline-flex;
385
+ align-items: center;
386
+ height: 23px;
387
+ padding: 2.5px 5.5px;
388
+ border: 0.36px solid var(--aia-footer-badge-border, rgba(189, 189, 189, 0.51));
389
+ border-radius: 999px;
390
+ font-family: inherit;
391
+ font-size: 10px;
392
+ line-height: 18px;
393
+ color: var(--aia-footer-brand-color, #b0b0b0);
394
+ }
395
+
291
396
  /* --- Loading mask on real options (preserves layout, hides text) --- */
292
397
  .magicx-aia-option[data-aia-loading] {
293
398
  cursor: default;
@@ -307,6 +412,12 @@ var L=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;t
307
412
  box-decoration-break: clone;
308
413
  }
309
414
 
415
+ .magicx-aia-option-tag {
416
+ font-size: 11px;
417
+ margin-left: 6px;
418
+ opacity: 0.5;
419
+ }
420
+
310
421
  .magicx-aia-option[data-aia-loading] .magicx-aia-option-tag {
311
422
  display: none;
312
423
  }
@@ -327,10 +438,9 @@ var L=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;t
327
438
  z-index: 1;
328
439
  pointer-events: auto;
329
440
  display: inline-flex;
330
- gap: 5px;
441
+ gap: 7px;
331
442
  align-items: center;
332
443
  vertical-align: middle;
333
- transform: translateY(-3px);
334
444
  }
335
445
 
336
446
  /* --- Individual pill --- */
@@ -338,14 +448,14 @@ var L=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;t
338
448
  display: inline-flex;
339
449
  align-items: center;
340
450
  justify-content: center;
341
- height: 36px;
342
- padding: 13px 13px;
451
+ height: 38px;
452
+ padding: 10px 12px;
343
453
  border: none;
344
454
  border-radius: 999px;
345
455
  background: rgba(49, 50, 85, 0.25);
346
456
  background: color-mix(
347
457
  in srgb,
348
- var(--aia-pill-bg, var(--aia-color-background-supportive, #313255)) 25%,
458
+ var(--aia-pill-bg, var(--aia-color-background-supportive, #313255)) 30%,
349
459
  transparent
350
460
  );
351
461
  color: var(--aia-pill-color, var(--aia-color-text-muted, #c1c4cb));
@@ -355,32 +465,12 @@ var L=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;t
355
465
  cursor: pointer;
356
466
  white-space: nowrap;
357
467
  animation: magicx-aia-fadeIn 400ms cubic-bezier(0.4, 0, 0.2, 1) forwards;
358
- box-shadow:
359
- hsla(0, 0%, 100%, 1) -3.2px -3.2px 3.2px -3.2px inset,
360
- hsla(0, 0%, 100%, 1) 6.4px 6.4px 1.6px -8px inset,
361
- var(--aia-dropdown-bg, transparent) -6.4px 6.4px 1.6px -8px inset,
362
- var(--aia-dropdown-bg, transparent) 6.4px -6.4px 1.6px -8px inset,
363
- hsla(0, 0%, 100%, 0.15) -1.6px 0px 0px -1.6px inset,
364
- hsla(0, 0%, 100%, 0.15) 0px -1.6px 0px -1.6px inset,
365
- hsla(0, 0%, 100%, 0.3) 0px 1.6px 0px 0px inset,
366
- hsla(0, 0%, 100%, 0.3) 1.6px 0px 0px 0px inset,
367
- inset 0 0 30px 5px hsla(0, 0%, 0%, 0.05),
368
- hsla(0, 0%, 0%, 0.08) 0px 0px 30px 2px;
369
- backdrop-filter: blur(30px);
370
468
  }
371
469
 
372
470
  .magicx-aia-pill--rounded {
373
471
  border-radius: 999px;
374
472
  }
375
473
 
376
- .magicx-aia-pill:hover {
377
- filter: brightness(1.2);
378
- }
379
-
380
- .magicx-aia-pill--active {
381
- outline: 1px solid #5a5b8a;
382
- }
383
-
384
474
  /* Real pill rendered as a skeleton (mirrored from cached pills during loading).
385
475
  Preserves the pill's full box so width/height match the previous state. */
386
476
  .magicx-aia-pill[data-aia-loading] {
@@ -422,39 +512,10 @@ var L=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;t
422
512
  }
423
513
  }
424
514
 
425
- /* --- Options grid --- */
426
- .magicx-aia-grid {
427
- display: grid;
428
- grid-template-columns: minmax(0, 250px);
429
- /* Pack rows from the top instead of stretching to fill the grid container. */
430
- grid-auto-rows: min-content;
431
- align-content: start;
432
- justify-content: start;
433
- padding: 8px 8px;
434
- max-height: 192px;
435
- overflow-y: auto;
436
- scrollbar-width: thin;
437
- scrollbar-color: rgba(255, 255, 255, 0.3) transparent;
438
- }
439
-
440
- @container (min-width: 516px) {
441
- .magicx-aia-grid {
442
- grid-template-columns: repeat(2, minmax(0, 250px));
443
- }
444
- }
445
-
446
- .magicx-aia-grid::-webkit-scrollbar {
447
- width: 6px;
448
- }
449
-
450
- .magicx-aia-grid::-webkit-scrollbar-track {
451
- background: transparent;
452
- }
453
-
454
- .magicx-aia-grid::-webkit-scrollbar-thumb {
455
- background: rgba(255, 255, 255, 0.3);
456
- border-radius: 3px;
457
- }
515
+ /* --- Options grid ---
516
+ Layout (auto-fit columns, scroll, scrollbar styling) is provided by the
517
+ \`.aia-grid\` / \`.aia-grid[data-scroll]\` layout primitive (see layout/Grid.css).
518
+ The \`.magicx-aia-grid\` class remains on the element as a public override hook. */
458
519
 
459
520
  /* --- Option item --- */
460
521
  .magicx-aia-option {
@@ -472,7 +533,10 @@ var L=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;t
472
533
  white-space: normal;
473
534
  word-break: break-word;
474
535
  border-radius: 12px;
475
- padding: 13px 13px;
536
+ /* Symmetric 15px inset (matches Figma). The dropdown pads only vertically, so
537
+ the option fills the full cell width \u2014 its highlight/border-streak animation
538
+ reaches the dropdown edges while the text stays inset 15px. */
539
+ padding: 10px 15px;
476
540
  animation: magicx-aia-optionFadeIn 500ms cubic-bezier(0.4, 0, 0.2, 1) forwards;
477
541
  }
478
542
 
@@ -504,12 +568,6 @@ var L=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;t
504
568
  background: var(--aia-option-bg, transparent);
505
569
  }
506
570
 
507
- .magicx-aia-option-tag {
508
- font-size: 11px;
509
- margin-left: 6px;
510
- opacity: 0.5;
511
- }
512
-
513
571
  .magicx-aia-option--pressed {
514
572
  opacity: 0.8;
515
573
  color: var(--aia-option-color-selected, var(--aia-color-text-default, #fff));
@@ -821,17 +879,19 @@ var L=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;t
821
879
  /* Light mode defaults (base) */
822
880
  :where(.magicx-aia),
823
881
  :where(.magicx-aia[data-mode="light"]) {
882
+ --aia-surface: #ffffff;
883
+ --aia-border: #b0b0b0;
824
884
  --aia-pill-bg: #bdbdbd;
825
- --aia-pill-color: #000000;
826
- --aia-pill-font-size: 19px;
885
+ --aia-pill-color: #333539;
886
+ --aia-pill-font-size: 18px;
827
887
 
828
888
  --aia-option-bg: transparent;
829
- --aia-option-color: #4f4f4f;
889
+ --aia-option-color: #505050;
830
890
  --aia-option-color-selected: #000000;
831
- --aia-option-font-size: 19px;
891
+ --aia-option-font-size: 18px;
832
892
 
833
893
  --aia-written-text-color: #000000;
834
- --aia-written-text-font-size: 19px;
894
+ --aia-written-text-font-size: 20px;
835
895
  --aia-caret-color: var(--aia-written-text-color, #000000);
836
896
 
837
897
  --aia-submit-bg: #000000;
@@ -843,21 +903,28 @@ var L=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;t
843
903
 
844
904
  --aia-streak-rgb: 99, 102, 241;
845
905
  --aia-streak-glass-bg: rgba(99, 102, 241, 0.1);
906
+
907
+ --aia-footer-divider: rgba(176, 176, 176, 0.4);
908
+ --aia-footer-hint-color: #505050;
909
+ --aia-footer-brand-color: #b0b0b0;
910
+ --aia-footer-badge-border: rgba(189, 189, 189, 0.51);
846
911
  }
847
912
 
848
913
  /* Dark mode defaults */
849
914
  :where(.magicx-aia[data-mode="dark"]) {
915
+ --aia-surface: #000000;
916
+ --aia-border: #505050;
850
917
  --aia-pill-bg: #bdbdbd;
851
- --aia-pill-color: #ffffff;
852
- --aia-pill-font-size: 19px;
918
+ --aia-pill-color: #b0b0b0;
919
+ --aia-pill-font-size: 18px;
853
920
 
854
921
  --aia-option-bg: transparent;
855
922
  --aia-option-color: #b0b0b0;
856
923
  --aia-option-color-selected: #ffffff;
857
- --aia-option-font-size: 19px;
924
+ --aia-option-font-size: 18px;
858
925
 
859
926
  --aia-written-text-color: #ffffff;
860
- --aia-written-text-font-size: 19px;
927
+ --aia-written-text-font-size: 20px;
861
928
  --aia-caret-color: var(--aia-written-text-color, #ffffff);
862
929
 
863
930
  --aia-submit-bg: #ffffff;
@@ -869,19 +936,32 @@ var L=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;t
869
936
 
870
937
  --aia-streak-rgb: 255, 255, 255;
871
938
  --aia-streak-glass-bg: rgba(255, 255, 255, 0.1);
939
+
940
+ --aia-footer-divider: rgba(255, 255, 255, 0.15);
941
+ --aia-footer-hint-color: #b0b0b0;
942
+ --aia-footer-brand-color: #505050;
943
+ --aia-footer-badge-border: #505050;
872
944
  }
873
945
 
874
- /* optionsPosition: dropdown above the input */
946
+ /* optionsPosition: dropdown above the input. The sections live inside the
947
+ dropdown's .aia-stack, so the reversal targets the stack (not the dropdown,
948
+ whose only child is the stack). */
875
949
  :where(.magicx-aia[data-options-position="above"]) [data-aia-dropdown] {
876
950
  top: auto;
877
951
  bottom: 100%;
878
952
  margin-top: 0;
879
953
  margin-bottom: 6px;
954
+ }
955
+
956
+ :where(.magicx-aia[data-options-position="above"]) [data-aia-dropdown] .aia-stack {
880
957
  flex-direction: column-reverse;
881
958
  }
882
959
 
883
- :where(.magicx-aia[data-options-position="above"]) [data-aia-pillbar] {
884
- padding: 13px 27px 13px 27px;
960
+ /* The footer sits at the top when the dropdown is above, so flip its own
961
+ internal stack too \u2014 the divider should sit BELOW the hint/branding row
962
+ (between the footer and the options beneath it), not above it. */
963
+ :where(.magicx-aia[data-options-position="above"]) [data-aia-dropdown] .magicx-aia-footer {
964
+ flex-direction: column-reverse;
885
965
  }
886
966
 
887
967
  /* Disable all animations when data-animations="off" */
@@ -891,5 +971,5 @@ var L=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;t
891
971
  animation-duration: 0s !important;
892
972
  transition-duration: 0s !important;
893
973
  }
894
- `;var z=class{constructor(){this.listeners={}}on(e,t){let i=(...s)=>t(...s),r=this.listeners[e];return r||(r=new Set,this.listeners[e]=r),r.add(i),()=>{this.listeners[e]?.delete(i)}}emit(e,...t){let i=this.listeners[e];if(i)for(let r of i)r(...t)}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var X=class{constructor(){this.timers=new Map}schedule(e,t,i){this.clear(e);let r=setTimeout(()=>{this.timers.delete(e),t()},i);this.timers.set(e,r)}clear(e){let t=this.timers.get(e);t!==void 0&&(clearTimeout(t),this.timers.delete(e))}clearAll(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};var 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 et(n){return(n??k).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function tt(n){return D(n)?`Bearer ${await R(n).getToken()}`:N(n)}async function Me(n){try{let e=et(n.apiConfig?.endpoint),t=_(n.apiConfig),i=await tt(n.apiConfig);i&&(t.Authorization=i);let r=JSON.stringify({source:n.source,session_id:n.sessionId,type:n.type,at:new Date().toISOString(),query_data:n.queryData});await fetch(e,{method:"POST",headers:t,body:r})}catch{}}var nt="newParam",Le="suggestionRemoval",it="selectionAnimation",rt=650,ot=0;function st(){return`:ac-${++ot}:`}var ke=500;function Re(){return{text:"",completedParams:[],suggestions:[],activeDropdownIndex:-1,newParamId:null,isLoading:!1,isReady:!1,error:null,filterBase:0,filterInProgress:!1,pillTapped:!1,skipNextFetch:!1,lastRawQuery:"",isFocused:!1,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:null,inSelectionAnimation:!1}}var ae=class{constructor(e,t={}){this.inputStore=oe(Re());this._listboxId=st();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new X;this.emitter=new z;this.sessionId=crypto.randomUUID();this.emitSubmit=e=>this.emitter.emit("submit",e);this.emitError=e=>this.emitter.emit("error",e);this.container=e,this.opts=t,this.renderMode=t.renderMode??"full",this.store=Oe(this.inputStore,i=>ve(i,this.opts)),t.onSubmit&&this.emitter.on("submit",t.onSubmit),t.onError&&this.emitter.on("error",t.onError),t.onChange&&this.emitter.on("change",t.onChange),t.onParamsChange&&this.emitter.on("paramsChange",t.onParamsChange),t.onStateChange&&this.emitter.on("stateChange",t.onStateChange),t.onFocus&&this.emitter.on("focus",t.onFocus),t.onBlur&&this.emitter.on("blur",t.onBlur),t.value!==void 0&&this.store.set({text:t.value}),t.completedParams!==void 0&&this.store.set({completedParams:t.completedParams}),this.pillsController=new $(this.store,{onPillSelected:({rawQuery:i,selectedPill:r,otherPills:s})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:r,other_pills:s})}}),this.reEdit=new q({store:this.store,scheduleSetCursor:i=>this.scheduleSetCursor(i),fireTelemetry:(i,r)=>this.fireTelemetry(i,r),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer()}),this.fetchController=new F(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.emitter.hasListeners("error")?this.emitError:void 0,()=>this.sessionId,{onAutoMatch:({active:i,matched:r,rawQuery:s})=>{this.fireTelemetry("option",{raw_query:s,selected_option:r.text,other_options:(i.options??[]).filter(o=>o.text!==r.text).map(o=>o.text)})}}),this.keyboardController=new Q(this.store,{columns:t.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.emitter.hasListeners("submit")?this.emitSubmit:void 0,getOptionsPosition:()=>this.opts.optionsPosition??"below",afterSubmit:this.renderMode==="full"?()=>this.reset():void 0,selectOption:i=>this.selectOption(i),removeParamAtCaret:i=>this.removeParamAtCaret(i),exitEditMode:()=>this.exitEditMode()}),this.unsubscribers.push(this.store.subscribe((i,r)=>{i.text!==r.text&&this.emitter.emit("change",i.text),i.completedParams!==r.completedParams&&this.emitter.emit("paramsChange",i.completedParams),i.isFocused!==r.isFocused&&(i.isFocused?this.emitter.emit("focus"):this.emitter.emit("blur")),this.emitter.emit("stateChange",i)})),this.unsubscribers.push(this.store.subscribe(()=>this.maybeExitReEditOnNoMatch())),this.renderMode!=="headless"&&(De(),this.setupContainer()),this.renderMode==="full"?this.buildAndRenderFull():this.renderMode==="dropdown"&&this.buildAndRenderDropdown(),this.fetchController.start()}focus(){this.domRefs?.input.focus()}blur(){this.domRefs?.input.blur()}reset(){let e=this.store.get().isFocused;this.store.set({...Re(),isFocused:e,skipNextFetch:!0}),this.sessionId=crypto.randomUUID(),this.fetchController.doFetch("",[])}destroy(){this.fetchController.dispose(),this.modeController?.destroy(),this.timers.clearAll(),this.emitter.clear();for(let e of this.unsubscribers)e();this.unsubscribers=[],this.domRefs?.abort.abort(),this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}setValue(e){this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e);let t=this.store.get().text.length;this.store.set({caretOffset:t,isFocused:!0}),this.scheduleSetCursor(t)}removeLastParam(){this.pillsController.removeLastParam()}removeParamAtCaret(e){let t=this.store.get(),{text:i,completedParams:r}=t,s=0;for(let o=0;o<r.length;o++){let a=r[o],l=i.indexOf(a.text,s);if(l===-1)continue;let d=l,p=l+a.text.length;if(e>d&&e<=p){let c=Z(i,e),m=i.slice(0,c)+i.slice(e),b=r.filter((g,h)=>h!==o);return this.store.set(g=>({text:m,filterBase:Math.min(g.filterBase,m.length),completedParams:b,pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(c),!0}s=p}return!1}scheduleSetCursor(e){queueMicrotask(()=>{let t=this.domRefs;t?(t.input.focus(),P(t.input,e)):this.opts.setCursor?.(e)})}clearNewParamId(){this.store.set({newParamId:null})}startEditingParam(e){this.reEdit.start(e)}replaceEditingRange(e){return this.reEdit.replaceRange(e)}exitEditMode(){this.reEdit.exit()}handleCaretAfterInput(e){this.reEdit.caretAfterInput(e)}handleCaretMove(e){this.reEdit.caretMove(e)}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}handleTextChange(e){this.handleChange(e)}handleKeyDown(e){this.keyboardController.handleKeyDown(e)}setFocused(e){this.store.get().isFocused!==e&&this.store.set({isFocused:e})}subscribe(e){return this.store.subscribe(t=>e(t))}getState(){return this.store.get()}get listboxId(){return this._listboxId}get isReady(){return this.store.get().isReady}on(e,t){return this.emitter.on(e,t)}update(e){Object.assign(this.opts,e),e.mode!==void 0&&this.modeController?.setMode(e.mode),e.optionsPosition!==void 0&&(this.container.dataset.optionsPosition=e.optionsPosition),e.animations!==void 0&&(this.container.dataset.animations=e.animations?"on":"off"),e.pillPlacement!==void 0&&(this.container.dataset.pillPlacement=e.pillPlacement,this.store.set({})),(e.dropdownTrigger!==void 0||e.closeDropdownOnBlur!==void 0||e.showNonTappableOptions!==void 0)&&this.store.set({}),e.value!==void 0&&this.store.set({text:e.value}),e.completedParams!==void 0&&this.store.set({completedParams:e.completedParams})}selectOption(e){let t=this.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null){this.reEdit.selectOption(e);return}let i=Ie(t,e);if(i&&(this.fireTelemetry("option",{raw_query:v(t.text,t.completedParams).rawQuery,selected_option:i.telemetry.selectedOption,other_options:i.telemetry.otherOptions}),this.store.set(i.patch),this.startSelectionAnimationTimer(),this.timers.clear(Le),i.remainingActionable>0)){let r=i.consumedSuggestion;this.timers.schedule(Le,()=>{this.store.set(s=>({suggestions:s.suggestions.filter(o=>o!==r)}))},ke)}}startSelectionAnimationTimer(){this.timers.schedule(it,()=>this.store.set({inSelectionAnimation:!1}),ke)}fireTelemetry(e,t){let i=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");Me({source:i,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}setupContainer(){this.container.classList.add("magicx-aia"),this.container.dataset.pillPlacement=this.renderMode==="dropdown"?"dropdown":this.opts.pillPlacement??"inline",this.container.dataset.optionsPosition=this.opts.optionsPosition??"below",this.container.dataset.animations=this.opts.animations??!0?"on":"off",this.modeController=new M(this.container,this.opts.mode??"auto")}buildAndRenderFull(){let e=this,t={store:this.store,listboxId:this.listboxId,get pillPlacement(){return e.opts.pillPlacement??"inline"},get onSubmit(){return e.emitter.hasListeners("submit")?e.emitSubmit:void 0},afterSubmit:()=>e.reset(),submitButton:this.opts.submitButton,autoFocus:this.opts.autoFocus??!0,selectOption:i=>this.selectOption(i),setActivePill:i=>this.pillsController.setActivePill(i),handleKeyDown:i=>this.keyboardController.handleKeyDown(i),handleChange:i=>this.handleChange(i),startEditingParam:i=>this.startEditingParam(i),handleCaretAfterInput:i=>this.handleCaretAfterInput(i),handleCaretMove:i=>this.handleCaretMove(i),replaceEditingRange:i=>this.replaceEditingRange(i)};this.domRefs=Ae(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&re(this.domRefs,this.store.get(),t)}),re(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=we(this.container,e),this.subscribeBatchedRender(()=>{this.dropdownRefs&&ne(this.dropdownRefs,this.store.get(),e)}),ne(this.dropdownRefs,this.store.get(),e),this.subscribeNewParamTimer()}subscribeBatchedRender(e){let t=!1;this.unsubscribers.push(this.store.subscribe(()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,t)=>{e.newParamId&&e.newParamId!==t.newParamId&&this.timers.schedule(nt,()=>this.store.set({newParamId:null}),rt)}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:r}=ye(e,t.completedParams);r.length>0&&this.store.set({completedParams:i}),this.maybePromoteExactMatch(e)}maybeExitReEditOnNoMatch(){let e=this.store.get();if(!e.editingParam||e.editingAnchor==null||e.completedParams.some(a=>a.id===e.editingParam?.id))return;let t=e.caretOffset??e.editingAnchor,i=e.text.slice(e.editingAnchor,t);if(E(e.editingParam.options,i).some(a=>a.is_tappable))return;this.reEdit.exit();let{rawQuery:s,completedParams:o}=v(e.text,e.completedParams);this.fetchController.doFetch(s,o)}maybePromoteExactMatch(e){let t=this.store.get(),i=U({mode:"fresh",text:e,completedParams:t.completedParams,suggestions:t.suggestions,filterBase:t.filterBase,filterInProgress:t.filterInProgress});i&&this.store.set(i.patch)}};export{ae as AIAutocomplete,M as ModeController,v as buildQuery,oe as createStore,J as cursorIsAtEnd,K as extractPlainText,T as getCursorOffset,Y as plainTextLength,Z as previousGraphemeBoundary,ie as renderEditableContent,P as setCursorOffset};
974
+ `;var z=class{constructor(){this.listeners={}}on(e,t){let i=(...s)=>t(...s),r=this.listeners[e];return r||(r=new Set,this.listeners[e]=r),r.add(i),()=>{this.listeners[e]?.delete(i)}}emit(e,...t){let i=this.listeners[e];if(i)for(let r of i)r(...t)}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var X=class{constructor(){this.timers=new Map}schedule(e,t,i){this.clear(e);let r=setTimeout(()=>{this.timers.delete(e),t()},i);this.timers.set(e,r)}clear(e){let t=this.timers.get(e);t!==void 0&&(clearTimeout(t),this.timers.delete(e))}clearAll(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};var M=class{constructor(e,t="auto",i){this.container=e;this.mode=t;this.onResolve=i;this.mediaQuery=null;this.onSystemChange=e=>{this.setResolved(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.setResolved(this.mediaQuery.matches?"dark":"light")):this.setResolved(this.mode)}setResolved(e){this.container.dataset.mode=e,this.onResolve?.(e)}detachListener(){this.mediaQuery?.removeEventListener("change",this.onSystemChange)}};function ot(n){return(n??L).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function st(n){return D(n)?`Bearer ${await R(n).getToken()}`:_(n)}async function Re(n){try{let e=ot(n.apiConfig?.endpoint),t=N(n.apiConfig),i=await st(n.apiConfig);i&&(t.Authorization=i);let r=JSON.stringify({source:n.source,session_id:n.sessionId,type:n.type,at:new Date().toISOString(),query_data:n.queryData});await fetch(e,{method:"POST",headers:t,body:r})}catch{}}var at="newParam",Ne="suggestionRemoval",lt="selectionAnimation",dt=650,ct=0;function pt(){return`:ac-${++ct}:`}var _e=500;function He(){return{text:"",completedParams:[],suggestions:[],activeDropdownIndex:-1,newParamId:null,isLoading:!1,isReady:!1,error:null,filterBase:0,filterInProgress:!1,pillTapped:!1,skipNextFetch:!1,lastRawQuery:"",isFocused:!1,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:null,inSelectionAnimation:!1,hasTabbedToHighlight:!1}}var le=class{constructor(e,t={}){this.inputStore=se(He());this._listboxId=pt();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new X;this.emitter=new z;this.sessionId=crypto.randomUUID();this.emitSubmit=e=>this.emitter.emit("submit",e);this.emitError=e=>this.emitter.emit("error",e);this.container=e,this.opts=t,this.renderMode=t.renderMode??"full",this.store=ke(this.inputStore,i=>Pe(i,this.opts)),t.onSubmit&&this.emitter.on("submit",t.onSubmit),t.onError&&this.emitter.on("error",t.onError),t.onChange&&this.emitter.on("change",t.onChange),t.onParamsChange&&this.emitter.on("paramsChange",t.onParamsChange),t.onStateChange&&this.emitter.on("stateChange",t.onStateChange),t.onFocus&&this.emitter.on("focus",t.onFocus),t.onBlur&&this.emitter.on("blur",t.onBlur),t.value!==void 0&&this.store.set({text:t.value}),t.completedParams!==void 0&&this.store.set({completedParams:t.completedParams}),this.pillsController=new q(this.store,{onPillSelected:({rawQuery:i,selectedPill:r,otherPills:s})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:r,other_pills:s})}}),this.reEdit=new U({store:this.store,scheduleSetCursor:i=>this.scheduleSetCursor(i),fireTelemetry:(i,r)=>this.fireTelemetry(i,r),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer()}),this.fetchController=new H(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.emitter.hasListeners("error")?this.emitError:void 0,()=>this.sessionId,{onAutoMatch:({active:i,matched:r,rawQuery:s})=>{this.fireTelemetry("option",{raw_query:s,selected_option:r.text,other_options:(i.options??[]).filter(o=>o.text!==r.text).map(o=>o.text)})}}),this.keyboardController=new Q(this.store,{columns:t.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.emitter.hasListeners("submit")?this.emitSubmit:void 0,getOptionsPosition:()=>this.opts.optionsPosition??"below",afterSubmit:this.renderMode==="full"?()=>this.reset():void 0,selectOption:i=>this.selectOption(i),removeParamAtCaret:i=>this.removeParamAtCaret(i),exitEditMode:()=>this.exitEditMode()}),this.unsubscribers.push(this.store.subscribe((i,r)=>{i.text!==r.text&&this.emitter.emit("change",i.text),i.completedParams!==r.completedParams&&this.emitter.emit("paramsChange",i.completedParams),i.isFocused!==r.isFocused&&(i.isFocused?this.emitter.emit("focus"):this.emitter.emit("blur")),this.emitter.emit("stateChange",i)})),this.unsubscribers.push(this.store.subscribe(()=>this.maybeExitReEditOnNoMatch())),this.renderMode!=="headless"&&(Le(),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(){let e=this.store.get().isFocused;this.store.set({...He(),isFocused:e,skipNextFetch:!0}),this.sessionId=crypto.randomUUID(),this.fetchController.doFetch("",[])}destroy(){this.fetchController.dispose(),this.modeController?.destroy(),this.timers.clearAll(),this.emitter.clear();for(let e of this.unsubscribers)e();this.unsubscribers=[],this.domRefs?.abort.abort(),this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}setValue(e){this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e);let t=this.store.get().text.length;this.store.set({caretOffset:t,isFocused:!0}),this.scheduleSetCursor(t)}removeLastParam(){this.pillsController.removeLastParam()}removeParamAtCaret(e){let t=this.store.get(),{text:i,completedParams:r}=t,s=0;for(let o=0;o<r.length;o++){let a=r[o],d=i.indexOf(a.text,s);if(d===-1)continue;let l=d,p=d+a.text.length;if(e>l&&e<=p){let c=Z(i,e),g=i.slice(0,c)+i.slice(e),b=r.filter((u,x)=>x!==o);return this.store.set(u=>({text:g,filterBase:Math.min(u.filterBase,g.length),completedParams:b,pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(c),!0}s=p}return!1}scheduleSetCursor(e){queueMicrotask(()=>{let t=this.domRefs;t?(t.input.focus(),T(t.input,e)):this.opts.setCursor?.(e)})}clearNewParamId(){this.store.set({newParamId:null})}startEditingParam(e){this.reEdit.start(e)}replaceEditingRange(e){return this.reEdit.replaceRange(e)}exitEditMode(){this.reEdit.exit()}handleCaretAfterInput(e){this.reEdit.caretAfterInput(e)}handleCaretMove(e){this.reEdit.caretMove(e)}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}handleTextChange(e){this.handleChange(e)}handleKeyDown(e){this.keyboardController.handleKeyDown(e)}setFocused(e){this.store.get().isFocused!==e&&this.store.set({isFocused:e})}subscribe(e){return this.store.subscribe(t=>e(t))}getState(){return this.store.get()}get listboxId(){return this._listboxId}get isReady(){return this.store.get().isReady}on(e,t){return this.emitter.on(e,t)}update(e){Object.assign(this.opts,e),e.mode!==void 0&&this.modeController?.setMode(e.mode),e.optionsPosition!==void 0&&(this.container.dataset.optionsPosition=e.optionsPosition),e.animations!==void 0&&(this.container.dataset.animations=e.animations?"on":"off"),e.pillPlacement!==void 0&&(this.container.dataset.pillPlacement=e.pillPlacement,this.store.set({})),(e.dropdownTrigger!==void 0||e.closeDropdownOnBlur!==void 0||e.showNonTappableOptions!==void 0)&&this.store.set({}),e.value!==void 0&&this.store.set({text:e.value}),e.completedParams!==void 0&&this.store.set({completedParams:e.completedParams})}selectOption(e){let t=this.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null){this.reEdit.selectOption(e);return}let i=Me(t,e);if(i&&(this.fireTelemetry("option",{raw_query:S(t.text,t.completedParams).rawQuery,selected_option:i.telemetry.selectedOption,other_options:i.telemetry.otherOptions}),this.store.set(i.patch),this.startSelectionAnimationTimer(),this.timers.clear(Ne),i.remainingActionable>0)){let r=i.consumedSuggestion;this.timers.schedule(Ne,()=>{this.store.set(s=>({suggestions:s.suggestions.filter(o=>o!==r)}))},_e)}}startSelectionAnimationTimer(){this.timers.schedule(lt,()=>this.store.set({inSelectionAnimation:!1}),_e)}fireTelemetry(e,t){let i=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");Re({source:i,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}setupContainer(){this.container.classList.add("magicx-aia"),this.container.dataset.pillPlacement=this.renderMode==="dropdown"?"dropdown":this.opts.pillPlacement??"inline",this.container.dataset.optionsPosition=this.opts.optionsPosition??"below",this.container.dataset.animations=this.opts.animations??!0?"on":"off",this.modeController=new M(this.container,this.opts.mode??"auto")}buildAndRenderFull(){let e=this,t={store:this.store,listboxId:this.listboxId,get pillPlacement(){return e.opts.pillPlacement??"inline"},get onSubmit(){return e.emitter.hasListeners("submit")?e.emitSubmit:void 0},afterSubmit:()=>e.reset(),submitButton:this.opts.submitButton,autoFocus:this.opts.autoFocus??!0,selectOption:i=>this.selectOption(i),setActivePill:i=>this.pillsController.setActivePill(i),handleKeyDown:i=>this.keyboardController.handleKeyDown(i),handleChange:i=>this.handleChange(i),startEditingParam:i=>this.startEditingParam(i),handleCaretAfterInput:i=>this.handleCaretAfterInput(i),handleCaretMove:i=>this.handleCaretMove(i),replaceEditingRange:i=>this.replaceEditingRange(i)};this.domRefs=De(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&oe(this.domRefs,this.store.get(),t)}),oe(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=Ae(this.container,e),this.subscribeBatchedRender(()=>{this.dropdownRefs&&ie(this.dropdownRefs,this.store.get(),e)}),ie(this.dropdownRefs,this.store.get(),e),this.subscribeNewParamTimer()}subscribeBatchedRender(e){let t=!1;this.unsubscribers.push(this.store.subscribe(()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,t)=>{e.newParamId&&e.newParamId!==t.newParamId&&this.timers.schedule(at,()=>this.store.set({newParamId:null}),dt)}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:r}=ve(e,t.completedParams);r.length>0&&this.store.set({completedParams:i}),this.maybePromoteExactMatch(e)}maybeExitReEditOnNoMatch(){let e=this.store.get();if(!e.editingParam||e.editingAnchor==null||e.completedParams.some(a=>a.id===e.editingParam?.id))return;let t=e.caretOffset??e.editingAnchor,i=e.text.slice(e.editingAnchor,t);if(w(e.editingParam.options,i).some(a=>a.is_tappable))return;this.reEdit.exit();let{rawQuery:s,completedParams:o}=S(e.text,e.completedParams);this.fetchController.doFetch(s,o)}maybePromoteExactMatch(e){let t=this.store.get(),i=$({mode:"fresh",text:e,completedParams:t.completedParams,suggestions:t.suggestions,filterBase:t.filterBase,filterInProgress:t.filterInProgress});i&&this.store.set(i.patch)}};export{le as AIAutocomplete,M as ModeController,S as buildQuery,se as createStore,J as cursorIsAtEnd,K as extractPlainText,C as getCursorOffset,te as getFooterHint,Y as plainTextLength,Z as previousGraphemeBoundary,re as renderEditableContent,T as setCursorOffset};
895
975
  //# sourceMappingURL=index.mjs.map