@magicx-eng/ai-autocomplete-vanilla 0.5.2 → 0.5.3

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.d.mts CHANGED
@@ -395,12 +395,16 @@ interface RenderEditableArgs {
395
395
  isFocused: boolean;
396
396
  }
397
397
  /**
398
- * Renders text segments including bold `<strong>` runs for completed params
399
- * into the contentEditable input. Pills are NOT rendered here; they live as
400
- * a sibling element so the editable's subtree never contains non-editable
401
- * children. See renderInput.ts for the pill list placement.
398
+ * Renders text segments into the contentEditable input. Completed params are
399
+ * emitted as `<strong data-seg="completed">` runs carrying the
400
+ * `magicx-aia-segment--completed` class, which the stylesheets restyle as
401
+ * inline pills (rounded chips). The tag stays a plain editable `<strong>` — the
402
+ * caret system counts its text as part of the editable plain text, so it must
403
+ * NOT become non-editable. The unfilled-suggestion pills are NOT rendered here;
404
+ * they live as a sibling element so the editable's subtree never contains
405
+ * non-editable children. See renderInput.ts for the pill list placement.
402
406
  *
403
- * Skips rebuilds when the segment key is unchanged so an in-flight shimmer
407
+ * Skips rebuilds when the segment key is unchanged so an in-flight reveal
404
408
  * animation isn't interrupted by unrelated state churn.
405
409
  */
406
410
  declare function renderEditableContent(args: RenderEditableArgs): void;
package/dist/index.d.ts CHANGED
@@ -395,12 +395,16 @@ interface RenderEditableArgs {
395
395
  isFocused: boolean;
396
396
  }
397
397
  /**
398
- * Renders text segments including bold `<strong>` runs for completed params
399
- * into the contentEditable input. Pills are NOT rendered here; they live as
400
- * a sibling element so the editable's subtree never contains non-editable
401
- * children. See renderInput.ts for the pill list placement.
398
+ * Renders text segments into the contentEditable input. Completed params are
399
+ * emitted as `<strong data-seg="completed">` runs carrying the
400
+ * `magicx-aia-segment--completed` class, which the stylesheets restyle as
401
+ * inline pills (rounded chips). The tag stays a plain editable `<strong>` — the
402
+ * caret system counts its text as part of the editable plain text, so it must
403
+ * NOT become non-editable. The unfilled-suggestion pills are NOT rendered here;
404
+ * they live as a sibling element so the editable's subtree never contains
405
+ * non-editable children. See renderInput.ts for the pill list placement.
402
406
  *
403
- * Skips rebuilds when the segment key is unchanged so an in-flight shimmer
407
+ * Skips rebuilds when the segment key is unchanged so an in-flight reveal
404
408
  * animation isn't interrupted by unrelated state churn.
405
409
  */
406
410
  declare function renderEditableContent(args: RenderEditableArgs): void;
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var re=Object.defineProperty;var qe=Object.getOwnPropertyDescriptor;var Qe=Object.getOwnPropertyNames;var $e=Object.prototype.hasOwnProperty;var Ue=(n,e)=>{for(var t in e)re(n,t,{get:e[t],enumerable:!0})},Ge=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Qe(e))!$e.call(n,o)&&o!==t&&re(n,o,{get:()=>e[o],enumerable:!(i=qe(e,o))||i.enumerable});return n};var We=n=>Ge(re({},"__esModule",{value:!0}),n);var Tt={};Ue(Tt,{AIAutocomplete:()=>oe,ModeController:()=>M,buildQuery:()=>S,createStore:()=>te,cursorIsAtEnd:()=>$,extractPlainText:()=>L,getCursorOffset:()=>C,getFooterHint:()=>z,plainTextLength:()=>Q,previousGraphemeBoundary:()=>U,renderEditableContent:()=>ee,setCursorOffset:()=>P});module.exports=We(Tt);var R=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 je="https://api.ai-autocomplete.com",N=`${je}/api/suggest`,ue=new WeakMap;function k(n){return n?.type==="accessToken"}function Ve(n){if(!(!n||k(n)))return n}function _(n){let e=ue.get(n.getAccessToken);return e||(e=new R(n),ue.set(n.getAccessToken,e)),e}function H(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function F(n){let e=Ve(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}var ze="0.5.2",me=!1;function Xe(){return crypto.randomUUID()}function Ye(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.text},kind:n.kind}}function Je(n,e,t,i){let o=e.find(s=>s.type==="contact"&&s.metadata?.contact_account_count)?.metadata?.contact_account_count,r=typeof o=="number"?o:void 0;return{data:{raw_query:n,completed_params:e.map(s=>Ye(s,t)),...r!=null&&{contact_account_count:r}},meta:{request_id:Xe(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:ze,session_id:i}}}async function ge(n,e,t,i,o){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:o})}async function fe(n,e,t){let i=t.apiConfig,o=!t.maskCompletedText,r=Je(n,e,o,t.sessionId),s=H(i),a=i?.endpoint??N,c=JSON.stringify(r);if(k(i)){let d=_(i),g=await d.getToken(),h=await ge(a,s,g,c,t.signal);if(h.status===401){let x=await d.getToken(!0);h=await ge(a,s,x,c,t.signal)}if(!h.ok)throw new Error(`API error: ${h.status} ${h.statusText}`);return h.json()}let l=F(i);!l&&!me&&(me=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),l&&(s.Authorization=l);let p=await fetch(a,{method:"POST",headers:s,body:c,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={},o=[];for(let r of e){let s=(i[r.type]??0)+1;i[r.type]=s;let c=`{{${r.type.toUpperCase().replace(/\s+/g,"_")}_${s}}}`,l=t.indexOf(r.text);l!==-1&&(t=t.slice(0,l)+c+t.slice(l+r.text.length)),o.push({...r,placeholder:c})}return{rawQuery:t,completedParams:o}}function I(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 o=i.indexOf(" ");return o===-1?"":i.slice(o+1)}function he(n,e){let t=n.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let i=t.split(" "),o=e.toLowerCase();for(let r=0;r<i.length;r++){let s=i.slice(r).join(" ");if(o.startsWith(s.toLowerCase())){let a=t.length-s.length;return n.length-a}}return 0}function A(n,e){if(!n)return[];let t=e.trimStart();if(!t)return n;let i=t.toLowerCase();return n.filter(o=>!o.is_tappable||o.text.toLowerCase().includes(i))}function O(n,e){if(!n)return null;let t=e.trim();if(!t)return null;let i=t.toLowerCase();return n.find(o=>o.is_tappable&&o.text.toLowerCase()===i)??null}function xe(n,e){return e?n.map(t=>{let i=e[t.type];if(!i)return t;let o=i("");if(o.length===0)return t;let r=new Set(o.map(a=>a.text)),s=(t.options??[]).filter(a=>!r.has(a.text));return{...t,options:[...o,...s]}}):n}var Ze=100,et=300,tt=2,B=class{constructor(e,t,i,o,r,s,a={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=o;this.getOnError=r;this.getSessionId=s;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 o=++this.fetchVersion,r=this.store.get().text.length;this.store.set({isLoading:!0,error:null});try{let s=await fe(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig()});if(o!==this.fetchVersion)return;let a=xe(s.data.suggestions??[],this.getOptionOverrides()),c=s.data.input??[],l=c[c.length-1],p=this.store.get().text,d,g;if(l?.state==="in_progress"){g=!0;let b=p.toLowerCase().lastIndexOf(l.text.toLowerCase());d=b!==-1?b:r}else g=!1,d=r;let x=a.filter(b=>b.type!=="placeholder")[0],f=null;if(x){let b=w(p,d,g),m=O(x.options,b);m&&(f={id:crypto.randomUUID(),placeholder:"",type:x.type,text:m.text,kind:m.kind,suggestionType:x.type,suggestionPlaceholder:x.text,options:x.options??[],metadata:m.metadata},a=a.filter(u=>u!==x),this.callbacks.onAutoMatch?.({active:x,matched:m,rawQuery:e}))}this.store.set(b=>({suggestions:a,isLoading:!1,isReady:s.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:d,filterInProgress:g,...f?{completedParams:[...b.completedParams,f]}:{}}))}catch(s){if(o===this.fetchVersion){let a=s instanceof Error?s:new Error(String(s));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 o=this.store.get();if(!o.text&&o.completedParams.length===0)return this.doFetch("",[]),!0;let r=o.suggestions.filter(u=>u.type==="placeholder").map(u=>u.text).join(" "),s=I(o.text,o.filterBase,r),a=w(o.text,s,o.filterInProgress),l=o.suggestions.filter(u=>u.type!=="placeholder")[0],d=(l?A(l.options,a):[]).filter(u=>u.is_tappable),g=l?O(l.options,a)!==null:!1,h=a.trim().length>0;if(d.length>0&&!g&&h||o.completedParams.length===0&&o.text.length>0&&r.length>0&&r.toLowerCase().startsWith(o.text.toLowerCase()))return!1;let{rawQuery:x,completedParams:f}=S(o.text,o.completedParams),b=x.length<o.lastRawQuery.length,m=Math.abs(x.length-o.lastRawQuery.length);return b||m>=i?(this.doFetch(x,f),!0):!1};this.debounceTimer=setTimeout(()=>{t(tt)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},Ze),this.slowDebounceTimer=setTimeout(()=>t(1),et)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var ye='[contenteditable="false"]',D;function nt(){if(D!==void 0)return D;let n=globalThis.Intl.Segmenter;if(!n)return D=null,null;try{D=new n(void 0,{granularity:"grapheme"})}catch{D=null}return D??null}function K(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(ye))return!0;t=t.parentNode}return!1}function q(n){return(n.ownerDocument??document).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return K(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function L(n){let e=q(n),t="",i=e.nextNode();for(;i;)t+=i.data,i=e.nextNode();return t}function Q(n){let e=q(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 o=t;if(K(o,n)&&o!==n)return null;let r=0;for(let s=0;s<i&&s<o.childNodes.length;s++)r+=ve(o.childNodes[s],n);return r+be(o,n)}return t.nodeType!==Node.TEXT_NODE||K(t,n)?null:be(t,n)+i}function ve(n,e){if(n.nodeType===Node.TEXT_NODE)return K(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(ye))return 0;let i=0;for(let o of Array.from(t.childNodes))i+=ve(o,e);return i}function be(n,e){let t=q(e),i=0,o=t.nextNode();for(;o;){if(o===n||n.nodeType===Node.ELEMENT_NODE&&n.contains(o))return i;i+=o.data.length,o=t.nextNode()}return i}function P(n,e){let t=n.ownerDocument??document,i=t.getSelection();if(!i)return;let o=Math.max(0,Math.min(e,Q(n))),r=q(n),s=0,a=null,c=0,l=r.nextNode(),p=null;for(;l;){let g=l.data.length;if(o<s+g){a=l,c=o-s;break}if(o===s+g){let h=r.nextNode();h?(a=h,c=0):(a=l,c=g);break}s+=g,p=l,l=r.nextNode()}let d=t.createRange();if(a){let g=a.parentElement?.closest('strong[data-seg="completed"]');g&&g!==n&&n.contains(g)?c===0?d.setStartBefore(g):c===a.data.length?d.setStartAfter(g):d.setStart(a,c):d.setStart(a,c)}else p?d.setStart(p,p.data.length):d.setStart(n,0);d.collapse(!0),i.removeAllRanges(),i.addRange(d)}function $(n){let e=C(n);return e==null?!1:e>=Q(n)}function U(n,e){if(e<=0)return 0;let t=nt();if(!t)return e-1;let i=n.slice(0,e),o=0;for(let{index:r}of t.segment(i))r<e&&(o=r);return o}function se(n,e){return n instanceof HTMLTextAreaElement||n instanceof HTMLInputElement?n.selectionStart!=null&&n.selectionStart===n.value.length:n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?$(n):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function it(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?C(n):null}var G=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:o}=this.ctx,r=this.getEffectiveColumns(),s=o(),a=this.getTappableIndices(r);if((e.shiftKey||e.metaKey||e.ctrlKey||e.altKey)&&(e.key==="ArrowDown"||e.key==="ArrowUp"||e.key==="ArrowLeft"||e.key==="ArrowRight"))return;let c=this.ctx.getOptionsPosition()==="above";switch(e.key){case"ArrowDown":{let l=se(e.target,t),p=!!t.editingParam;if(!l&&!p&&t.activeDropdownIndex<0)break;if(t.activeDropdownIndex<0){if(c)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 h=Math.floor((t.filteredOptions.length-1)/r);if(Math.floor(t.activeDropdownIndex/r)===h){this.store.set({activeDropdownIndex:-1});break}}let d=a.indexOf(t.activeDropdownIndex),g=d<a.length-1?d+1:0;this.store.set({activeDropdownIndex:a[g]});break}case"ArrowUp":{if(t.activeDropdownIndex<0){if(!c)break;let d=se(e.target,t),g=!!t.editingParam;if(!d&&!g)break;e.preventDefault();let h=this.firstTappableInBottomRow(r)??a[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:h});break}if(a.length===0)return;this.store.set({activeDropdownIndex:h});break}if(a.length===0)break;if(e.preventDefault(),t.activeDropdownIndex<r){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%r<r-1){let d=t.activeDropdownIndex+1;d<t.filteredOptions.length&&t.filteredOptions[d]?.is_tappable&&this.store.set({activeDropdownIndex:d})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let p=e.target.closest("[data-aia-input]")??e.target,d=t.editingTail;this.ctx.exitEditMode?.(),P(p,d);break}se(e.target,t)&&t.actionableSuggestions.length>=1&&(e.preventDefault(),this.removeActivePill());break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%r>0){let l=t.activeDropdownIndex-1;l>=0&&t.filteredOptions[l]?.is_tappable&&this.store.set({activeDropdownIndex:l})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let l=e.target.closest("[data-aia-input]")??e.target,p=t.editingAnchor;this.ctx.exitEditMode?.(),P(l,p);break}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let l=it(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(s){let{rawQuery:l,completedParams:p}=S(t.text,t.completedParams);s({query:t.text.trim(),raw_query:l,completed_params:p}),this.ctx.afterSubmit?.()}break}case"Tab":{let l=t.filteredOptions.map((g,h)=>g.is_tappable?h:-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});break}e.preventDefault();let p=l.indexOf(t.activeDropdownIndex),d;if(p<0)d=e.shiftKey?l.length-1:0;else{let g=e.shiftKey?-1:1;d=(p+g+l.length)%l.length}this.store.set({activeDropdownIndex:l[d]});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?.(),P(l,p)}this.store.set({activeDropdownIndex:-1});break}}}firstTappableInBottomRow(e){let t=this.store.get();if(t.filteredOptions.length===0)return null;let o=Math.floor((t.filteredOptions.length-1)/e)*e;for(let r=o;r<t.filteredOptions.length;r++)if(t.filteredOptions[r]?.is_tappable)return r;return null}getTappableIndices(e){let i=this.store.get().filteredOptions.map((r,s)=>r.is_tappable?s:-1).filter(r=>r!==-1),o=Array.from({length:e},()=>[]);for(let r of i)o[r%e].push(r);return o.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 o=getComputedStyle(i).gridTemplateColumns;if(o&&o!=="none"){let r=o.split(" ").filter(Boolean).length;if(r>0)return r}if(i===e)break;i=i.parentElement}return this.ctx.columns}clickOrSelect(e,t,i){let o=document.getElementById(`${i}-option-${e}`);o?o.click():this.ctx.selectOption(t[e])}removeActivePill(){let e=this.store.get(),t=e.suggestions.filter(r=>r.type==="placeholder"),i=e.suggestions.filter(r=>r.type!=="placeholder");if(i.length===0)return;let o=i.slice(1);this.store.set({suggestions:[...t,...o],pillTapped:o.length>0,activeDropdownIndex:-1})}};var W=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),i=t.suggestions.filter(l=>l.type!=="placeholder");if(e<0||e>=i.length)return;let o=i[e],r=i.filter((l,p)=>p!==e),s=t.suggestions.filter(l=>l.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:l}=S(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:l,selectedPill:o.text,otherPills:r.map(p=>p.text)})}let a=[...s,o,...r],c=this.store.peek({suggestions:a}).filteredOptions.findIndex(l=>l.is_tappable);this.store.set({suggestions:a,pillTapped:!0,activeDropdownIndex:c})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};function Se(n,e){let t=[],i=0;for(let r of e){let s=n.indexOf(r.text,i);s!==-1&&(s>i&&t.push({type:"text",value:n.slice(i,s)}),t.push({type:"completed",value:r.text,param:r}),i=s+r.text.length)}let o=n.slice(i);return o&&t.push({type:"text",value:o}),t}function Pe(n,e){let t=[],i=[],o=0;for(let r of e){let s=n.indexOf(r.text,o);s===-1?i.push(r):(t.push(r),o=s+r.text.length)}return{valid:t,invalid:i}}function Te(n,e){let t=e.dropdownTrigger??"auto",i=e.closeDropdownOnBlur??!0,r=n.filteredOptionsLength>0||n.activePillHasNoOptions;if(n.inEditMode){let s=i?n.isFocused:!0;return r&&s}if(t==="auto"){let s=i?n.isFocused:!0,a=n.text.replace(/\s+$/,"").length,c=n.caretOffset==null||n.caretOffset>=a;return(r||n.isLoading)&&s&&c}return t==="manual"?(r||n.isLoading)&&n.pillTapped:!1}function Ce(n,e){let t=Se(n.text,n.completedParams),i=n.suggestions.filter(u=>u.type!=="placeholder"),o=i[0],r=o?e.optionOverrides?.[o.type]:void 0,s=n.suggestions.filter(u=>u.type==="placeholder").map(u=>u.text).join(" "),a=I(n.text,Math.min(n.filterBase,n.text.length),s),l=n.lastRawQuery!==""||a>0?w(n.text,a,n.filterInProgress):"",p=o?r?r(l.trim()):o.options??[]:[],d=n.editingParam!=null&&n.editingAnchor!=null,g;if(d&&n.editingParam&&n.editingAnchor!=null){let u=n.editingParam.id,y=n.completedParams.some(E=>E.id===u),v=n.caretOffset??n.editingAnchor,T=y?"":n.text.slice(n.editingAnchor,v);g=A(n.editingParam.options,T)}else g=A(p,l);let h=e.showNonTappableOptions===!1;h&&(g=g.filter(u=>u.is_tappable));let x=u=>h?u.is_tappable:!0,f;if(d){let u=n.editingParam?.options??[];f=n.editingParam!=null&&u.filter(x).length===0}else{let u=o?r?r(""):o.options??[]:[];f=o!=null&&u.filter(x).length===0}let b=Te({inEditMode:d,filteredOptionsLength:g.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading,pillTapped:n.pillTapped,activePillHasNoOptions:f},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),m=b&&n.activeDropdownIndex>=0&&!!g[n.activeDropdownIndex]?.is_tappable;return{segments:t,actionableSuggestions:i,filteredOptions:g,placeholderText:s,isDropdownOpen:b,isActivePillSelected:m}}function j(n){return n.mode==="fresh"?ot(n):rt(n)}function ot(n){let{text:e,completedParams:t,suggestions:i,filterBase:o,filterInProgress:r}=n,a=i.filter(v=>v.type!=="placeholder")[0];if(!a?.options)return null;let c=i.filter(v=>v.type==="placeholder").map(v=>v.text).join(" "),l=I(e,o,c),p=w(e,l,r),d=O(a.options,p);if(!d)return null;let g=d.text.toLowerCase(),h=e.toLowerCase().lastIndexOf(g),x=h>=0?h:Math.max(0,e.length-d.text.length),f=x+d.text.length,b=e.slice(x,f),u=f<e.length&&e[f]===" "?f+1:f,y={id:crypto.randomUUID(),placeholder:"",type:a.type,text:b,kind:d.kind,suggestionType:a.type,suggestionPlaceholder:a.text,options:a.options??[],metadata:d.metadata};return{patch:{text:e,completedParams:[...t,y],suggestions:i.filter(v=>v!==a),filterBase:u,newParamId:y.id,caretOffset:u,activeDropdownIndex:-1},caretPos:u}}function rt(n){let{text:e,completedParams:t,editingParam:i,editingAnchor:o,editingTail:r}=n;if(t.some(y=>y.id===i.id))return null;let s=e.slice(o,r),a=O(i.options,s);if(!a)return null;let c=a.text.toLowerCase(),l=s.toLowerCase().lastIndexOf(c),p=o+Math.max(0,l),d=p+a.text.length,g=e.slice(p,d),x=d<e.length&&e[d]===" "?d+1:d,f={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:g,kind:a.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:a.metadata},b=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>=x){b=y;break}m=v+t[y].text.length}}let u=[...t];return u.splice(b,0,f),{patch:{text:e,completedParams:u,newParamId:f.id,filterBase:x,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:x,activeDropdownIndex:-1},caretPos:x}}var V=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(s=>s.id===e);if(!i)return;let o=0,r=-1;for(let s of t.completedParams){let a=t.text.indexOf(s.text,o);if(a!==-1){if(s.id===e){r=a;break}o=a+s.text.length}}r<0||this.deps.store.set({editingParam:i,editingAnchor:r,editingTail:r+i.text.length,caretOffset:r+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,o=t.editingAnchor,r=t.editingTail;if(!i||o==null||r==null||!t.completedParams.some(c=>c.id===i.id))return!1;let s=t.text.slice(0,o)+e+t.text.slice(r),a=o+e.length;return this.deps.store.set(c=>({text:s,completedParams:c.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,o=t.editingAnchor,r=t.editingTail;if(!i||o==null||r==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 s=t.text.slice(0,o),a=t.text.slice(r),c=o===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,l=a.length===0||a[0]!==" ",p=l?`${c} `:c,d=s+p+a,g=o+p.length+(l?0:1),h={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:c,kind:e.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:e.metadata},x=t.completedParams.findIndex(m=>m.id===i.id),f=t.completedParams.filter(m=>m.id!==i.id),b=x>=0?Math.min(x,f.length):f.length;f.splice(b,0,h),this.deps.store.set({text:d,completedParams:f,newParamId:h.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=j({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 z(n,e){return n?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}var Ee="data-aia-key";function X(n,e,t){let i=new Map;for(let s of Array.from(n.children)){let a=s.getAttribute(Ee);a!=null&&i.set(a,s)}let o=new Set,r=[];for(let s=0;s<e.length;s++){let a=e[s],c=t.keyOf(a,s);o.add(c);let l=i.get(c);l||(l=t.create(a,s),l.setAttribute(Ee,c)),t.update?.(l,a,s),n.children[s]!==l&&n.insertBefore(l,n.children[s]??null),r.push(l)}for(let[s,a]of i)o.has(s)||a.remove();return r}var we=[125,69];function Ae(n,e){return e?1:n===0?.7:n===1?.4:.2}function Y(n,e,t,i,o=!1,r=!1,s=!1){let a=n.querySelector(".magicx-aia-pill-list");if(a||(a=document.createElement("span"),a.className="magicx-aia-pill-list",n.appendChild(a)),r&&e.length===0){a.setAttribute("data-aia-pill-list-loading",""),a.innerHTML="";for(let c=0;c<we.length;c++){let l=we[c],p=document.createElement("span");p.setAttribute("data-aia-pill-skeleton",""),p.className=`magicx-aia-pill magicx-aia-pill--skeleton${o?" magicx-aia-pill--rounded":""}`,p.style.width=`${l}px`,p.style.opacity=String(Ae(c,!1)),a.appendChild(p)}return}r?a.setAttribute("data-aia-pill-list-loading",""):a.removeAttribute("data-aia-pill-list-loading");for(let c of a.querySelectorAll("[data-aia-pill-skeleton]"))c.remove();X(a,e,{keyOf:c=>`${c.type}-${c.text}`,create:c=>{let l=document.createElement("button");return l.type="button",l.tabIndex=-1,l.setAttribute("data-aia-pill",""),l.setAttribute("contenteditable","false"),l.textContent=c.text,l.addEventListener("mousedown",p=>p.preventDefault()),l},update:(c,l,p)=>{let d=c,g=s&&p===t&&!r,h=["magicx-aia-pill"];o&&h.push("magicx-aia-pill--rounded"),g&&h.push("magicx-aia-pill--active"),r&&h.push("magicx-aia-pill--skeleton"),d.className=h.join(" "),d.style.width="",d.style.opacity=String(Ae(p,g)),r?(d.setAttribute("data-aia-loading",""),d.disabled=!0,d.onclick=null):(d.removeAttribute("data-aia-loading"),d.disabled=!1,d.onclick=()=>i(p))}})}function ae(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var le=new WeakMap;function Ie(n,e,t,i,o,r,s){let a=n.querySelector(".aia-grid-fade");if(e.length===0){a&&(at(a),a.remove());return}let c=a?.querySelector(".aia-grid")??null;(!a||!c)&&(a=document.createElement("div"),a.className="aia-grid-fade",c=document.createElement("div"),c.className="aia-grid magicx-aia-grid",c.setAttribute("data-scroll",""),c.style.setProperty("--aia-grid-min","250px"),c.style.setProperty("--aia-grid-max","250px"),c.style.setProperty("--aia-grid-gap","0"),a.appendChild(c),st(a,c),n.appendChild(a)),lt(c,e,t,i,o,r,s),Oe(a,c)}function Oe(n,e){e.scrollHeight-e.scrollTop-e.clientHeight>1?n.setAttribute("data-fade",""):n.removeAttribute("data-fade")}function st(n,e){let t=()=>Oe(n,e),i=new ResizeObserver(t);i.observe(e),e.addEventListener("scroll",t,{passive:!0}),le.set(n,{ro:i,onScroll:t})}function at(n){let e=le.get(n);e&&(e.ro.disconnect(),n.querySelector(".aia-grid")?.removeEventListener("scroll",e.onScroll),le.delete(n))}function lt(n,e,t,i,o,r,s){let a=s?"1":"0";X(n,e,{keyOf:c=>`${c.text}\0${a}`,create:c=>ct(c,s),update:(c,l,p)=>{let d=p===t&&!s;c.id=`${r}-option-${p}`,c.dataset.aiaIndex=String(p),c.setAttribute("aria-selected",String(d)),c.classList.toggle("magicx-aia-option--highlighted",d),!s&&l.is_tappable?(c.onclick=()=>{c.classList.add("magicx-aia-option--pressed"),i(l),setTimeout(()=>c.classList.remove("magicx-aia-option--pressed"),500)},c.onmouseenter=()=>{let g=Number.parseInt(c.dataset.aiaIndex??"-1",10);g>=0&&o(g)}):(c.onclick=null,c.onmouseenter=null)}})}function ct(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 o=document.createElement("div");o.className="magicx-aia-streaks",t.appendChild(o);let r=document.createElement("div");r.className="magicx-aia-streaks-vert",t.appendChild(r);let s=document.createElement("span");s.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,s.appendChild(a),n.tag){let c=document.createElement("span");c.className="magicx-aia-option-tag",c.textContent=n.tag,s.appendChild(c)}return t.appendChild(s),t}var dt=[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 Z(n,e){let{filteredOptions:t,activeIndex:i,isOpen:o,isLoading:r,pills:s,showPills:a,isActivePillSelected:c,onSelect:l,onHighlight:p,onPillClick:d}=e,g=a&&s.length>0,h=t.length>0,x=o&&(h||g||r);if(x?n.classList.add("magicx-aia-dropdown--visible"):n.classList.remove("magicx-aia-dropdown--visible"),r?n.setAttribute("data-aia-loading",""):n.removeAttribute("data-aia-loading"),!x)return;let f=n.querySelector(".aia-stack");f||(f=document.createElement("div"),f.className="aia-stack",f.style.setProperty("--aia-stack-space","8px"),n.appendChild(f));let b=g||r&&a,m=f.querySelector(".magicx-aia-pill-bar");b?(m||(m=document.createElement("div"),m.className="magicx-aia-pill-bar aia-cluster",m.setAttribute("data-nowrap",""),m.setAttribute("data-aia-pillbar",""),f.insertBefore(m,f.firstChild)),Y(m,s,0,d,!0,r,c)):m&&m.remove(),Ie(f,t,i,l,p,e.listboxId,r);let u=f.querySelector(".magicx-aia-skeleton-bars");if(r&&!h){if(!u){u=document.createElement("div"),u.className="magicx-aia-skeleton-bars",u.setAttribute("data-aia-skeleton-bars","");for(let T of dt){let E=document.createElement("span");E.className="magicx-aia-skeleton-bar",E.style.width=`${T}px`,u.appendChild(E)}f.appendChild(u)}}else u&&u.remove();let y=f.querySelector(".magicx-aia-footer")??ut(),v=i>=0&&!!t[i]?.is_tappable;pt(y,z(v,e.isInputEmpty)),f.lastElementChild!==y&&f.appendChild(y)}function pt(n,{key:e,hint:t}){let i=n.querySelector(".magicx-aia-footer-key"),o=n.querySelector(".magicx-aia-footer-hint");!i||!o||(i.textContent!==e&&(i.textContent=e),o.textContent!==t&&(o.textContent=t))}function ut(){let n=document.createElement("footer");n.className="magicx-aia-footer",n.setAttribute("data-aia-footer","");let e=document.createElement("div");e.className="aia-cluster magicx-aia-footer-row",e.setAttribute("data-align","center"),e.setAttribute("data-justify","between"),e.setAttribute("data-nowrap","");let t=document.createElement("div");t.className="aia-cluster magicx-aia-footer-hint-group",t.setAttribute("data-align","center"),t.style.setProperty("--aia-cluster-gap","5px");let i=document.createElement("kbd");i.className="magicx-aia-footer-key",i.textContent="tab";let o=document.createElement("span");o.className="magicx-aia-footer-hint",o.textContent="to select",t.append(i,o);let r=document.createElement("a");r.className="aia-cluster magicx-aia-footer-brand-link",r.setAttribute("data-align","center"),r.href="https://ai-autocomplete.com",r.target="_blank",r.rel="noopener noreferrer",r.style.setProperty("--aia-cluster-gap","2px");let s=document.createElement("span");s.className="magicx-aia-footer-brand",s.textContent="AI";let a=document.createElement("span");return a.className="magicx-aia-footer-badge",a.textContent="Autocomplete",r.append(s,a),e.append(t,r),n.append(e),n}function De(n,e){let t=J(e.listboxId);return n.appendChild(t),{dropdown:t}}function ce(n,e,t){Z(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,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,onSelect:t.selectOption,onHighlight:i=>t.store.set({activeDropdownIndex:i}),onPillClick:t.setActivePill})}function ee(n){let{input:e,segments:t,newParamId:i,editingParamId:o,placeholderText:r,isFocused:s}=n,a=t.length===0;e.dataset.aiaEmpty=a?"true":"false",a&&r?e.dataset.placeholder=r:delete e.dataset.placeholder;let c=t.map(b=>`${b.type}:${b.value}`).join("\0"),l=e.dataset.segKey??"",p=e.dataset.newParamId??"",d=e.dataset.editingParamId??"";if(c===l&&(i??"")===p&&(o??"")===d)return;let g=s?C(e):null;e.dataset.segKey=c,e.dataset.newParamId=i??"",e.dataset.editingParamId=o??"";let h=e.ownerDocument??document,x=h.createDocumentFragment(),f=0;for(let b of t)if(f+=b.value.length,b.type==="completed"){let m=h.createElement("strong");m.dataset.seg="completed",m.dataset.paramId=b.param.id;let u=b.param.id===i,y=b.param.id===o,v=["magicx-aia-segment","magicx-aia-segment--completed"];u&&v.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),y&&v.push("magicx-aia-segment--editing"),m.className=v.join(" "),m.textContent=b.value,x.appendChild(m)}else x.appendChild(h.createTextNode(b.value));e.replaceChildren(x),e.dataset.aiaTextLength=String(f),g!=null&&P(e,Math.max(0,Math.min(g,f)))}var mt='<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 Me(){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=mt,n}function gt(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function ke(n,e){let t=e.firstElementChild;if(!t){e.removeAttribute("data-aia-pill-wrapped");return}let i=t.getBoundingClientRect(),o=n.getBoundingClientRect();i.top>=o.bottom-2?e.setAttribute("data-aia-pill-wrapped",""):e.removeAttribute("data-aia-pill-wrapped")}function Le(n,e){let{listboxId:t}=e,i=J(t);n.appendChild(i);let o=document.createElement("div");o.className="magicx-aia-input-wrapper",n.appendChild(o);let r=document.createElement("div");r.className="magicx-aia-editor",r.setAttribute("data-aia-editor",""),o.appendChild(r);let s=document.createElement("div");s.className="magicx-aia-input",s.setAttribute("data-aia-input",""),s.setAttribute("contenteditable",gt()?"plaintext-only":"true"),s.setAttribute("role","combobox"),s.setAttribute("aria-autocomplete","list"),s.setAttribute("aria-haspopup","listbox"),s.setAttribute("aria-controls",t),s.setAttribute("aria-expanded","false"),s.setAttribute("spellcheck","true"),s.setAttribute("enterkeyhint","send"),r.appendChild(s);let a=document.createElement("span");a.className="magicx-aia-pill-list-container",a.setAttribute("data-aia-pill-list-container",""),r.appendChild(a);let c=null,l=null;e.submitButton===void 0?(c=Me(),o.appendChild(c),l=c):e.submitButton!==null&&(l=e.submitButton,l.hasAttribute("data-aia-submit")||l.setAttribute("data-aia-submit",""),o.appendChild(l));let p=new AbortController,{signal:d}=p,g=!1,h=0,x=()=>{let m=L(s),y=m.length>0&&m[0]!==m[0].toUpperCase()?m[0].toUpperCase()+m.slice(1):m;e.handleChange(y)},f=()=>{let m=(s.ownerDocument??document).getSelection();if(!m||m.rangeCount===0)return null;let u=m.anchorNode;return!u||!s.contains(u)?null:(u.nodeType===Node.ELEMENT_NODE?u:u.parentElement)?.closest('strong[data-seg="completed"][data-param-id]')?.dataset.paramId??null};o.addEventListener("click",m=>{m.target?.closest("[data-aia-pill]")||s.focus()},{signal:d}),s.addEventListener("input",()=>{g||(h=performance.now(),x(),e.handleCaretAfterInput(C(s)))},{signal:d});let b=s.ownerDocument??document;if(b.addEventListener("selectionchange",()=>{let m=b.getSelection();if(!m||m.rangeCount===0||!s.contains(m.anchorNode))return;let u=f(),y=e.store.get().editingParam?.id??null;if(u&&u!==y){e.startEditingParam(u);return}performance.now()-h<50||e.handleCaretMove(C(s))},{signal:d}),s.addEventListener("compositionstart",()=>{g=!0},{signal:d}),s.addEventListener("compositionend",()=>{g=!1,x()},{signal:d}),s.addEventListener("beforeinput",m=>{let u=m,y=u.inputType;if(y==="insertParagraph"||y==="insertLineBreak"||y==="insertFromDrop"){m.preventDefault();return}if(y.startsWith("insert")||y.startsWith("delete")){let v=y.startsWith("delete")?"":u.data??"";e.replaceEditingRange(v)&&m.preventDefault()}},{signal:d}),s.addEventListener("paste",m=>{m.preventDefault();let u=(m.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!u)return;let y=s.ownerDocument??document,v=y.getSelection();if(!v||v.rangeCount===0)return;let T=v.getRangeAt(0);if(!s.contains(T.startContainer))return;T.deleteContents();let E=y.createTextNode(u);T.insertNode(E),T.setStartAfter(E),T.collapse(!0),v.removeAllRanges(),v.addRange(T),x()},{signal:d}),s.addEventListener("keydown",m=>e.handleKeyDown(m),{signal:d}),s.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:d}),s.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:d}),l&&l.addEventListener("click",m=>{let u=e.store.get();if(!(!!u.text||u.completedParams.length>0)||!e.onSubmit)return;m.stopPropagation();let{rawQuery:v,completedParams:T}=S(u.text,u.completedParams);e.onSubmit({query:u.text.trim(),raw_query:v,completed_params:T}),e.afterSubmit?.()},{signal:d}),e.autoFocus!==!1){s.focus();let m=s.ownerDocument??document,u=m.getSelection(),y=u&&u.rangeCount>0&&s.contains(u.anchorNode);if(u&&!y){let v=m.createRange();v.selectNodeContents(s),v.collapse(!0),u.removeAllRanges(),u.addRange(v)}}if(typeof ResizeObserver<"u"){let m=new ResizeObserver(()=>ke(s,a));m.observe(s),p.signal.addEventListener("abort",()=>m.disconnect(),{once:!0})}return{input:s,inlinePillContainer:a,dropdown:i,submitButton:c,abort:p}}function de(n,e,t){let{input:i,inlinePillContainer:o,dropdown:r,submitButton:s}=n,{pillPlacement:a,setActivePill:c,selectOption:l,store:p}=t;i.setAttribute("aria-expanded",String(e.isDropdownOpen));let d=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(d?i.setAttribute("aria-activedescendant",d):i.removeAttribute("aria-activedescendant"),s){let b=!!e.text||e.completedParams.length>0;s.disabled=!b}let g=i.dataset.newParamId??"",h=e.newParamId!==null&&e.newParamId!==g;if(ee({input:i,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused}),a==="inline"){let b=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;b||e.actionableSuggestions.length>0?Y(o,e.actionableSuggestions,0,c,!1,b,e.isActivePillSelected):ae(o)}else ae(o);ke(i,o),h?(i.focus(),P(i,e.caretOffset??e.text.length)):e.isFocused&&L(i)!==e.text&&P(i,e.text.length);let x=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:null,f=x??e.actionableSuggestions[0];Z(r,{suggestions:f?[{...f,options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation,listboxId:t.listboxId,pills:x?[x]:e.actionableSuggestions,showPills:a==="dropdown",isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,onSelect:l,onHighlight:b=>p.set({activeDropdownIndex:b}),onPillClick:c})}function Re(n,e){let t=n.actionableSuggestions[0];if(!t)return null;let i=n.filterBase,o=n.text.slice(0,i),r=o.length===0&&n.text.length===0,s=o.length===0&&n.text.length>0&&n.placeholderText.length>0&&n.placeholderText.toLowerCase().startsWith(n.text.toLowerCase());(r||s)&&n.placeholderText&&(o=`${n.placeholderText} `);let a=he(o,e.text);a>0&&(o=o.slice(0,o.length-a));let c=o.length>0&&o[o.length-1]!==" ",l=`${o}${c?" ":""}${e.text} `,p=(r||s)&&l.length>0?l[0].toUpperCase()+l.slice(1):l,d=p.toLowerCase().lastIndexOf(e.text.toLowerCase()),g=d>=0?p.slice(d,d+e.text.length):e.text,h={id:crypto.randomUUID(),placeholder:"",type:t.type,text:g,kind:e.kind,suggestionType:t.type,suggestionPlaceholder:t.text,options:t.options??[],metadata:e.metadata},x=n.actionableSuggestions.length-1;return{patch:{text:p,filterBase:p.length,completedParams:[...n.completedParams,h],newParamId:h.id,caretOffset:p.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:x>0,inSelectionAnimation:!0},telemetry:{selectedOption:e.text,otherOptions:n.filteredOptions.filter(f=>f.text!==e.text).map(f=>f.text)},consumedSuggestion:t,remainingActionable:x}}function te(n){let e=n,t=new Set;return{get:()=>e,set:i=>{let o=typeof i=="function"?i(e):i,r={...e,...o},s=e;e=r;for(let a of t)a(r,s)},subscribe:i=>(t.add(i),()=>{t.delete(i)})}}function Ne(n,e){let t,i,o=r=>(r!==t&&(t=r,i=e(r)),i);return{get:()=>{let r=n.get();return{...r,...o(r)}},set:r=>{typeof r=="function"?n.set(s=>{let a={...s,...o(s)};return r(a)}):n.set(r)},peek:r=>{let s={...n.get(),...r};return{...s,...e(s)}},subscribe:r=>n.subscribe((s,a)=>{let c={...a,...o(a)},l={...s,...o(s)};r(l,c)})}}var pe=!1;function _e(){if(pe||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){pe=!0;return}pe=!0;let n=document.createElement("style");n.setAttribute("data-magicx-aia",""),n.textContent=ft,document.head.appendChild(n)}var ft=`@layer layout {
1
+ "use strict";var re=Object.defineProperty;var qe=Object.getOwnPropertyDescriptor;var Qe=Object.getOwnPropertyNames;var $e=Object.prototype.hasOwnProperty;var Ue=(n,e)=>{for(var t in e)re(n,t,{get:e[t],enumerable:!0})},Ge=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Qe(e))!$e.call(n,o)&&o!==t&&re(n,o,{get:()=>e[o],enumerable:!(i=qe(e,o))||i.enumerable});return n};var We=n=>Ge(re({},"__esModule",{value:!0}),n);var Tt={};Ue(Tt,{AIAutocomplete:()=>oe,ModeController:()=>M,buildQuery:()=>S,createStore:()=>te,cursorIsAtEnd:()=>$,extractPlainText:()=>L,getCursorOffset:()=>C,getFooterHint:()=>z,plainTextLength:()=>Q,previousGraphemeBoundary:()=>U,renderEditableContent:()=>ee,setCursorOffset:()=>P});module.exports=We(Tt);var R=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 je="https://api.ai-autocomplete.com",N=`${je}/api/suggest`,ue=new WeakMap;function k(n){return n?.type==="accessToken"}function Ve(n){if(!(!n||k(n)))return n}function _(n){let e=ue.get(n.getAccessToken);return e||(e=new R(n),ue.set(n.getAccessToken,e)),e}function H(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function F(n){let e=Ve(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}var ze="0.5.3",me=!1;function Xe(){return crypto.randomUUID()}function Ye(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.text},kind:n.kind}}function Je(n,e,t,i){let o=e.find(s=>s.type==="contact"&&s.metadata?.contact_account_count)?.metadata?.contact_account_count,r=typeof o=="number"?o:void 0;return{data:{raw_query:n,completed_params:e.map(s=>Ye(s,t)),...r!=null&&{contact_account_count:r}},meta:{request_id:Xe(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:ze,session_id:i}}}async function ge(n,e,t,i,o){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:o})}async function fe(n,e,t){let i=t.apiConfig,o=!t.maskCompletedText,r=Je(n,e,o,t.sessionId),s=H(i),a=i?.endpoint??N,c=JSON.stringify(r);if(k(i)){let d=_(i),g=await d.getToken(),h=await ge(a,s,g,c,t.signal);if(h.status===401){let x=await d.getToken(!0);h=await ge(a,s,x,c,t.signal)}if(!h.ok)throw new Error(`API error: ${h.status} ${h.statusText}`);return h.json()}let l=F(i);!l&&!me&&(me=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),l&&(s.Authorization=l);let p=await fetch(a,{method:"POST",headers:s,body:c,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={},o=[];for(let r of e){let s=(i[r.type]??0)+1;i[r.type]=s;let c=`{{${r.type.toUpperCase().replace(/\s+/g,"_")}_${s}}}`,l=t.indexOf(r.text);l!==-1&&(t=t.slice(0,l)+c+t.slice(l+r.text.length)),o.push({...r,placeholder:c})}return{rawQuery:t,completedParams:o}}function I(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 o=i.indexOf(" ");return o===-1?"":i.slice(o+1)}function he(n,e){let t=n.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let i=t.split(" "),o=e.toLowerCase();for(let r=0;r<i.length;r++){let s=i.slice(r).join(" ");if(o.startsWith(s.toLowerCase())){let a=t.length-s.length;return n.length-a}}return 0}function A(n,e){if(!n)return[];let t=e.trimStart();if(!t)return n;let i=t.toLowerCase();return n.filter(o=>!o.is_tappable||o.text.toLowerCase().includes(i))}function O(n,e){if(!n)return null;let t=e.trim();if(!t)return null;let i=t.toLowerCase();return n.find(o=>o.is_tappable&&o.text.toLowerCase()===i)??null}function xe(n,e){return e?n.map(t=>{let i=e[t.type];if(!i)return t;let o=i("");if(o.length===0)return t;let r=new Set(o.map(a=>a.text)),s=(t.options??[]).filter(a=>!r.has(a.text));return{...t,options:[...o,...s]}}):n}var Ze=100,et=300,tt=2,B=class{constructor(e,t,i,o,r,s,a={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=o;this.getOnError=r;this.getSessionId=s;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 o=++this.fetchVersion,r=this.store.get().text.length;this.store.set({isLoading:!0,error:null});try{let s=await fe(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig()});if(o!==this.fetchVersion)return;let a=xe(s.data.suggestions??[],this.getOptionOverrides()),c=s.data.input??[],l=c[c.length-1],p=this.store.get().text,d,g;if(l?.state==="in_progress"){g=!0;let b=p.toLowerCase().lastIndexOf(l.text.toLowerCase());d=b!==-1?b:r}else g=!1,d=r;let x=a.filter(b=>b.type!=="placeholder")[0],f=null;if(x){let b=w(p,d,g),m=O(x.options,b);m&&(f={id:crypto.randomUUID(),placeholder:"",type:x.type,text:m.text,kind:m.kind,suggestionType:x.type,suggestionPlaceholder:x.text,options:x.options??[],metadata:m.metadata},a=a.filter(u=>u!==x),this.callbacks.onAutoMatch?.({active:x,matched:m,rawQuery:e}))}this.store.set(b=>({suggestions:a,isLoading:!1,isReady:s.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:d,filterInProgress:g,...f?{completedParams:[...b.completedParams,f]}:{}}))}catch(s){if(o===this.fetchVersion){let a=s instanceof Error?s:new Error(String(s));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 o=this.store.get();if(!o.text&&o.completedParams.length===0)return this.doFetch("",[]),!0;let r=o.suggestions.filter(u=>u.type==="placeholder").map(u=>u.text).join(" "),s=I(o.text,o.filterBase,r),a=w(o.text,s,o.filterInProgress),l=o.suggestions.filter(u=>u.type!=="placeholder")[0],d=(l?A(l.options,a):[]).filter(u=>u.is_tappable),g=l?O(l.options,a)!==null:!1,h=a.trim().length>0;if(d.length>0&&!g&&h||o.completedParams.length===0&&o.text.length>0&&r.length>0&&r.toLowerCase().startsWith(o.text.toLowerCase()))return!1;let{rawQuery:x,completedParams:f}=S(o.text,o.completedParams),b=x.length<o.lastRawQuery.length,m=Math.abs(x.length-o.lastRawQuery.length);return b||m>=i?(this.doFetch(x,f),!0):!1};this.debounceTimer=setTimeout(()=>{t(tt)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},Ze),this.slowDebounceTimer=setTimeout(()=>t(1),et)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var ye='[contenteditable="false"]',D;function nt(){if(D!==void 0)return D;let n=globalThis.Intl.Segmenter;if(!n)return D=null,null;try{D=new n(void 0,{granularity:"grapheme"})}catch{D=null}return D??null}function K(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(ye))return!0;t=t.parentNode}return!1}function q(n){return(n.ownerDocument??document).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return K(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function L(n){let e=q(n),t="",i=e.nextNode();for(;i;)t+=i.data,i=e.nextNode();return t}function Q(n){let e=q(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 o=t;if(K(o,n)&&o!==n)return null;let r=0;for(let s=0;s<i&&s<o.childNodes.length;s++)r+=ve(o.childNodes[s],n);return r+be(o,n)}return t.nodeType!==Node.TEXT_NODE||K(t,n)?null:be(t,n)+i}function ve(n,e){if(n.nodeType===Node.TEXT_NODE)return K(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(ye))return 0;let i=0;for(let o of Array.from(t.childNodes))i+=ve(o,e);return i}function be(n,e){let t=q(e),i=0,o=t.nextNode();for(;o;){if(o===n||n.nodeType===Node.ELEMENT_NODE&&n.contains(o))return i;i+=o.data.length,o=t.nextNode()}return i}function P(n,e){let t=n.ownerDocument??document,i=t.getSelection();if(!i)return;let o=Math.max(0,Math.min(e,Q(n))),r=q(n),s=0,a=null,c=0,l=r.nextNode(),p=null;for(;l;){let g=l.data.length;if(o<s+g){a=l,c=o-s;break}if(o===s+g){let h=r.nextNode();h?(a=h,c=0):(a=l,c=g);break}s+=g,p=l,l=r.nextNode()}let d=t.createRange();if(a){let g=a.parentElement?.closest('strong[data-seg="completed"]');g&&g!==n&&n.contains(g)?c===0?d.setStartBefore(g):c===a.data.length?d.setStartAfter(g):d.setStart(a,c):d.setStart(a,c)}else p?d.setStart(p,p.data.length):d.setStart(n,0);d.collapse(!0),i.removeAllRanges(),i.addRange(d)}function $(n){let e=C(n);return e==null?!1:e>=Q(n)}function U(n,e){if(e<=0)return 0;let t=nt();if(!t)return e-1;let i=n.slice(0,e),o=0;for(let{index:r}of t.segment(i))r<e&&(o=r);return o}function se(n,e){return n instanceof HTMLTextAreaElement||n instanceof HTMLInputElement?n.selectionStart!=null&&n.selectionStart===n.value.length:n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?$(n):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function it(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?C(n):null}var G=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:o}=this.ctx,r=this.getEffectiveColumns(),s=o(),a=this.getTappableIndices(r);if((e.shiftKey||e.metaKey||e.ctrlKey||e.altKey)&&(e.key==="ArrowDown"||e.key==="ArrowUp"||e.key==="ArrowLeft"||e.key==="ArrowRight"))return;let c=this.ctx.getOptionsPosition()==="above";switch(e.key){case"ArrowDown":{let l=se(e.target,t),p=!!t.editingParam;if(!l&&!p&&t.activeDropdownIndex<0)break;if(t.activeDropdownIndex<0){if(c)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 h=Math.floor((t.filteredOptions.length-1)/r);if(Math.floor(t.activeDropdownIndex/r)===h){this.store.set({activeDropdownIndex:-1});break}}let d=a.indexOf(t.activeDropdownIndex),g=d<a.length-1?d+1:0;this.store.set({activeDropdownIndex:a[g]});break}case"ArrowUp":{if(t.activeDropdownIndex<0){if(!c)break;let d=se(e.target,t),g=!!t.editingParam;if(!d&&!g)break;e.preventDefault();let h=this.firstTappableInBottomRow(r)??a[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:h});break}if(a.length===0)return;this.store.set({activeDropdownIndex:h});break}if(a.length===0)break;if(e.preventDefault(),t.activeDropdownIndex<r){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%r<r-1){let d=t.activeDropdownIndex+1;d<t.filteredOptions.length&&t.filteredOptions[d]?.is_tappable&&this.store.set({activeDropdownIndex:d})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let p=e.target.closest("[data-aia-input]")??e.target,d=t.editingTail;this.ctx.exitEditMode?.(),P(p,d);break}se(e.target,t)&&t.actionableSuggestions.length>=1&&(e.preventDefault(),this.removeActivePill());break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%r>0){let l=t.activeDropdownIndex-1;l>=0&&t.filteredOptions[l]?.is_tappable&&this.store.set({activeDropdownIndex:l})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let l=e.target.closest("[data-aia-input]")??e.target,p=t.editingAnchor;this.ctx.exitEditMode?.(),P(l,p);break}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let l=it(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(s){let{rawQuery:l,completedParams:p}=S(t.text,t.completedParams);s({query:t.text.trim(),raw_query:l,completed_params:p}),this.ctx.afterSubmit?.()}break}case"Tab":{let l=t.filteredOptions.map((g,h)=>g.is_tappable?h:-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});break}e.preventDefault();let p=l.indexOf(t.activeDropdownIndex),d;if(p<0)d=e.shiftKey?l.length-1:0;else{let g=e.shiftKey?-1:1;d=(p+g+l.length)%l.length}this.store.set({activeDropdownIndex:l[d]});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?.(),P(l,p)}this.store.set({activeDropdownIndex:-1});break}}}firstTappableInBottomRow(e){let t=this.store.get();if(t.filteredOptions.length===0)return null;let o=Math.floor((t.filteredOptions.length-1)/e)*e;for(let r=o;r<t.filteredOptions.length;r++)if(t.filteredOptions[r]?.is_tappable)return r;return null}getTappableIndices(e){let i=this.store.get().filteredOptions.map((r,s)=>r.is_tappable?s:-1).filter(r=>r!==-1),o=Array.from({length:e},()=>[]);for(let r of i)o[r%e].push(r);return o.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 o=getComputedStyle(i).gridTemplateColumns;if(o&&o!=="none"){let r=o.split(" ").filter(Boolean).length;if(r>0)return r}if(i===e)break;i=i.parentElement}return this.ctx.columns}clickOrSelect(e,t,i){let o=document.getElementById(`${i}-option-${e}`);o?o.click():this.ctx.selectOption(t[e])}removeActivePill(){let e=this.store.get(),t=e.suggestions.filter(r=>r.type==="placeholder"),i=e.suggestions.filter(r=>r.type!=="placeholder");if(i.length===0)return;let o=i.slice(1);this.store.set({suggestions:[...t,...o],pillTapped:o.length>0,activeDropdownIndex:-1})}};var W=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),i=t.suggestions.filter(l=>l.type!=="placeholder");if(e<0||e>=i.length)return;let o=i[e],r=i.filter((l,p)=>p!==e),s=t.suggestions.filter(l=>l.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:l}=S(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:l,selectedPill:o.text,otherPills:r.map(p=>p.text)})}let a=[...s,o,...r],c=this.store.peek({suggestions:a}).filteredOptions.findIndex(l=>l.is_tappable);this.store.set({suggestions:a,pillTapped:!0,activeDropdownIndex:c})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};function Se(n,e){let t=[],i=0;for(let r of e){let s=n.indexOf(r.text,i);s!==-1&&(s>i&&t.push({type:"text",value:n.slice(i,s)}),t.push({type:"completed",value:r.text,param:r}),i=s+r.text.length)}let o=n.slice(i);return o&&t.push({type:"text",value:o}),t}function Pe(n,e){let t=[],i=[],o=0;for(let r of e){let s=n.indexOf(r.text,o);s===-1?i.push(r):(t.push(r),o=s+r.text.length)}return{valid:t,invalid:i}}function Te(n,e){let t=e.dropdownTrigger??"auto",i=e.closeDropdownOnBlur??!0,r=n.filteredOptionsLength>0||n.activePillHasNoOptions;if(n.inEditMode){let s=i?n.isFocused:!0;return r&&s}if(t==="auto"){let s=i?n.isFocused:!0,a=n.text.replace(/\s+$/,"").length,c=n.caretOffset==null||n.caretOffset>=a;return(r||n.isLoading)&&s&&c}return t==="manual"?(r||n.isLoading)&&n.pillTapped:!1}function Ce(n,e){let t=Se(n.text,n.completedParams),i=n.suggestions.filter(u=>u.type!=="placeholder"),o=i[0],r=o?e.optionOverrides?.[o.type]:void 0,s=n.suggestions.filter(u=>u.type==="placeholder").map(u=>u.text).join(" "),a=I(n.text,Math.min(n.filterBase,n.text.length),s),l=n.lastRawQuery!==""||a>0?w(n.text,a,n.filterInProgress):"",p=o?r?r(l.trim()):o.options??[]:[],d=n.editingParam!=null&&n.editingAnchor!=null,g;if(d&&n.editingParam&&n.editingAnchor!=null){let u=n.editingParam.id,y=n.completedParams.some(E=>E.id===u),v=n.caretOffset??n.editingAnchor,T=y?"":n.text.slice(n.editingAnchor,v);g=A(n.editingParam.options,T)}else g=A(p,l);let h=e.showNonTappableOptions===!1;h&&(g=g.filter(u=>u.is_tappable));let x=u=>h?u.is_tappable:!0,f;if(d){let u=n.editingParam?.options??[];f=n.editingParam!=null&&u.filter(x).length===0}else{let u=o?r?r(""):o.options??[]:[];f=o!=null&&u.filter(x).length===0}let b=Te({inEditMode:d,filteredOptionsLength:g.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading,pillTapped:n.pillTapped,activePillHasNoOptions:f},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),m=b&&n.activeDropdownIndex>=0&&!!g[n.activeDropdownIndex]?.is_tappable;return{segments:t,actionableSuggestions:i,filteredOptions:g,placeholderText:s,isDropdownOpen:b,isActivePillSelected:m}}function j(n){return n.mode==="fresh"?ot(n):rt(n)}function ot(n){let{text:e,completedParams:t,suggestions:i,filterBase:o,filterInProgress:r}=n,a=i.filter(v=>v.type!=="placeholder")[0];if(!a?.options)return null;let c=i.filter(v=>v.type==="placeholder").map(v=>v.text).join(" "),l=I(e,o,c),p=w(e,l,r),d=O(a.options,p);if(!d)return null;let g=d.text.toLowerCase(),h=e.toLowerCase().lastIndexOf(g),x=h>=0?h:Math.max(0,e.length-d.text.length),f=x+d.text.length,b=e.slice(x,f),u=f<e.length&&e[f]===" "?f+1:f,y={id:crypto.randomUUID(),placeholder:"",type:a.type,text:b,kind:d.kind,suggestionType:a.type,suggestionPlaceholder:a.text,options:a.options??[],metadata:d.metadata};return{patch:{text:e,completedParams:[...t,y],suggestions:i.filter(v=>v!==a),filterBase:u,newParamId:y.id,caretOffset:u,activeDropdownIndex:-1},caretPos:u}}function rt(n){let{text:e,completedParams:t,editingParam:i,editingAnchor:o,editingTail:r}=n;if(t.some(y=>y.id===i.id))return null;let s=e.slice(o,r),a=O(i.options,s);if(!a)return null;let c=a.text.toLowerCase(),l=s.toLowerCase().lastIndexOf(c),p=o+Math.max(0,l),d=p+a.text.length,g=e.slice(p,d),x=d<e.length&&e[d]===" "?d+1:d,f={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:g,kind:a.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:a.metadata},b=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>=x){b=y;break}m=v+t[y].text.length}}let u=[...t];return u.splice(b,0,f),{patch:{text:e,completedParams:u,newParamId:f.id,filterBase:x,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:x,activeDropdownIndex:-1},caretPos:x}}var V=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(s=>s.id===e);if(!i)return;let o=0,r=-1;for(let s of t.completedParams){let a=t.text.indexOf(s.text,o);if(a!==-1){if(s.id===e){r=a;break}o=a+s.text.length}}r<0||this.deps.store.set({editingParam:i,editingAnchor:r,editingTail:r+i.text.length,caretOffset:r+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,o=t.editingAnchor,r=t.editingTail;if(!i||o==null||r==null||!t.completedParams.some(c=>c.id===i.id))return!1;let s=t.text.slice(0,o)+e+t.text.slice(r),a=o+e.length;return this.deps.store.set(c=>({text:s,completedParams:c.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,o=t.editingAnchor,r=t.editingTail;if(!i||o==null||r==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 s=t.text.slice(0,o),a=t.text.slice(r),c=o===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,l=a.length===0||a[0]!==" ",p=l?`${c} `:c,d=s+p+a,g=o+p.length+(l?0:1),h={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:c,kind:e.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:e.metadata},x=t.completedParams.findIndex(m=>m.id===i.id),f=t.completedParams.filter(m=>m.id!==i.id),b=x>=0?Math.min(x,f.length):f.length;f.splice(b,0,h),this.deps.store.set({text:d,completedParams:f,newParamId:h.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=j({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 z(n,e){return n?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}var Ee="data-aia-key";function X(n,e,t){let i=new Map;for(let s of Array.from(n.children)){let a=s.getAttribute(Ee);a!=null&&i.set(a,s)}let o=new Set,r=[];for(let s=0;s<e.length;s++){let a=e[s],c=t.keyOf(a,s);o.add(c);let l=i.get(c);l||(l=t.create(a,s),l.setAttribute(Ee,c)),t.update?.(l,a,s),n.children[s]!==l&&n.insertBefore(l,n.children[s]??null),r.push(l)}for(let[s,a]of i)o.has(s)||a.remove();return r}var we=[125,69];function Ae(n,e){return e?1:n===0?.7:n===1?.4:.2}function Y(n,e,t,i,o=!1,r=!1,s=!1){let a=n.querySelector(".magicx-aia-pill-list");if(a||(a=document.createElement("span"),a.className="magicx-aia-pill-list",n.appendChild(a)),r&&e.length===0){a.setAttribute("data-aia-pill-list-loading",""),a.innerHTML="";for(let c=0;c<we.length;c++){let l=we[c],p=document.createElement("span");p.setAttribute("data-aia-pill-skeleton",""),p.className=`magicx-aia-pill magicx-aia-pill--skeleton${o?" magicx-aia-pill--rounded":""}`,p.style.width=`${l}px`,p.style.opacity=String(Ae(c,!1)),a.appendChild(p)}return}r?a.setAttribute("data-aia-pill-list-loading",""):a.removeAttribute("data-aia-pill-list-loading");for(let c of a.querySelectorAll("[data-aia-pill-skeleton]"))c.remove();X(a,e,{keyOf:c=>`${c.type}-${c.text}`,create:c=>{let l=document.createElement("button");return l.type="button",l.tabIndex=-1,l.setAttribute("data-aia-pill",""),l.setAttribute("contenteditable","false"),l.textContent=c.text,l.addEventListener("mousedown",p=>p.preventDefault()),l},update:(c,l,p)=>{let d=c,g=s&&p===t&&!r,h=["magicx-aia-pill"];o&&h.push("magicx-aia-pill--rounded"),r&&h.push("magicx-aia-pill--skeleton"),d.className=h.join(" "),d.style.width="",d.style.opacity=String(Ae(p,g)),r?(d.setAttribute("data-aia-loading",""),d.disabled=!0,d.onclick=null):(d.removeAttribute("data-aia-loading"),d.disabled=!1,d.onclick=()=>i(p))}})}function ae(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var le=new WeakMap;function Ie(n,e,t,i,o,r,s){let a=n.querySelector(".aia-grid-fade");if(e.length===0){a&&(at(a),a.remove());return}let c=a?.querySelector(".aia-grid")??null;(!a||!c)&&(a=document.createElement("div"),a.className="aia-grid-fade",c=document.createElement("div"),c.className="aia-grid magicx-aia-grid",c.setAttribute("data-scroll",""),c.style.setProperty("--aia-grid-min","250px"),c.style.setProperty("--aia-grid-max","250px"),c.style.setProperty("--aia-grid-gap","0"),a.appendChild(c),st(a,c),n.appendChild(a)),lt(c,e,t,i,o,r,s),Oe(a,c)}function Oe(n,e){e.scrollHeight-e.scrollTop-e.clientHeight>1?n.setAttribute("data-fade",""):n.removeAttribute("data-fade")}function st(n,e){let t=()=>Oe(n,e),i=new ResizeObserver(t);i.observe(e),e.addEventListener("scroll",t,{passive:!0}),le.set(n,{ro:i,onScroll:t})}function at(n){let e=le.get(n);e&&(e.ro.disconnect(),n.querySelector(".aia-grid")?.removeEventListener("scroll",e.onScroll),le.delete(n))}function lt(n,e,t,i,o,r,s){let a=s?"1":"0";X(n,e,{keyOf:c=>`${c.text}\0${a}`,create:c=>ct(c,s),update:(c,l,p)=>{let d=p===t&&!s;c.id=`${r}-option-${p}`,c.dataset.aiaIndex=String(p),c.setAttribute("aria-selected",String(d)),c.classList.toggle("magicx-aia-option--highlighted",d),!s&&l.is_tappable?(c.onclick=()=>{c.classList.add("magicx-aia-option--pressed"),i(l),setTimeout(()=>c.classList.remove("magicx-aia-option--pressed"),500)},c.onmouseenter=()=>{let g=Number.parseInt(c.dataset.aiaIndex??"-1",10);g>=0&&o(g)}):(c.onclick=null,c.onmouseenter=null)}})}function ct(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 o=document.createElement("div");o.className="magicx-aia-streaks",t.appendChild(o);let r=document.createElement("div");r.className="magicx-aia-streaks-vert",t.appendChild(r);let s=document.createElement("span");s.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,s.appendChild(a),n.tag){let c=document.createElement("span");c.className="magicx-aia-option-tag",c.textContent=n.tag,s.appendChild(c)}return t.appendChild(s),t}var dt=[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 Z(n,e){let{filteredOptions:t,activeIndex:i,isOpen:o,isLoading:r,pills:s,showPills:a,isActivePillSelected:c,onSelect:l,onHighlight:p,onPillClick:d}=e,g=a&&s.length>0,h=t.length>0,x=o&&(h||g||r);if(x?n.classList.add("magicx-aia-dropdown--visible"):n.classList.remove("magicx-aia-dropdown--visible"),r?n.setAttribute("data-aia-loading",""):n.removeAttribute("data-aia-loading"),!x)return;let f=n.querySelector(".aia-stack");f||(f=document.createElement("div"),f.className="aia-stack",f.style.setProperty("--aia-stack-space","8px"),n.appendChild(f));let b=g||r&&a,m=f.querySelector(".magicx-aia-pill-bar");b?(m||(m=document.createElement("div"),m.className="magicx-aia-pill-bar aia-cluster",m.setAttribute("data-nowrap",""),m.setAttribute("data-aia-pillbar",""),f.insertBefore(m,f.firstChild)),Y(m,s,0,d,!0,r,c)):m&&m.remove(),Ie(f,t,i,l,p,e.listboxId,r);let u=f.querySelector(".magicx-aia-skeleton-bars");if(r&&!h){if(!u){u=document.createElement("div"),u.className="magicx-aia-skeleton-bars",u.setAttribute("data-aia-skeleton-bars","");for(let T of dt){let E=document.createElement("span");E.className="magicx-aia-skeleton-bar",E.style.width=`${T}px`,u.appendChild(E)}f.appendChild(u)}}else u&&u.remove();let y=f.querySelector(".magicx-aia-footer")??ut(),v=i>=0&&!!t[i]?.is_tappable;pt(y,z(v,e.isInputEmpty)),f.lastElementChild!==y&&f.appendChild(y)}function pt(n,{key:e,hint:t}){let i=n.querySelector(".magicx-aia-footer-key"),o=n.querySelector(".magicx-aia-footer-hint");!i||!o||(i.textContent!==e&&(i.textContent=e),o.textContent!==t&&(o.textContent=t))}function ut(){let n=document.createElement("footer");n.className="magicx-aia-footer",n.setAttribute("data-aia-footer","");let e=document.createElement("div");e.className="aia-cluster magicx-aia-footer-row",e.setAttribute("data-align","center"),e.setAttribute("data-justify","between"),e.setAttribute("data-nowrap","");let t=document.createElement("div");t.className="aia-cluster magicx-aia-footer-hint-group",t.setAttribute("data-align","center"),t.style.setProperty("--aia-cluster-gap","5px");let i=document.createElement("kbd");i.className="magicx-aia-footer-key",i.textContent="tab";let o=document.createElement("span");o.className="magicx-aia-footer-hint",o.textContent="to select",t.append(i,o);let r=document.createElement("a");r.className="aia-cluster magicx-aia-footer-brand-link",r.setAttribute("data-align","center"),r.href="https://ai-autocomplete.com",r.target="_blank",r.rel="noopener noreferrer",r.style.setProperty("--aia-cluster-gap","2px");let s=document.createElement("span");s.className="magicx-aia-footer-brand",s.textContent="AI";let a=document.createElement("span");return a.className="magicx-aia-footer-badge",a.textContent="Autocomplete",r.append(s,a),e.append(t,r),n.append(e),n}function De(n,e){let t=J(e.listboxId);return n.appendChild(t),{dropdown:t}}function ce(n,e,t){Z(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,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,onSelect:t.selectOption,onHighlight:i=>t.store.set({activeDropdownIndex:i}),onPillClick:t.setActivePill})}function ee(n){let{input:e,segments:t,newParamId:i,editingParamId:o,placeholderText:r,isFocused:s}=n,a=t.length===0;e.dataset.aiaEmpty=a?"true":"false",a&&r?e.dataset.placeholder=r:delete e.dataset.placeholder;let c=t.map(b=>`${b.type}:${b.value}`).join("\0"),l=e.dataset.segKey??"",p=e.dataset.newParamId??"",d=e.dataset.editingParamId??"";if(c===l&&(i??"")===p&&(o??"")===d)return;let g=s?C(e):null;e.dataset.segKey=c,e.dataset.newParamId=i??"",e.dataset.editingParamId=o??"";let h=e.ownerDocument??document,x=h.createDocumentFragment(),f=0;for(let b of t)if(f+=b.value.length,b.type==="completed"){let m=h.createElement("strong");m.dataset.seg="completed",m.dataset.paramId=b.param.id;let u=b.param.id===i,y=b.param.id===o,v=["magicx-aia-segment","magicx-aia-segment--completed"];u&&v.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),y&&v.push("magicx-aia-segment--editing"),m.className=v.join(" "),m.textContent=b.value,x.appendChild(m)}else x.appendChild(h.createTextNode(b.value));e.replaceChildren(x),e.dataset.aiaTextLength=String(f),g!=null&&P(e,Math.max(0,Math.min(g,f)))}var mt='<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 Me(){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=mt,n}function gt(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function ke(n,e){let t=e.firstElementChild;if(!t){e.removeAttribute("data-aia-pill-wrapped");return}let i=t.getBoundingClientRect(),o=n.getBoundingClientRect();i.top>=o.bottom-2?e.setAttribute("data-aia-pill-wrapped",""):e.removeAttribute("data-aia-pill-wrapped")}function Le(n,e){let{listboxId:t}=e,i=J(t);n.appendChild(i);let o=document.createElement("div");o.className="magicx-aia-input-wrapper",n.appendChild(o);let r=document.createElement("div");r.className="magicx-aia-editor",r.setAttribute("data-aia-editor",""),o.appendChild(r);let s=document.createElement("div");s.className="magicx-aia-input",s.setAttribute("data-aia-input",""),s.setAttribute("contenteditable",gt()?"plaintext-only":"true"),s.setAttribute("role","combobox"),s.setAttribute("aria-autocomplete","list"),s.setAttribute("aria-haspopup","listbox"),s.setAttribute("aria-controls",t),s.setAttribute("aria-expanded","false"),s.setAttribute("spellcheck","true"),s.setAttribute("enterkeyhint","send"),r.appendChild(s);let a=document.createElement("span");a.className="magicx-aia-pill-list-container",a.setAttribute("data-aia-pill-list-container",""),r.appendChild(a);let c=null,l=null;e.submitButton===void 0?(c=Me(),o.appendChild(c),l=c):e.submitButton!==null&&(l=e.submitButton,l.hasAttribute("data-aia-submit")||l.setAttribute("data-aia-submit",""),o.appendChild(l));let p=new AbortController,{signal:d}=p,g=!1,h=0,x=()=>{let m=L(s),y=m.length>0&&m[0]!==m[0].toUpperCase()?m[0].toUpperCase()+m.slice(1):m;e.handleChange(y)},f=()=>{let m=(s.ownerDocument??document).getSelection();if(!m||m.rangeCount===0)return null;let u=m.anchorNode;return!u||!s.contains(u)?null:(u.nodeType===Node.ELEMENT_NODE?u:u.parentElement)?.closest('strong[data-seg="completed"][data-param-id]')?.dataset.paramId??null};o.addEventListener("click",m=>{m.target?.closest("[data-aia-pill]")||s.focus()},{signal:d}),s.addEventListener("input",()=>{g||(h=performance.now(),x(),e.handleCaretAfterInput(C(s)))},{signal:d});let b=s.ownerDocument??document;if(b.addEventListener("selectionchange",()=>{let m=b.getSelection();if(!m||m.rangeCount===0||!s.contains(m.anchorNode))return;let u=f(),y=e.store.get().editingParam?.id??null;if(u&&u!==y){e.startEditingParam(u);return}performance.now()-h<50||e.handleCaretMove(C(s))},{signal:d}),s.addEventListener("compositionstart",()=>{g=!0},{signal:d}),s.addEventListener("compositionend",()=>{g=!1,x()},{signal:d}),s.addEventListener("beforeinput",m=>{let u=m,y=u.inputType;if(y==="insertParagraph"||y==="insertLineBreak"||y==="insertFromDrop"){m.preventDefault();return}if(y.startsWith("insert")||y.startsWith("delete")){let v=y.startsWith("delete")?"":u.data??"";e.replaceEditingRange(v)&&m.preventDefault()}},{signal:d}),s.addEventListener("paste",m=>{m.preventDefault();let u=(m.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!u)return;let y=s.ownerDocument??document,v=y.getSelection();if(!v||v.rangeCount===0)return;let T=v.getRangeAt(0);if(!s.contains(T.startContainer))return;T.deleteContents();let E=y.createTextNode(u);T.insertNode(E),T.setStartAfter(E),T.collapse(!0),v.removeAllRanges(),v.addRange(T),x()},{signal:d}),s.addEventListener("keydown",m=>e.handleKeyDown(m),{signal:d}),s.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:d}),s.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:d}),l&&l.addEventListener("click",m=>{let u=e.store.get();if(!(!!u.text||u.completedParams.length>0)||!e.onSubmit)return;m.stopPropagation();let{rawQuery:v,completedParams:T}=S(u.text,u.completedParams);e.onSubmit({query:u.text.trim(),raw_query:v,completed_params:T}),e.afterSubmit?.()},{signal:d}),e.autoFocus!==!1){s.focus();let m=s.ownerDocument??document,u=m.getSelection(),y=u&&u.rangeCount>0&&s.contains(u.anchorNode);if(u&&!y){let v=m.createRange();v.selectNodeContents(s),v.collapse(!0),u.removeAllRanges(),u.addRange(v)}}if(typeof ResizeObserver<"u"){let m=new ResizeObserver(()=>ke(s,a));m.observe(s),p.signal.addEventListener("abort",()=>m.disconnect(),{once:!0})}return{input:s,inlinePillContainer:a,dropdown:i,submitButton:c,abort:p}}function de(n,e,t){let{input:i,inlinePillContainer:o,dropdown:r,submitButton:s}=n,{pillPlacement:a,setActivePill:c,selectOption:l,store:p}=t;i.setAttribute("aria-expanded",String(e.isDropdownOpen));let d=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(d?i.setAttribute("aria-activedescendant",d):i.removeAttribute("aria-activedescendant"),s){let b=!!e.text||e.completedParams.length>0;s.disabled=!b}let g=i.dataset.newParamId??"",h=e.newParamId!==null&&e.newParamId!==g;if(ee({input:i,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused}),a==="inline"){let b=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;b||e.actionableSuggestions.length>0?Y(o,e.actionableSuggestions,0,c,!1,b,e.isActivePillSelected):ae(o)}else ae(o);ke(i,o),h?(i.focus(),P(i,e.caretOffset??e.text.length)):e.isFocused&&L(i)!==e.text&&P(i,e.text.length);let x=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:null,f=x??e.actionableSuggestions[0];Z(r,{suggestions:f?[{...f,options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation,listboxId:t.listboxId,pills:x?[x]:e.actionableSuggestions,showPills:a==="dropdown",isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,onSelect:l,onHighlight:b=>p.set({activeDropdownIndex:b}),onPillClick:c})}function Re(n,e){let t=n.actionableSuggestions[0];if(!t)return null;let i=n.filterBase,o=n.text.slice(0,i),r=o.length===0&&n.text.length===0,s=o.length===0&&n.text.length>0&&n.placeholderText.length>0&&n.placeholderText.toLowerCase().startsWith(n.text.toLowerCase());(r||s)&&n.placeholderText&&(o=`${n.placeholderText} `);let a=he(o,e.text);a>0&&(o=o.slice(0,o.length-a));let c=o.length>0&&o[o.length-1]!==" ",l=`${o}${c?" ":""}${e.text} `,p=(r||s)&&l.length>0?l[0].toUpperCase()+l.slice(1):l,d=p.toLowerCase().lastIndexOf(e.text.toLowerCase()),g=d>=0?p.slice(d,d+e.text.length):e.text,h={id:crypto.randomUUID(),placeholder:"",type:t.type,text:g,kind:e.kind,suggestionType:t.type,suggestionPlaceholder:t.text,options:t.options??[],metadata:e.metadata},x=n.actionableSuggestions.length-1;return{patch:{text:p,filterBase:p.length,completedParams:[...n.completedParams,h],newParamId:h.id,caretOffset:p.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:x>0,inSelectionAnimation:!0},telemetry:{selectedOption:e.text,otherOptions:n.filteredOptions.filter(f=>f.text!==e.text).map(f=>f.text)},consumedSuggestion:t,remainingActionable:x}}function te(n){let e=n,t=new Set;return{get:()=>e,set:i=>{let o=typeof i=="function"?i(e):i,r={...e,...o},s=e;e=r;for(let a of t)a(r,s)},subscribe:i=>(t.add(i),()=>{t.delete(i)})}}function Ne(n,e){let t,i,o=r=>(r!==t&&(t=r,i=e(r)),i);return{get:()=>{let r=n.get();return{...r,...o(r)}},set:r=>{typeof r=="function"?n.set(s=>{let a={...s,...o(s)};return r(a)}):n.set(r)},peek:r=>{let s={...n.get(),...r};return{...s,...e(s)}},subscribe:r=>n.subscribe((s,a)=>{let c={...a,...o(a)},l={...s,...o(s)};r(l,c)})}}var pe=!1;function _e(){if(pe||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){pe=!0;return}pe=!0;let n=document.createElement("style");n.setAttribute("data-magicx-aia",""),n.textContent=ft,document.head.appendChild(n)}var ft=`@layer layout {
2
2
  .aia-stack {
3
3
  display: flex;
4
4
  flex-direction: column;
@@ -181,24 +181,50 @@
181
181
  min-width: 1px;
182
182
  }
183
183
 
184
- /* Completed params render as inline bold runs. Specificity stays at (0,2,0)
185
- so consumers can override with \`.magicx-aia-input strong\`. */
186
- :where(.magicx-aia-input) strong {
187
- font-weight: 600;
188
- letter-spacing: -0.01em;
184
+ /* Completed params render as inline pills (Figma "RichTextPill") \u2014 a compact
185
+ ~26px chip with regular-weight primary-color text on a faint-gray fill.
186
+ inline-block gives the padding / radius a box while the text stays part of
187
+ the editable plain text (the caret system counts characters inside this
188
+ <strong>). white-space: nowrap keeps a pill from breaking across lines.
189
+ :where() zeroes the wrapper so the rule sits at (0,1,1) \u2014 the same
190
+ specificity as a consumer's \`.magicx-aia-input strong\`, which then wins on
191
+ cascade order (their stylesheet loads after this injected one). */
192
+ :where(.magicx-aia-input) strong.magicx-aia-segment--completed {
193
+ display: inline-block;
194
+ padding: 4px 6px;
195
+ border-radius: 999px;
196
+ background: var(--aia-completed-pill-bg, rgba(189, 189, 189, 0.15));
197
+ color: var(--aia-completed-pill-color, var(--aia-written-text-color, #fff));
198
+ font-size: var(--aia-pill-font-size, 14px);
199
+ font-weight: 400;
200
+ line-height: normal;
201
+ white-space: nowrap;
202
+ /* Small vertical breathing room so wrapped rows of pills don't touch. */
203
+ margin: 2px 0;
204
+ vertical-align: middle;
205
+ cursor: pointer;
206
+ /* Smooth hover fade. Neutralized by the data-animations="off" block, which
207
+ zeroes transition-duration on every descendant. */
208
+ transition: background-color 150ms ease;
209
+ }
210
+
211
+ /* Hover highlight \u2014 a slightly stronger fill so a pointed-at pill reads as
212
+ tappable. Declared between the base and editing rules so editing (a tapped
213
+ pill in re-edit) still wins. */
214
+ :where(.magicx-aia-input) strong.magicx-aia-segment--completed:hover {
215
+ background: var(--aia-completed-pill-bg-active, rgba(189, 189, 189, 0.35));
189
216
  }
190
217
 
191
- /* Re-edit highlight \u2014 applied to the bold param being re-edited. A 20% fill
192
- marks the selection; the native selection paint and caret are hidden so the
193
- only visual cue is this fill. */
218
+ /* Re-edit highlight \u2014 applied to the completed pill being re-edited (i.e. after
219
+ a tap). Reuses the exact hover fill so the highlight persists from tap until
220
+ an option is selected (ReEditManager clears the editing class on select). The
221
+ native caret is hidden so the fill is the only cue; cursor switches to text
222
+ since the pill is in text-replacement mode. Same specificity (0,1,1) as the
223
+ base/hover rules, declared last so it wins on a strong carrying both classes. */
194
224
  :where(.magicx-aia-input) strong.magicx-aia-segment--editing {
195
- background-color: color-mix(in srgb, var(--aia-edit-outline, currentColor) 20%, transparent);
196
- border-radius: 6px;
197
- padding: 2px 3px;
198
- /* Pull surrounding inline text back so the wider/taller fill doesn't shove
199
- the rest of the line \u2014 only the visible background grows. */
200
- margin: 0 -1.5px;
225
+ background: var(--aia-completed-pill-bg-active, rgba(189, 189, 189, 0.35));
201
226
  caret-color: transparent;
227
+ cursor: text;
202
228
  }
203
229
 
204
230
  /* In re-edit mode the caret is parked just *before* the bold strong, which
@@ -499,20 +525,19 @@
499
525
  vertical-align: middle;
500
526
  }
501
527
 
502
- /* --- Individual pill --- */
528
+ /* --- Individual pill (Figma "ParamPill") ---
529
+ Unfilled suggestion pill: transparent fill with a dashed border (the fill
530
+ was previously a color-mix chip). Height ~28px via 6px padding + 14px text +
531
+ the 1px border (border-box). Public class name is intentionally kept stable
532
+ for consumer overrides. */
503
533
  .magicx-aia-pill {
504
534
  display: inline-flex;
505
535
  align-items: center;
506
536
  justify-content: center;
507
- padding: 7px 10px;
508
- border: none;
537
+ padding: 6px;
538
+ border: 1px dashed var(--aia-pill-border, rgba(189, 189, 189, 0.3));
509
539
  border-radius: 999px;
510
- background: rgba(49, 50, 85, 0.25);
511
- background: color-mix(
512
- in srgb,
513
- var(--aia-pill-bg, var(--aia-color-background-supportive, #313255)) 30%,
514
- transparent
515
- );
540
+ background: transparent;
516
541
  color: var(--aia-pill-color, var(--aia-color-text-muted, #c1c4cb));
517
542
  font-family: inherit;
518
543
  font-size: var(--aia-pill-font-size, 14px);
@@ -528,11 +553,14 @@
528
553
  }
529
554
 
530
555
  /* Real pill rendered as a skeleton (mirrored from cached pills during loading).
531
- Preserves the pill's full box so width/height match the previous state. */
556
+ Preserves the pill's full box so width/height match the previous state. The
557
+ base pill is now transparent, so fill the interior with the skeleton color
558
+ (inside the dashed border) and pulse it so it still reads as a loading chip. */
532
559
  .magicx-aia-pill[data-aia-loading] {
533
560
  pointer-events: none;
534
561
  cursor: default;
535
562
  color: transparent;
563
+ background: var(--aia-skeleton-bg, var(--aia-pill-bg, rgba(189, 189, 189, 0.51)));
536
564
  animation: magicx-aia-pill-skeleton-pulse 1.4s ease-in-out infinite;
537
565
  }
538
566
 
@@ -870,44 +898,17 @@
870
898
  }
871
899
  }
872
900
 
873
- /* --- Shimmer --- */
874
- .magicx-aia-shimmer {
875
- position: relative;
876
- z-index: 2;
877
- display: inline;
878
- }
879
-
880
- .magicx-aia-shimmer-revealed {
881
- color: transparent;
882
- background: linear-gradient(
883
- 120deg,
884
- var(--aia-written-text-color, var(--aia-color-text-default, #fff)) 0%,
885
- var(--aia-written-text-color, var(--aia-color-text-default, #fff)) 44%,
886
- #b0b0b0 48%,
887
- #b0b0b0 52%,
888
- var(--aia-written-text-color, var(--aia-color-text-default, #fff)) 56%,
889
- var(--aia-written-text-color, var(--aia-color-text-default, #fff)) 100%
890
- );
891
- background-size: 200% 100%;
892
- -webkit-background-clip: text;
893
- background-clip: text;
894
- }
895
-
896
- .magicx-aia-shimmer-sweep {
897
- animation: magicx-aia-textShimmer 650ms ease-out forwards;
898
- }
899
-
900
- @keyframes magicx-aia-textShimmer {
901
- 0% {
902
- background-position: 100% 0;
903
- }
904
- 100% {
905
- background-position: -50% 0;
906
- }
907
- }
908
-
909
- .magicx-aia-shimmer-hidden {
910
- color: transparent !important;
901
+ /* --- Promotion reveal ---
902
+ A newly promoted completed param is stamped with the shimmer-revealed /
903
+ shimmer-sweep classes by renderEditable. Now that completed params are pills
904
+ (with a solid background), the old text-clip gradient shimmer can't be used \u2014
905
+ \`background-clip: text\` would wipe out the pill background. The reveal is a
906
+ simple fade-in of the whole pill instead (matching how unfilled pills enter
907
+ via magicx-aia-fadeIn). shimmer-revealed carries no styling on its own; the
908
+ fade rides on shimmer-sweep so it only plays on genuine promotions, not on
909
+ every re-render of the pill. */
910
+ :where(.magicx-aia-input) strong.magicx-aia-shimmer-sweep {
911
+ animation: magicx-aia-fadeIn 400ms cubic-bezier(0.4, 0, 0.2, 1) forwards;
911
912
  }
912
913
 
913
914
  /*
@@ -949,6 +950,9 @@
949
950
  --aia-primitive-neutral-1000: #ffffff;
950
951
  --aia-primitive-blue-50: #eef2ff;
951
952
  --aia-primitive-neutral-750-a50: rgba(189, 189, 189, 0.51);
953
+ --aia-primitive-neutral-750-a35: rgba(189, 189, 189, 0.35);
954
+ --aia-primitive-neutral-750-a30: rgba(189, 189, 189, 0.3);
955
+ --aia-primitive-neutral-750-a15: rgba(189, 189, 189, 0.15);
952
956
  --aia-primitive-neutral-700-a40: rgba(176, 176, 176, 0.4);
953
957
  }
954
958
 
@@ -965,10 +969,22 @@
965
969
  --aia-primitive-neutral-900
966
970
  ); /* was #e5e7eb \u2014 snapped to palette (\u03942) */
967
971
  --aia-dropdown-shadow: 0 8px 12px rgba(0, 0, 0, 0.1);
968
- --aia-pill-bg: var(--aia-primitive-neutral-750); /* solid; per-pill opacity via getPillOpacity */
972
+ /* Suggestion pills (Figma "ParamPill"): transparent fill + dashed border;
973
+ per-pill opacity via getPillOpacity. --aia-pill-bg is retained for
974
+ consumer overrides but the default ParamPill no longer paints a fill. */
975
+ --aia-pill-bg: var(--aia-primitive-neutral-750);
969
976
  --aia-pill-color: var(--aia-primitive-neutral-300);
977
+ --aia-pill-border: var(--aia-primitive-neutral-750-a30);
970
978
  --aia-pill-font-size: 14px;
971
979
 
980
+ /* Completed params (Figma "RichTextPill"): compact faint-gray chip with
981
+ primary-color regular-weight text. -active is the hover / tapped (re-edit)
982
+ highlight \u2014 an alpha over the input background, so one value works in both
983
+ themes. */
984
+ --aia-completed-pill-bg: var(--aia-primitive-neutral-750-a15);
985
+ --aia-completed-pill-bg-active: var(--aia-primitive-neutral-750-a35);
986
+ --aia-completed-pill-color: var(--aia-primitive-neutral-0);
987
+
972
988
  --aia-option-bg: var(--aia-primitive-blue-50);
973
989
  --aia-option-color: var(--aia-primitive-neutral-500);
974
990
  --aia-option-color-selected: var(--aia-primitive-neutral-0);
@@ -1006,10 +1022,18 @@
1006
1022
  --aia-primitive-neutral-400
1007
1023
  ); /* was #484848 \u2014 snapped to palette (\u03942) */
1008
1024
  --aia-dropdown-shadow: 0 8px 12px rgba(0, 0, 0, 0.1);
1025
+ /* Suggestion pills (Figma "ParamPill"): transparent fill + dashed border. */
1009
1026
  --aia-pill-bg: var(--aia-primitive-neutral-750);
1010
1027
  --aia-pill-color: var(--aia-primitive-neutral-700);
1028
+ --aia-pill-border: var(--aia-primitive-neutral-750-a30);
1011
1029
  --aia-pill-font-size: 14px;
1012
1030
 
1031
+ /* Completed params (Figma "RichTextPill") \u2014 dark theme (design source):
1032
+ white text on a faint-gray chip. -active is the hover / tapped highlight. */
1033
+ --aia-completed-pill-bg: var(--aia-primitive-neutral-750-a15);
1034
+ --aia-completed-pill-bg-active: var(--aia-primitive-neutral-750-a35);
1035
+ --aia-completed-pill-color: var(--aia-primitive-neutral-1000);
1036
+
1013
1037
  --aia-option-bg: var(--aia-primitive-neutral-250);
1014
1038
  --aia-option-color: var(--aia-primitive-neutral-700);
1015
1039
  --aia-option-color-selected: var(--aia-primitive-neutral-1000);