@magicx-eng/ai-autocomplete-vanilla 0.4.7 → 0.5.1

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/README.md CHANGED
@@ -366,8 +366,14 @@ Override these on the container element. All built-in defaults use `:where()` (z
366
366
  | `--aia-written-text-color` | `#000000` | `#ffffff` | Input text |
367
367
  | `--aia-written-text-font-size` | `19px` | `19px` | Input text font size |
368
368
  | `--aia-caret-color` | `--aia-written-text-color` | `--aia-written-text-color` | Editor caret color. Override independently of input text color. |
369
- | `--aia-submit-bg` | `#000000` | `#ffffff` | Submit button background |
370
- | `--aia-submit-color` | `#ffffff` | `#000000` | Submit button icon color |
369
+ | `--aia-submit-bg` | `#000000` | `#ffffff` | Submit button background. Solid + full-opacity at rest, even when the input is empty/disabled. |
370
+ | `--aia-submit-color` | `#ffffff` | `#000000` | Submit button arrow color |
371
+ | `--aia-submit-bg-disabled` | `--aia-submit-bg` | `--aia-submit-bg` | Submit background when disabled (empty input). Defaults to the enabled background so themed colors aren't washed out. Set this for a faded rest state. |
372
+ | `--aia-submit-color-disabled` | `--aia-submit-color` | `--aia-submit-color` | Submit arrow color when disabled. Defaults to the enabled color. |
373
+ | `--aia-border` | `rgba(17, 24, 39, 0.14)` | `#505050` | Input container border color |
374
+ | `--aia-shadow` | `inset 0 1px 0 rgba(255,255,255,0.9), 0 1px 2px rgba(16,24,40,0.1), 0 8px 24px rgba(16,24,40,0.16)` | `inset 0 1px 0 rgba(255,255,255,0.06), 0 1px 2px rgba(0,0,0,0.4), 0 8px 24px rgba(0,0,0,0.5)` | Input container elevation (box-shadow) |
375
+ | `--aia-dropdown-offset` | `13px` | `13px` | Gap between the input box and the dropdown (the dropdown's margin toward the input). |
376
+ | `--aia-footer-gap` | `8px` | `8px` | Breathing room above the dropdown footer (badge / keyboard hints), additive to the dropdown's 8px section gap. |
371
377
  | `--aia-dropdown-bg` | — | — | Optional bg color the dropdown's "glass" rim shadow tints toward. Set this to the page background behind the dropdown so the bottom-corner glow blends seamlessly. |
372
378
  | `--aia-scrollbar-thumb` | `rgba(0, 0, 0, 0.3)` | `rgba(0, 0, 0, 0.3)` | Color of the option list's scrollbar thumb (Firefox + WebKit). |
373
379
  | `--aia-streak-rgb` | `99, 102, 241` | `255, 255, 255` | Comma-separated RGB triplet used to tint the option-selection streak animation (consumed via `rgba(var(--aia-streak-rgb), …)`). |
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var oe=Object.defineProperty;var qe=Object.getOwnPropertyDescriptor;var Qe=Object.getOwnPropertyNames;var $e=Object.prototype.hasOwnProperty;var Ue=(n,e)=>{for(var t in e)oe(n,t,{get:e[t],enumerable:!0})},Ge=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Qe(e))!$e.call(n,r)&&r!==t&&oe(n,r,{get:()=>e[r],enumerable:!(i=qe(e,r))||i.enumerable});return n};var We=n=>Ge(oe({},"__esModule",{value:!0}),n);var Tt={};Ue(Tt,{AIAutocomplete:()=>re,ModeController:()=>M,buildQuery:()=>S,createStore:()=>te,cursorIsAtEnd:()=>$,extractPlainText:()=>L,getCursorOffset:()=>E,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.4.7",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 r=e.find(o=>o.type==="contact"&&o.metadata?.contact_account_count)?.metadata?.contact_account_count,s=typeof r=="number"?r:void 0;return{data:{raw_query:n,completed_params:e.map(o=>Ye(o,t)),...s!=null&&{contact_account_count:s}},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,r){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:r})}async function fe(n,e,t){let i=t.apiConfig,r=!t.maskCompletedText,s=Je(n,e,r,t.sessionId),o=H(i),a=i?.endpoint??N,c=JSON.stringify(s);if(k(i)){let d=_(i),u=await d.getToken(),h=await ge(a,o,u,c,t.signal);if(h.status===401){let x=await d.getToken(!0);h=await ge(a,o,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&&(o.Authorization=l);let p=await fetch(a,{method:"POST",headers:o,body:c,signal:t.signal});if(!p.ok)throw new Error(`API error: ${p.status} ${p.statusText}`);return p.json()}function S(n,e){let t=n,i={},r=[];for(let s of e){let o=(i[s.type]??0)+1;i[s.type]=o;let c=`{{${s.type.toUpperCase().replace(/\s+/g,"_")}_${o}}}`,l=t.indexOf(s.text);l!==-1&&(t=t.slice(0,l)+c+t.slice(l+s.text.length)),r.push({...s,placeholder:c})}return{rawQuery:t,completedParams:r}}function I(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function C(n,e,t){let i=n.slice(e);if(t||e===0||n[e-1]===" ")return i;let r=i.indexOf(" ");return r===-1?"":i.slice(r+1)}function he(n,e){let t=n.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let i=t.split(" "),r=e.toLowerCase();for(let s=0;s<i.length;s++){let o=i.slice(s).join(" ");if(r.startsWith(o.toLowerCase())){let a=t.length-o.length;return n.length-a}}return 0}function w(n,e){if(!n)return[];let t=e.trimStart();if(!t)return n;let i=t.toLowerCase();return n.filter(r=>!r.is_tappable||r.text.toLowerCase().includes(i))}function O(n,e){if(!n)return null;let t=e.trim();if(!t)return null;let i=t.toLowerCase();return n.find(r=>r.is_tappable&&r.text.toLowerCase()===i)??null}function xe(n,e){return e?n.map(t=>{let i=e[t.type];if(!i)return t;let r=i("");if(r.length===0)return t;let s=new Set(r.map(a=>a.text)),o=(t.options??[]).filter(a=>!s.has(a.text));return{...t,options:[...r,...o]}}):n}var Ze=100,et=300,tt=2,B=class{constructor(e,t,i,r,s,o,a={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=r;this.getOnError=s;this.getSessionId=o;this.callbacks=a;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null}start(){this.doFetch("",[]);let e=this.store.get().text,t=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(i=>{(i.text!==e||i.completedParams!==t)&&(e=i.text,t=i.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let i=new AbortController;this.abortController=i;let r=++this.fetchVersion,s=this.store.get().text.length;this.store.set({isLoading:!0,error:null});try{let o=await fe(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig()});if(r!==this.fetchVersion)return;let a=xe(o.data.suggestions??[],this.getOptionOverrides()),c=o.data.input??[],l=c[c.length-1],p=this.store.get().text,d,u;if(l?.state==="in_progress"){u=!0;let b=p.toLowerCase().lastIndexOf(l.text.toLowerCase());d=b!==-1?b:s}else u=!1,d=s;let x=a.filter(b=>b.type!=="placeholder")[0],g=null;if(x){let b=C(p,d,u),m=O(x.options,b);m&&(g={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(f=>f!==x),this.callbacks.onAutoMatch?.({active:x,matched:m,rawQuery:e}))}this.store.set(b=>({suggestions:a,isLoading:!1,isReady:o.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:d,filterInProgress:u,...g?{completedParams:[...b.completedParams,g]}:{}}))}catch(o){if(r===this.fetchVersion){let a=o instanceof Error?o:new Error(String(o));this.store.set({error:a,isLoading:!1}),this.getOnError()?.(a)}}}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}let t=i=>{let r=this.store.get();if(!r.text&&r.completedParams.length===0)return this.doFetch("",[]),!0;let s=r.suggestions.filter(f=>f.type==="placeholder").map(f=>f.text).join(" "),o=I(r.text,r.filterBase,s),a=C(r.text,o,r.filterInProgress),l=r.suggestions.filter(f=>f.type!=="placeholder")[0],d=(l?w(l.options,a):[]).filter(f=>f.is_tappable),u=l?O(l.options,a)!==null:!1,h=a.trim().length>0;if(d.length>0&&!u&&h||r.completedParams.length===0&&r.text.length>0&&s.length>0&&s.toLowerCase().startsWith(r.text.toLowerCase()))return!1;let{rawQuery:x,completedParams:g}=S(r.text,r.completedParams),b=x.length<r.lastRawQuery.length,m=Math.abs(x.length-r.lastRawQuery.length);return b||m>=i?(this.doFetch(x,g),!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 E(n){let e=(n.ownerDocument??document).getSelection();if(!e||e.rangeCount===0)return null;let t=e.anchorNode,i=e.anchorOffset;if(!t||!n.contains(t))return null;if(t.nodeType===Node.ELEMENT_NODE){let r=t;if(K(r,n)&&r!==n)return null;let s=0;for(let o=0;o<i&&o<r.childNodes.length;o++)s+=ve(r.childNodes[o],n);return s+be(r,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 r of Array.from(t.childNodes))i+=ve(r,e);return i}function be(n,e){let t=q(e),i=0,r=t.nextNode();for(;r;){if(r===n||n.nodeType===Node.ELEMENT_NODE&&n.contains(r))return i;i+=r.data.length,r=t.nextNode()}return i}function P(n,e){let t=n.ownerDocument??document,i=t.getSelection();if(!i)return;let r=Math.max(0,Math.min(e,Q(n))),s=q(n),o=0,a=null,c=0,l=s.nextNode(),p=null;for(;l;){let u=l.data.length;if(r<o+u){a=l,c=r-o;break}if(r===o+u){let h=s.nextNode();h?(a=h,c=0):(a=l,c=u);break}o+=u,p=l,l=s.nextNode()}let d=t.createRange();if(a){let u=a.parentElement?.closest('strong[data-seg="completed"]');u&&u!==n&&n.contains(u)?c===0?d.setStartBefore(u):c===a.data.length?d.setStartAfter(u):d.setStart(a,c):d.setStart(a,c)}else p?d.setStart(p,p.data.length):d.setStart(n,0);d.collapse(!0),i.removeAllRanges(),i.addRange(d)}function $(n){let e=E(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),r=0;for(let{index:s}of t.segment(i))s<e&&(r=s);return r}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")?E(n):null}var G=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:r}=this.ctx,s=this.getEffectiveColumns(),o=r(),a=this.getTappableIndices(s);if((e.shiftKey||e.metaKey||e.ctrlKey||e.altKey)&&(e.key==="ArrowDown"||e.key==="ArrowUp"||e.key==="ArrowLeft"||e.key==="ArrowRight"))return;let 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)/s);if(Math.floor(t.activeDropdownIndex/s)===h){this.store.set({activeDropdownIndex:-1});break}}let d=a.indexOf(t.activeDropdownIndex),u=d<a.length-1?d+1:0;this.store.set({activeDropdownIndex:a[u]});break}case"ArrowUp":{if(t.activeDropdownIndex<0){if(!c)break;let d=se(e.target,t),u=!!t.editingParam;if(!d&&!u)break;e.preventDefault();let h=this.firstTappableInBottomRow(s)??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<s){this.store.set({activeDropdownIndex:-1});break}let l=a.indexOf(t.activeDropdownIndex),p=l>0?l-1:a.length-1;this.store.set({activeDropdownIndex:a[p]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%s<s-1){let 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%s>0){let l=t.activeDropdownIndex-1;l>=0&&t.filteredOptions[l]?.is_tappable&&this.store.set({activeDropdownIndex:l})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let l=e.target.closest("[data-aia-input]")??e.target,p=t.editingAnchor;this.ctx.exitEditMode?.(),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(o){let{rawQuery:l,completedParams:p}=S(t.text,t.completedParams);o({query:t.text.trim(),raw_query:l,completed_params:p}),this.ctx.afterSubmit?.()}break}case"Tab":{let l=t.filteredOptions.map((u,h)=>u.is_tappable?h:-1).filter(u=>u!==-1);if(l.length===0)break;if(!t.isDropdownOpen){if(t.actionableSuggestions.length===0)break;e.preventDefault();let u=e.shiftKey?l[l.length-1]:l[0];this.store.set({pillTapped:!0,activeDropdownIndex:u});break}e.preventDefault();let p=l.indexOf(t.activeDropdownIndex),d;if(p<0)d=e.shiftKey?l.length-1:0;else{let u=e.shiftKey?-1:1;d=(p+u+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 r=Math.floor((t.filteredOptions.length-1)/e)*e;for(let s=r;s<t.filteredOptions.length;s++)if(t.filteredOptions[s]?.is_tappable)return s;return null}getTappableIndices(e){let i=this.store.get().filteredOptions.map((s,o)=>s.is_tappable?o:-1).filter(s=>s!==-1),r=Array.from({length:e},()=>[]);for(let s of i)r[s%e].push(s);return r.flat()}getEffectiveColumns(){let e=document.getElementById(this.ctx.listboxId);if(!e)return this.ctx.columns;let i=document.getElementById(`${this.ctx.listboxId}-option-0`)?.parentElement??null;for(;i;){let r=getComputedStyle(i).gridTemplateColumns;if(r&&r!=="none"){let s=r.split(" ").filter(Boolean).length;if(s>0)return s}if(i===e)break;i=i.parentElement}return this.ctx.columns}clickOrSelect(e,t,i){let r=document.getElementById(`${i}-option-${e}`);r?r.click():this.ctx.selectOption(t[e])}removeActivePill(){let e=this.store.get(),t=e.suggestions.filter(s=>s.type==="placeholder"),i=e.suggestions.filter(s=>s.type!=="placeholder");if(i.length===0)return;let r=i.slice(1);this.store.set({suggestions:[...t,...r],pillTapped:r.length>0,activeDropdownIndex:-1})}};var 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 r=i[e],s=i.filter((l,p)=>p!==e),o=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:r.text,otherPills:s.map(p=>p.text)})}let a=[...o,r,...s],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 s of e){let o=n.indexOf(s.text,i);o!==-1&&(o>i&&t.push({type:"text",value:n.slice(i,o)}),t.push({type:"completed",value:s.text,param:s}),i=o+s.text.length)}let r=n.slice(i);return r&&t.push({type:"text",value:r}),t}function Pe(n,e){let t=[],i=[],r=0;for(let s of e){let o=n.indexOf(s.text,r);o===-1?i.push(s):(t.push(s),r=o+s.text.length)}return{valid:t,invalid:i}}function Te(n,e){let t=e.dropdownTrigger??"auto",i=e.closeDropdownOnBlur??!0,r=n.filteredOptionsLength>0;if(n.inEditMode){let s=i?n.isFocused:!0;return r&&s}if(t==="auto"){let s=i?n.isFocused:!0,o=n.text.replace(/\s+$/,"").length,a=n.caretOffset==null||n.caretOffset>=o;return(r||n.isLoading)&&s&&a}return t==="manual"?(r||n.isLoading)&&n.pillTapped:!1}function Ee(n,e){let t=Se(n.text,n.completedParams),i=n.suggestions.filter(g=>g.type!=="placeholder"),r=i[0],s=r?e.optionOverrides?.[r.type]:void 0,o=n.suggestions.filter(g=>g.type==="placeholder").map(g=>g.text).join(" "),a=I(n.text,Math.min(n.filterBase,n.text.length),o),l=n.lastRawQuery!==""||a>0?C(n.text,a,n.filterInProgress):"",p=r?s?s(l.trim()):r.options??[]:[],d=n.editingParam!=null&&n.editingAnchor!=null,u;if(d&&n.editingParam&&n.editingAnchor!=null){let g=n.editingParam.id,b=n.completedParams.some(y=>y.id===g),m=n.caretOffset??n.editingAnchor,f=b?"":n.text.slice(n.editingAnchor,m);u=w(n.editingParam.options,f)}else u=w(p,l);e.showNonTappableOptions===!1&&(u=u.filter(g=>g.is_tappable));let h=Te({inEditMode:d,filteredOptionsLength:u.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading,pillTapped:n.pillTapped},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),x=h&&n.activeDropdownIndex>=0&&!!u[n.activeDropdownIndex]?.is_tappable;return{segments:t,actionableSuggestions:i,filteredOptions:u,placeholderText:o,isDropdownOpen:h,isActivePillSelected:x}}function j(n){return n.mode==="fresh"?rt(n):ot(n)}function rt(n){let{text:e,completedParams:t,suggestions:i,filterBase:r,filterInProgress:s}=n,a=i.filter(v=>v.type!=="placeholder")[0];if(!a?.options)return null;let c=i.filter(v=>v.type==="placeholder").map(v=>v.text).join(" "),l=I(e,r,c),p=C(e,l,s),d=O(a.options,p);if(!d)return null;let u=d.text.toLowerCase(),h=e.toLowerCase().lastIndexOf(u),x=h>=0?h:Math.max(0,e.length-d.text.length),g=x+d.text.length,b=e.slice(x,g),f=g<e.length&&e[g]===" "?g+1:g,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:f,newParamId:y.id,caretOffset:f,activeDropdownIndex:-1},caretPos:f}}function ot(n){let{text:e,completedParams:t,editingParam:i,editingAnchor:r,editingTail:s}=n;if(t.some(y=>y.id===i.id))return null;let o=e.slice(r,s),a=O(i.options,o);if(!a)return null;let c=a.text.toLowerCase(),l=o.toLowerCase().lastIndexOf(c),p=r+Math.max(0,l),d=p+a.text.length,u=e.slice(p,d),x=d<e.length&&e[d]===" "?d+1:d,g={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:u,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 f=[...t];return f.splice(b,0,g),{patch:{text:e,completedParams:f,newParamId:g.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(o=>o.id===e);if(!i)return;let r=0,s=-1;for(let o of t.completedParams){let a=t.text.indexOf(o.text,r);if(a!==-1){if(o.id===e){s=a;break}r=a+o.text.length}}s<0||this.deps.store.set({editingParam:i,editingAnchor:s,editingTail:s+i.text.length,caretOffset:s+i.text.length,activeDropdownIndex:-1})}exit(){this.deps.store.get().editingParam&&this.deps.store.set({editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1})}replaceRange(e){let t=this.deps.store.get(),i=t.editingParam,r=t.editingAnchor,s=t.editingTail;if(!i||r==null||s==null||!t.completedParams.some(c=>c.id===i.id))return!1;let o=t.text.slice(0,r)+e+t.text.slice(s),a=r+e.length;return this.deps.store.set(c=>({text:o,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,r=t.editingAnchor,s=t.editingTail;if(!i||r==null||s==null)return;this.deps.fireTelemetry("option",{raw_query:S(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:i.options.filter(m=>m.text!==e.text).map(m=>m.text)});let o=t.text.slice(0,r),a=t.text.slice(s),c=r===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,l=a.length===0||a[0]!==" ",p=l?`${c} `:c,d=o+p+a,u=r+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),g=t.completedParams.filter(m=>m.id!==i.id),b=x>=0?Math.min(x,g.length):g.length;g.splice(b,0,h),this.deps.store.set({text:d,completedParams:g,newParamId:h.id,filterBase:u,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:u,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.deps.startSelectionAnimationTimer(),this.deps.scheduleSetCursor(u)}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 Ce="data-aia-key";function X(n,e,t){let i=new Map;for(let o of Array.from(n.children)){let a=o.getAttribute(Ce);a!=null&&i.set(a,o)}let r=new Set,s=[];for(let o=0;o<e.length;o++){let a=e[o],c=t.keyOf(a,o);r.add(c);let l=i.get(c);l||(l=t.create(a,o),l.setAttribute(Ce,c)),t.update?.(l,a,o),n.children[o]!==l&&n.insertBefore(l,n.children[o]??null),s.push(l)}for(let[o,a]of i)r.has(o)||a.remove();return s}var we=[125,69];function Ae(n,e){return e?1:n===0?.7:n===1?.4:.2}function Y(n,e,t,i,r=!1,s=!1,o=!1){let a=n.querySelector(".magicx-aia-pill-list");if(a||(a=document.createElement("span"),a.className="magicx-aia-pill-list",n.appendChild(a)),s&&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${r?" magicx-aia-pill--rounded":""}`,p.style.width=`${l}px`,p.style.opacity=String(Ae(c,!1)),a.appendChild(p)}return}s?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,u=o&&p===t&&!s,h=["magicx-aia-pill"];r&&h.push("magicx-aia-pill--rounded"),u&&h.push("magicx-aia-pill--active"),s&&h.push("magicx-aia-pill--skeleton"),d.className=h.join(" "),d.style.width="",d.style.opacity=String(Ae(p,u)),s?(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,r,s,o){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,r,s,o),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,r,s,o){let a=o?"1":"0";X(n,e,{keyOf:c=>`${c.text}\0${a}`,create:c=>ct(c,o),update:(c,l,p)=>{let d=p===t&&!o;c.id=`${s}-option-${p}`,c.dataset.aiaIndex=String(p),c.setAttribute("aria-selected",String(d)),c.classList.toggle("magicx-aia-option--highlighted",d),!o&&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 u=Number.parseInt(c.dataset.aiaIndex??"-1",10);u>=0&&r(u)}):(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 r=document.createElement("div");r.className="magicx-aia-streaks",t.appendChild(r);let s=document.createElement("div");s.className="magicx-aia-streaks-vert",t.appendChild(s);let o=document.createElement("span");o.className="magicx-aia-option-content";let a=document.createElement("span");if(a.className="magicx-aia-option-text",a.textContent=n.icon?`${n.icon} ${n.text}`:n.text,o.appendChild(a),n.tag){let c=document.createElement("span");c.className="magicx-aia-option-tag",c.textContent=n.tag,o.appendChild(c)}return t.appendChild(o),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:r,isLoading:s,pills:o,showPills:a,isActivePillSelected:c,onSelect:l,onHighlight:p,onPillClick:d}=e,u=a&&o.length>0,h=t.length>0,x=r&&(h||u||s);if(x?n.classList.add("magicx-aia-dropdown--visible"):n.classList.remove("magicx-aia-dropdown--visible"),s?n.setAttribute("data-aia-loading",""):n.removeAttribute("data-aia-loading"),!x)return;let g=n.querySelector(".aia-stack");g||(g=document.createElement("div"),g.className="aia-stack",g.style.setProperty("--aia-stack-space","8px"),n.appendChild(g));let b=u||s&&a,m=g.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",""),g.insertBefore(m,g.firstChild)),Y(m,o,0,d,!0,s,c)):m&&m.remove(),Ie(g,t,i,l,p,e.listboxId,s);let f=g.querySelector(".magicx-aia-skeleton-bars");if(s&&!h){if(!f){f=document.createElement("div"),f.className="magicx-aia-skeleton-bars",f.setAttribute("data-aia-skeleton-bars","");for(let T of dt){let A=document.createElement("span");A.className="magicx-aia-skeleton-bar",A.style.width=`${T}px`,f.appendChild(A)}g.appendChild(f)}}else f&&f.remove();let y=g.querySelector(".magicx-aia-footer")??ut(),v=i>=0&&!!t[i]?.is_tappable;pt(y,z(v,e.isInputEmpty)),g.lastElementChild!==y&&g.appendChild(y)}function pt(n,{key:e,hint:t}){let i=n.querySelector(".magicx-aia-footer-key"),r=n.querySelector(".magicx-aia-footer-hint");!i||!r||(i.textContent!==e&&(i.textContent=e),r.textContent!==t&&(r.textContent=t))}function ut(){let n=document.createElement("footer");n.className="magicx-aia-footer",n.setAttribute("data-aia-footer","");let e=document.createElement("div");e.className="magicx-aia-footer-divider";let t=document.createElement("div");t.className="aia-cluster magicx-aia-footer-row",t.setAttribute("data-align","center"),t.setAttribute("data-justify","between"),t.setAttribute("data-nowrap","");let i=document.createElement("div");i.className="aia-cluster magicx-aia-footer-hint-group",i.setAttribute("data-align","center"),i.style.setProperty("--aia-cluster-gap","5px");let r=document.createElement("kbd");r.className="magicx-aia-footer-key",r.textContent="tab";let s=document.createElement("span");s.className="magicx-aia-footer-hint",s.textContent="to select",i.append(r,s);let o=document.createElement("a");o.className="aia-cluster magicx-aia-footer-brand-link",o.setAttribute("data-align","center"),o.href="https://ai-autocomplete.com",o.target="_blank",o.rel="noopener noreferrer",o.style.setProperty("--aia-cluster-gap","2px");let a=document.createElement("span");a.className="magicx-aia-footer-brand",a.textContent="AI";let c=document.createElement("span");return c.className="magicx-aia-footer-badge",c.textContent="Autocomplete",o.append(a,c),t.append(i,o),n.append(e,t),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:r,placeholderText:s,isFocused:o}=n,a=t.length===0;e.dataset.aiaEmpty=a?"true":"false",a&&s?e.dataset.placeholder=s:delete e.dataset.placeholder;let 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&&(r??"")===d)return;let u=o?E(e):null;e.dataset.segKey=c,e.dataset.newParamId=i??"",e.dataset.editingParamId=r??"";let h=e.ownerDocument??document,x=h.createDocumentFragment(),g=0;for(let b of t)if(g+=b.value.length,b.type==="completed"){let m=h.createElement("strong");m.dataset.seg="completed",m.dataset.paramId=b.param.id;let f=b.param.id===i,y=b.param.id===r,v=["magicx-aia-segment","magicx-aia-segment--completed"];f&&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(g),u!=null&&P(e,Math.max(0,Math.min(u,g)))}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(),r=n.getBoundingClientRect();i.top>=r.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 r=document.createElement("div");r.className="magicx-aia-input-wrapper",n.appendChild(r);let s=document.createElement("div");s.className="magicx-aia-editor",s.setAttribute("data-aia-editor",""),r.appendChild(s);let o=document.createElement("div");o.className="magicx-aia-input",o.setAttribute("data-aia-input",""),o.setAttribute("contenteditable",gt()?"plaintext-only":"true"),o.setAttribute("role","combobox"),o.setAttribute("aria-autocomplete","list"),o.setAttribute("aria-haspopup","listbox"),o.setAttribute("aria-controls",t),o.setAttribute("aria-expanded","false"),o.setAttribute("spellcheck","true"),o.setAttribute("enterkeyhint","send"),s.appendChild(o);let a=document.createElement("span");a.className="magicx-aia-pill-list-container",a.setAttribute("data-aia-pill-list-container",""),s.appendChild(a);let c=null,l=null;e.submitButton===void 0?(c=Me(),r.appendChild(c),l=c):e.submitButton!==null&&(l=e.submitButton,l.hasAttribute("data-aia-submit")||l.setAttribute("data-aia-submit",""),r.appendChild(l));let p=new AbortController,{signal:d}=p,u=!1,h=0,x=()=>{let m=L(o),y=m.length>0&&m[0]!==m[0].toUpperCase()?m[0].toUpperCase()+m.slice(1):m;e.handleChange(y)},g=()=>{let m=(o.ownerDocument??document).getSelection();if(!m||m.rangeCount===0)return null;let f=m.anchorNode;return!f||!o.contains(f)?null:(f.nodeType===Node.ELEMENT_NODE?f:f.parentElement)?.closest('strong[data-seg="completed"][data-param-id]')?.dataset.paramId??null};r.addEventListener("click",m=>{m.target?.closest("[data-aia-pill]")||o.focus()},{signal:d}),o.addEventListener("input",()=>{u||(h=performance.now(),x(),e.handleCaretAfterInput(E(o)))},{signal:d});let b=o.ownerDocument??document;if(b.addEventListener("selectionchange",()=>{let m=b.getSelection();if(!m||m.rangeCount===0||!o.contains(m.anchorNode))return;let f=g(),y=e.store.get().editingParam?.id??null;if(f&&f!==y){e.startEditingParam(f);return}performance.now()-h<50||e.handleCaretMove(E(o))},{signal:d}),o.addEventListener("compositionstart",()=>{u=!0},{signal:d}),o.addEventListener("compositionend",()=>{u=!1,x()},{signal:d}),o.addEventListener("beforeinput",m=>{let f=m,y=f.inputType;if(y==="insertParagraph"||y==="insertLineBreak"||y==="insertFromDrop"){m.preventDefault();return}if(y.startsWith("insert")||y.startsWith("delete")){let v=y.startsWith("delete")?"":f.data??"";e.replaceEditingRange(v)&&m.preventDefault()}},{signal:d}),o.addEventListener("paste",m=>{m.preventDefault();let f=(m.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!f)return;let y=o.ownerDocument??document,v=y.getSelection();if(!v||v.rangeCount===0)return;let T=v.getRangeAt(0);if(!o.contains(T.startContainer))return;T.deleteContents();let A=y.createTextNode(f);T.insertNode(A),T.setStartAfter(A),T.collapse(!0),v.removeAllRanges(),v.addRange(T),x()},{signal:d}),o.addEventListener("keydown",m=>e.handleKeyDown(m),{signal:d}),o.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:d}),o.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:d}),l&&l.addEventListener("click",m=>{let f=e.store.get();if(!(!!f.text||f.completedParams.length>0)||!e.onSubmit)return;m.stopPropagation();let{rawQuery:v,completedParams:T}=S(f.text,f.completedParams);e.onSubmit({query:f.text.trim(),raw_query:v,completed_params:T}),e.afterSubmit?.()},{signal:d}),e.autoFocus!==!1&&o.focus(),typeof ResizeObserver<"u"){let m=new ResizeObserver(()=>ke(o,a));m.observe(o),p.signal.addEventListener("abort",()=>m.disconnect(),{once:!0})}return{input:o,inlinePillContainer:a,dropdown:i,submitButton:c,abort:p}}function de(n,e,t){let{input:i,inlinePillContainer:r,dropdown:s,submitButton:o}=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"),o){let b=!!e.text||e.completedParams.length>0;o.disabled=!b}let u=i.dataset.newParamId??"",h=e.newParamId!==null&&e.newParamId!==u;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(r,e.actionableSuggestions,0,c,!1,b,e.isActivePillSelected):ae(r)}else ae(r);ke(i,r),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,g=x??e.actionableSuggestions[0];Z(s,{suggestions:g?[{...g,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,r=n.text.slice(0,i),s=r.length===0&&n.text.length===0,o=r.length===0&&n.text.length>0&&n.placeholderText.length>0&&n.placeholderText.toLowerCase().startsWith(n.text.toLowerCase());(s||o)&&n.placeholderText&&(r=`${n.placeholderText} `);let a=he(r,e.text);a>0&&(r=r.slice(0,r.length-a));let c=r.length>0&&r[r.length-1]!==" ",l=`${r}${c?" ":""}${e.text} `,p=(s||o)&&l.length>0?l[0].toUpperCase()+l.slice(1):l,d=p.toLowerCase().lastIndexOf(e.text.toLowerCase()),u=d>=0?p.slice(d,d+e.text.length):e.text,h={id:crypto.randomUUID(),placeholder:"",type:t.type,text:u,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(g=>g.text!==e.text).map(g=>g.text)},consumedSuggestion:t,remainingActionable:x}}function te(n){let e=n,t=new Set;return{get:()=>e,set:i=>{let r=typeof i=="function"?i(e):i,s={...e,...r},o=e;e=s;for(let a of t)a(s,o)},subscribe:i=>(t.add(i),()=>{t.delete(i)})}}function Ne(n,e){let t,i,r=s=>(s!==t&&(t=s,i=e(s)),i);return{get:()=>{let s=n.get();return{...s,...r(s)}},set:s=>{typeof s=="function"?n.set(o=>{let a={...o,...r(o)};return s(a)}):n.set(s)},peek:s=>{let o={...n.get(),...s};return{...o,...e(o)}},subscribe:s=>n.subscribe((o,a)=>{let c={...a,...r(a)},l={...o,...r(o)};s(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.1",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),m=await d.getToken(),h=await ge(a,s,m,c,t.signal);if(h.status===401){let b=await d.getToken(!0);h=await ge(a,s,b,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 E(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 w(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,m;if(l?.state==="in_progress"){m=!0;let f=p.toLowerCase().lastIndexOf(l.text.toLowerCase());d=f!==-1?f:r}else m=!1,d=r;let b=a.filter(f=>f.type!=="placeholder")[0],x=null;if(b){let f=E(p,d,m),u=O(b.options,f);u&&(x={id:crypto.randomUUID(),placeholder:"",type:b.type,text:u.text,kind:u.kind,suggestionType:b.type,suggestionPlaceholder:b.text,options:b.options??[],metadata:u.metadata},a=a.filter(g=>g!==b),this.callbacks.onAutoMatch?.({active:b,matched:u,rawQuery:e}))}this.store.set(f=>({suggestions:a,isLoading:!1,isReady:s.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:d,filterInProgress:m,...x?{completedParams:[...f.completedParams,x]}:{}}))}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(g=>g.type==="placeholder").map(g=>g.text).join(" "),s=I(o.text,o.filterBase,r),a=E(o.text,s,o.filterInProgress),l=o.suggestions.filter(g=>g.type!=="placeholder")[0],d=(l?w(l.options,a):[]).filter(g=>g.is_tappable),m=l?O(l.options,a)!==null:!1,h=a.trim().length>0;if(d.length>0&&!m&&h||o.completedParams.length===0&&o.text.length>0&&r.length>0&&r.toLowerCase().startsWith(o.text.toLowerCase()))return!1;let{rawQuery:b,completedParams:x}=S(o.text,o.completedParams),f=b.length<o.lastRawQuery.length,u=Math.abs(b.length-o.lastRawQuery.length);return f||u>=i?(this.doFetch(b,x),!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 m=l.data.length;if(o<s+m){a=l,c=o-s;break}if(o===s+m){let h=r.nextNode();h?(a=h,c=0):(a=l,c=m);break}s+=m,p=l,l=r.nextNode()}let d=t.createRange();if(a){let m=a.parentElement?.closest('strong[data-seg="completed"]');m&&m!==n&&n.contains(m)?c===0?d.setStartBefore(m):c===a.data.length?d.setStartAfter(m):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),m=d<a.length-1?d+1:0;this.store.set({activeDropdownIndex:a[m]});break}case"ArrowUp":{if(t.activeDropdownIndex<0){if(!c)break;let d=se(e.target,t),m=!!t.editingParam;if(!d&&!m)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((m,h)=>m.is_tappable?h:-1).filter(m=>m!==-1);if(l.length===0)break;if(!t.isDropdownOpen){if(t.actionableSuggestions.length===0)break;e.preventDefault();let m=e.shiftKey?l[l.length-1]:l[0];this.store.set({pillTapped:!0,activeDropdownIndex:m});break}e.preventDefault();let p=l.indexOf(t.activeDropdownIndex),d;if(p<0)d=e.shiftKey?l.length-1:0;else{let m=e.shiftKey?-1:1;d=(p+m+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(f=>f.type!=="placeholder"),o=i[0],r=o?e.optionOverrides?.[o.type]:void 0,s=n.suggestions.filter(f=>f.type==="placeholder").map(f=>f.text).join(" "),a=I(n.text,Math.min(n.filterBase,n.text.length),s),l=n.lastRawQuery!==""||a>0?E(n.text,a,n.filterInProgress):"",p=o?r?r(l.trim()):o.options??[]:[],d=n.editingParam!=null&&n.editingAnchor!=null,m;if(d&&n.editingParam&&n.editingAnchor!=null){let f=n.editingParam.id,u=n.completedParams.some(v=>v.id===f),g=n.caretOffset??n.editingAnchor,y=u?"":n.text.slice(n.editingAnchor,g);m=w(n.editingParam.options,y)}else m=w(p,l);e.showNonTappableOptions===!1&&(m=m.filter(f=>f.is_tappable));let h;if(d)h=n.editingParam!=null&&(n.editingParam.options?.length??0)===0;else{let f=o?r?r(""):o.options??[]:[];h=o!=null&&f.length===0}let b=Te({inEditMode:d,filteredOptionsLength:m.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading,pillTapped:n.pillTapped,activePillHasNoOptions:h},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),x=b&&n.activeDropdownIndex>=0&&!!m[n.activeDropdownIndex]?.is_tappable;return{segments:t,actionableSuggestions:i,filteredOptions:m,placeholderText:s,isDropdownOpen:b,isActivePillSelected:x}}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=E(e,l,r),d=O(a.options,p);if(!d)return null;let m=d.text.toLowerCase(),h=e.toLowerCase().lastIndexOf(m),b=h>=0?h:Math.max(0,e.length-d.text.length),x=b+d.text.length,f=e.slice(b,x),g=x<e.length&&e[x]===" "?x+1:x,y={id:crypto.randomUUID(),placeholder:"",type:a.type,text:f,kind:d.kind,suggestionType:a.type,suggestionPlaceholder:a.text,options:a.options??[],metadata:d.metadata};return{patch:{text:e,completedParams:[...t,y],suggestions:i.filter(v=>v!==a),filterBase:g,newParamId:y.id,caretOffset:g,activeDropdownIndex:-1},caretPos:g}}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,m=e.slice(p,d),b=d<e.length&&e[d]===" "?d+1:d,x={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:m,kind:a.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:a.metadata},f=t.length,u=0;for(let y=0;y<t.length;y++){let v=e.indexOf(t[y].text,u);if(v!==-1){if(v>=b){f=y;break}u=v+t[y].text.length}}let g=[...t];return g.splice(f,0,x),{patch:{text:e,completedParams:g,newParamId:x.id,filterBase:b,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:b,activeDropdownIndex:-1},caretPos:b}}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(u=>u.text!==e.text).map(u=>u.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,m=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},b=t.completedParams.findIndex(u=>u.id===i.id),x=t.completedParams.filter(u=>u.id!==i.id),f=b>=0?Math.min(b,x.length):x.length;x.splice(f,0,h),this.deps.store.set({text:d,completedParams:x,newParamId:h.id,filterBase:m,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:m,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.deps.startSelectionAnimationTimer(),this.deps.scheduleSetCursor(m)}tryPromote(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let t=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,m=s&&p===t&&!r,h=["magicx-aia-pill"];o&&h.push("magicx-aia-pill--rounded"),m&&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,m)),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 m=Number.parseInt(c.dataset.aiaIndex??"-1",10);m>=0&&o(m)}):(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,m=a&&s.length>0,h=t.length>0,b=o&&(h||m||r);if(b?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"),!b)return;let x=n.querySelector(".aia-stack");x||(x=document.createElement("div"),x.className="aia-stack",x.style.setProperty("--aia-stack-space","8px"),n.appendChild(x));let f=m||r&&a,u=x.querySelector(".magicx-aia-pill-bar");f?(u||(u=document.createElement("div"),u.className="magicx-aia-pill-bar aia-cluster",u.setAttribute("data-nowrap",""),u.setAttribute("data-aia-pillbar",""),x.insertBefore(u,x.firstChild)),Y(u,s,0,d,!0,r,c)):u&&u.remove(),Ie(x,t,i,l,p,e.listboxId,r);let g=x.querySelector(".magicx-aia-skeleton-bars");if(r&&!h){if(!g){g=document.createElement("div"),g.className="magicx-aia-skeleton-bars",g.setAttribute("data-aia-skeleton-bars","");for(let T of dt){let A=document.createElement("span");A.className="magicx-aia-skeleton-bar",A.style.width=`${T}px`,g.appendChild(A)}x.appendChild(g)}}else g&&g.remove();let y=x.querySelector(".magicx-aia-footer")??ut(),v=i>=0&&!!t[i]?.is_tappable;pt(y,z(v,e.isInputEmpty)),x.lastElementChild!==y&&x.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(f=>`${f.type}:${f.value}`).join("\0"),l=e.dataset.segKey??"",p=e.dataset.newParamId??"",d=e.dataset.editingParamId??"";if(c===l&&(i??"")===p&&(o??"")===d)return;let m=s?C(e):null;e.dataset.segKey=c,e.dataset.newParamId=i??"",e.dataset.editingParamId=o??"";let h=e.ownerDocument??document,b=h.createDocumentFragment(),x=0;for(let f of t)if(x+=f.value.length,f.type==="completed"){let u=h.createElement("strong");u.dataset.seg="completed",u.dataset.paramId=f.param.id;let g=f.param.id===i,y=f.param.id===o,v=["magicx-aia-segment","magicx-aia-segment--completed"];g&&v.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),y&&v.push("magicx-aia-segment--editing"),u.className=v.join(" "),u.textContent=f.value,b.appendChild(u)}else b.appendChild(h.createTextNode(f.value));e.replaceChildren(b),e.dataset.aiaTextLength=String(x),m!=null&&P(e,Math.max(0,Math.min(m,x)))}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,m=!1,h=0,b=()=>{let u=L(s),y=u.length>0&&u[0]!==u[0].toUpperCase()?u[0].toUpperCase()+u.slice(1):u;e.handleChange(y)},x=()=>{let u=(s.ownerDocument??document).getSelection();if(!u||u.rangeCount===0)return null;let g=u.anchorNode;return!g||!s.contains(g)?null:(g.nodeType===Node.ELEMENT_NODE?g:g.parentElement)?.closest('strong[data-seg="completed"][data-param-id]')?.dataset.paramId??null};o.addEventListener("click",u=>{u.target?.closest("[data-aia-pill]")||s.focus()},{signal:d}),s.addEventListener("input",()=>{m||(h=performance.now(),b(),e.handleCaretAfterInput(C(s)))},{signal:d});let f=s.ownerDocument??document;if(f.addEventListener("selectionchange",()=>{let u=f.getSelection();if(!u||u.rangeCount===0||!s.contains(u.anchorNode))return;let g=x(),y=e.store.get().editingParam?.id??null;if(g&&g!==y){e.startEditingParam(g);return}performance.now()-h<50||e.handleCaretMove(C(s))},{signal:d}),s.addEventListener("compositionstart",()=>{m=!0},{signal:d}),s.addEventListener("compositionend",()=>{m=!1,b()},{signal:d}),s.addEventListener("beforeinput",u=>{let g=u,y=g.inputType;if(y==="insertParagraph"||y==="insertLineBreak"||y==="insertFromDrop"){u.preventDefault();return}if(y.startsWith("insert")||y.startsWith("delete")){let v=y.startsWith("delete")?"":g.data??"";e.replaceEditingRange(v)&&u.preventDefault()}},{signal:d}),s.addEventListener("paste",u=>{u.preventDefault();let g=(u.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!g)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 A=y.createTextNode(g);T.insertNode(A),T.setStartAfter(A),T.collapse(!0),v.removeAllRanges(),v.addRange(T),b()},{signal:d}),s.addEventListener("keydown",u=>e.handleKeyDown(u),{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",u=>{let g=e.store.get();if(!(!!g.text||g.completedParams.length>0)||!e.onSubmit)return;u.stopPropagation();let{rawQuery:v,completedParams:T}=S(g.text,g.completedParams);e.onSubmit({query:g.text.trim(),raw_query:v,completed_params:T}),e.afterSubmit?.()},{signal:d}),e.autoFocus!==!1){s.focus();let u=s.ownerDocument??document,g=u.getSelection(),y=g&&g.rangeCount>0&&s.contains(g.anchorNode);if(g&&!y){let v=u.createRange();v.selectNodeContents(s),v.collapse(!0),g.removeAllRanges(),g.addRange(v)}}if(typeof ResizeObserver<"u"){let u=new ResizeObserver(()=>ke(s,a));u.observe(s),p.signal.addEventListener("abort",()=>u.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 f=!!e.text||e.completedParams.length>0;s.disabled=!f}let m=i.dataset.newParamId??"",h=e.newParamId!==null&&e.newParamId!==m;if(ee({input:i,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused}),a==="inline"){let f=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;f||e.actionableSuggestions.length>0?Y(o,e.actionableSuggestions,0,c,!1,f,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 b=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:null,x=b??e.actionableSuggestions[0];Z(r,{suggestions:x?[{...x,options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation,listboxId:t.listboxId,pills:b?[b]:e.actionableSuggestions,showPills:a==="dropdown",isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,onSelect:l,onHighlight:f=>p.set({activeDropdownIndex:f}),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()),m=d>=0?p.slice(d,d+e.text.length):e.text,h={id:crypto.randomUUID(),placeholder:"",type:t.type,text:m,kind:e.kind,suggestionType:t.type,suggestionPlaceholder:t.text,options:t.options??[],metadata:e.metadata},b=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:b>0,inSelectionAnimation:!0},telemetry:{selectedOption:e.text,otherOptions:n.filteredOptions.filter(x=>x.text!==e.text).map(x=>x.text)},consumedSuggestion:t,remainingActionable:b}}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;
@@ -136,6 +136,7 @@
136
136
  border: 1px solid var(--aia-border, #b0b0b0);
137
137
  border-radius: 20px;
138
138
  background: var(--aia-surface, #ffffff);
139
+ box-shadow: var(--aia-shadow, none);
139
140
  overflow: hidden;
140
141
  display: flex;
141
142
  align-items: center;
@@ -264,6 +265,22 @@
264
265
  opacity: 0.85;
265
266
  }
266
267
 
268
+ /* Disabled (empty input) keeps the solid themed look by default \u2014 the disabled
269
+ tokens fall back to the enabled ones, so a consumer's themed color is never
270
+ washed out. Opt into a faded/dimmed rest state by setting
271
+ --aia-submit-bg-disabled / --aia-submit-color-disabled. */
272
+ .magicx-aia-submit:disabled {
273
+ background: var(
274
+ --aia-submit-bg-disabled,
275
+ var(--aia-submit-bg, var(--aia-color-text-default, #fff))
276
+ );
277
+ color: var(
278
+ --aia-submit-color-disabled,
279
+ var(--aia-submit-color, var(--aia-color-bg-default, #000))
280
+ );
281
+ cursor: default;
282
+ }
283
+
267
284
  /* --- Dropdown (glassmorphism \u2014 matches the React build) --- */
268
285
  .magicx-aia-dropdown {
269
286
  position: absolute;
@@ -271,7 +288,8 @@
271
288
  right: 0;
272
289
  top: 100%;
273
290
  max-width: 544px;
274
- margin-top: 6px;
291
+ /* Gap between the input box and the dropdown. Tunable via --aia-dropdown-offset. */
292
+ margin-top: var(--aia-dropdown-offset, 13px);
275
293
  display: flex;
276
294
  flex-direction: column;
277
295
  box-sizing: border-box;
@@ -355,19 +373,15 @@
355
373
  }
356
374
 
357
375
  /* --- Footer (keyboard hint + AI-Autocomplete branding) ---
358
- The footer insets its own 8px horizontally (no vertical padding \u2014 the 8px
359
- section gap above and its own 8px gap provide the vertical rhythm), so the
360
- divider spans the full footer width yet still stays clear of the dropdown's
361
- rounded edges. */
376
+ The footer insets its own 8px horizontally so it stays clear of the
377
+ dropdown's rounded edges. The top inset (--aia-footer-gap) adds breathing
378
+ room above the hint/branding row so the footer doesn't butt against the last
379
+ option row \u2014 additive to the dropdown's 8px section gap. */
362
380
  .magicx-aia-footer {
363
381
  display: flex;
364
382
  flex-direction: column;
365
383
  gap: 8px;
366
- padding: 0 8px;
367
- }
368
-
369
- .magicx-aia-footer-divider {
370
- border-top: 1px solid var(--aia-footer-divider, rgba(176, 176, 176, 0.4));
384
+ padding: var(--aia-footer-gap, 8px) 8px 0;
371
385
  }
372
386
 
373
387
  .magicx-aia-footer-key {
@@ -423,10 +437,9 @@
423
437
  }
424
438
 
425
439
  /* Mobile footer variant (Figma "Mobile"): on phone-width viewports drop the
426
- keyboard hint ("tab to select" is meaningless on touch) and its divider,
427
- leaving only the AI-Autocomplete brand pinned to the right. */
440
+ keyboard hint ("tab to select" is meaningless on touch), leaving only the
441
+ AI-Autocomplete brand pinned to the right. */
428
442
  @media (max-width: 768px) {
429
- .magicx-aia-footer-divider,
430
443
  .magicx-aia-footer-hint-group {
431
444
  display: none;
432
445
  }
@@ -943,7 +956,11 @@
943
956
  :where(.magicx-aia),
944
957
  :where(.magicx-aia[data-mode="light"]) {
945
958
  --aia-surface: var(--aia-primitive-neutral-1000);
946
- --aia-border: var(--aia-primitive-neutral-700);
959
+ --aia-border: rgba(17, 24, 39, 0.14); /* subtle slate hairline (off-palette) */
960
+ /* Elevation for the input container (.magicx-aia-input-wrapper). */
961
+ --aia-shadow:
962
+ inset 0 1px 0 rgba(255, 255, 255, 0.9), 0 1px 2px rgba(16, 24, 40, 0.1),
963
+ 0 8px 24px rgba(16, 24, 40, 0.16);
947
964
  --aia-dropdown-border: var(
948
965
  --aia-primitive-neutral-900
949
966
  ); /* was #e5e7eb \u2014 snapped to palette (\u03942) */
@@ -971,7 +988,6 @@
971
988
  --aia-streak-rgb: 99, 102, 241; /* off shared palette (indigo effect) */
972
989
  --aia-streak-glass-bg: rgba(99, 102, 241, 0.1);
973
990
 
974
- --aia-footer-divider: var(--aia-primitive-neutral-700-a40);
975
991
  --aia-footer-hint-color: var(--aia-primitive-neutral-500);
976
992
  --aia-footer-brand-color: var(--aia-primitive-neutral-700);
977
993
  --aia-footer-badge-border: var(--aia-primitive-neutral-750-a50);
@@ -981,6 +997,11 @@
981
997
  :where(.magicx-aia[data-mode="dark"]) {
982
998
  --aia-surface: var(--aia-primitive-neutral-0);
983
999
  --aia-border: var(--aia-primitive-neutral-500);
1000
+ /* Elevation for the input container (.magicx-aia-input-wrapper) \u2014 tuned for
1001
+ dark surfaces: a faint top highlight + deeper ambient shadows. */
1002
+ --aia-shadow:
1003
+ inset 0 1px 0 rgba(255, 255, 255, 0.06), 0 1px 2px rgba(0, 0, 0, 0.4),
1004
+ 0 8px 24px rgba(0, 0, 0, 0.5);
984
1005
  --aia-dropdown-border: var(
985
1006
  --aia-primitive-neutral-400
986
1007
  ); /* was #484848 \u2014 snapped to palette (\u03942) */
@@ -1008,7 +1029,6 @@
1008
1029
  --aia-streak-rgb: 255, 255, 255;
1009
1030
  --aia-streak-glass-bg: rgba(255, 255, 255, 0.1);
1010
1031
 
1011
- --aia-footer-divider: rgba(255, 255, 255, 0.15); /* off shared palette (no .15 step) */
1012
1032
  --aia-footer-hint-color: var(--aia-primitive-neutral-700);
1013
1033
  --aia-footer-brand-color: var(--aia-primitive-neutral-500);
1014
1034
  --aia-footer-badge-border: var(--aia-primitive-neutral-500);
@@ -1021,20 +1041,13 @@
1021
1041
  top: auto;
1022
1042
  bottom: 100%;
1023
1043
  margin-top: 0;
1024
- margin-bottom: 6px;
1044
+ margin-bottom: var(--aia-dropdown-offset, 13px);
1025
1045
  }
1026
1046
 
1027
1047
  :where(.magicx-aia[data-options-position="above"]) [data-aia-dropdown] .aia-stack {
1028
1048
  flex-direction: column-reverse;
1029
1049
  }
1030
1050
 
1031
- /* The footer sits at the top when the dropdown is above, so flip its own
1032
- internal stack too \u2014 the divider should sit BELOW the hint/branding row
1033
- (between the footer and the options beneath it), not above it. */
1034
- :where(.magicx-aia[data-options-position="above"]) [data-aia-dropdown] .magicx-aia-footer {
1035
- flex-direction: column-reverse;
1036
- }
1037
-
1038
1051
  /* Disable all animations when data-animations="off" */
1039
1052
  :where(.magicx-aia[data-animations="off"]) *,
1040
1053
  :where(.magicx-aia[data-animations="off"]) *::before,
@@ -1042,5 +1055,5 @@
1042
1055
  animation-duration: 0s !important;
1043
1056
  transition-duration: 0s !important;
1044
1057
  }
1045
- `;var ne=class{constructor(){this.listeners={}}on(e,t){let i=(...s)=>t(...s),r=this.listeners[e];return r||(r=new Set,this.listeners[e]=r),r.add(i),()=>{this.listeners[e]?.delete(i)}}emit(e,...t){let i=this.listeners[e];if(i)for(let r of i)r(...t)}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var ie=class{constructor(){this.timers=new Map}schedule(e,t,i){this.clear(e);let r=setTimeout(()=>{this.timers.delete(e),t()},i);this.timers.set(e,r)}clear(e){let t=this.timers.get(e);t!==void 0&&(clearTimeout(t),this.timers.delete(e))}clearAll(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};var M=class{constructor(e,t="auto",i){this.container=e;this.mode=t;this.onResolve=i;this.mediaQuery=null;this.onSystemChange=e=>{this.setResolved(e.matches?"dark":"light")};this.apply()}setMode(e){this.detachListener(),this.mode=e,this.apply()}destroy(){this.detachListener()}apply(){this.mode==="auto"?(this.mediaQuery??(this.mediaQuery=window.matchMedia("(prefers-color-scheme: dark)")),this.mediaQuery.addEventListener("change",this.onSystemChange),this.setResolved(this.mediaQuery.matches?"dark":"light")):this.setResolved(this.mode)}setResolved(e){this.container.dataset.mode=e,this.onResolve?.(e)}detachListener(){this.mediaQuery?.removeEventListener("change",this.onSystemChange)}};function ht(n){return(n??N).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function xt(n){return k(n)?`Bearer ${await _(n).getToken()}`:F(n)}async function He(n){try{let e=ht(n.apiConfig?.endpoint),t=H(n.apiConfig),i=await xt(n.apiConfig);i&&(t.Authorization=i);let r=JSON.stringify({source:n.source,session_id:n.sessionId,type:n.type,at:new Date().toISOString(),query_data:n.queryData});await fetch(e,{method:"POST",headers:t,body:r})}catch{}}var bt="newParam",Fe="suggestionRemoval",yt="selectionAnimation",vt=650,St=0;function Pt(){return`:ac-${++St}:`}var Be=500;function Ke(){return{text:"",completedParams:[],suggestions:[],activeDropdownIndex:-1,newParamId:null,isLoading:!1,isReady:!1,error:null,filterBase:0,filterInProgress:!1,pillTapped:!1,skipNextFetch:!1,lastRawQuery:"",isFocused:!1,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:null,inSelectionAnimation:!1}}var re=class{constructor(e,t={}){this.inputStore=te(Ke());this._listboxId=Pt();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new ie;this.emitter=new ne;this.sessionId=crypto.randomUUID();this.emitSubmit=e=>this.emitter.emit("submit",e);this.emitError=e=>this.emitter.emit("error",e);this.container=e,this.opts=t,this.renderMode=t.renderMode??"full",this.store=Ne(this.inputStore,i=>Ee(i,this.opts)),t.onSubmit&&this.emitter.on("submit",t.onSubmit),t.onError&&this.emitter.on("error",t.onError),t.onChange&&this.emitter.on("change",t.onChange),t.onParamsChange&&this.emitter.on("paramsChange",t.onParamsChange),t.onStateChange&&this.emitter.on("stateChange",t.onStateChange),t.onFocus&&this.emitter.on("focus",t.onFocus),t.onBlur&&this.emitter.on("blur",t.onBlur),t.value!==void 0&&this.store.set({text:t.value}),t.completedParams!==void 0&&this.store.set({completedParams:t.completedParams}),this.pillsController=new W(this.store,{onPillSelected:({rawQuery:i,selectedPill:r,otherPills:s})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:r,other_pills:s})}}),this.reEdit=new V({store:this.store,scheduleSetCursor:i=>this.scheduleSetCursor(i),fireTelemetry:(i,r)=>this.fireTelemetry(i,r),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer()}),this.fetchController=new B(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.emitter.hasListeners("error")?this.emitError:void 0,()=>this.sessionId,{onAutoMatch:({active:i,matched:r,rawQuery:s})=>{this.fireTelemetry("option",{raw_query:s,selected_option:r.text,other_options:(i.options??[]).filter(o=>o.text!==r.text).map(o=>o.text)})}}),this.keyboardController=new G(this.store,{columns:t.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.emitter.hasListeners("submit")?this.emitSubmit:void 0,getOptionsPosition:()=>this.opts.optionsPosition??"below",afterSubmit:this.renderMode==="full"?()=>this.reset():void 0,selectOption:i=>this.selectOption(i),removeParamAtCaret:i=>this.removeParamAtCaret(i),exitEditMode:()=>this.exitEditMode()}),this.unsubscribers.push(this.store.subscribe((i,r)=>{i.text!==r.text&&this.emitter.emit("change",i.text),i.completedParams!==r.completedParams&&this.emitter.emit("paramsChange",i.completedParams),i.isFocused!==r.isFocused&&(i.isFocused?this.emitter.emit("focus"):this.emitter.emit("blur")),this.emitter.emit("stateChange",i)})),this.unsubscribers.push(this.store.subscribe(()=>this.maybeExitReEditOnNoMatch())),this.renderMode!=="headless"&&(_e(),this.setupContainer()),this.renderMode==="full"?this.buildAndRenderFull():this.renderMode==="dropdown"&&this.buildAndRenderDropdown(),this.fetchController.start()}focus(){this.domRefs?.input.focus()}blur(){this.domRefs?.input.blur()}reset(){let e=this.store.get().isFocused;this.store.set({...Ke(),isFocused:e,skipNextFetch:!0}),this.sessionId=crypto.randomUUID(),this.fetchController.doFetch("",[])}destroy(){this.fetchController.dispose(),this.modeController?.destroy(),this.timers.clearAll(),this.emitter.clear();for(let e of this.unsubscribers)e();this.unsubscribers=[],this.domRefs?.abort.abort(),this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}setValue(e){this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e);let t=this.store.get().text.length;this.store.set({caretOffset:t,isFocused:!0}),this.scheduleSetCursor(t)}removeLastParam(){this.pillsController.removeLastParam()}removeParamAtCaret(e){let t=this.store.get(),{text:i,completedParams:r}=t,s=0;for(let o=0;o<r.length;o++){let a=r[o],c=i.indexOf(a.text,s);if(c===-1)continue;let l=c,p=c+a.text.length;if(e>l&&e<=p){let d=U(i,e),u=i.slice(0,d)+i.slice(e),h=r.filter((x,g)=>g!==o);return this.store.set(x=>({text:u,filterBase:Math.min(x.filterBase,u.length),completedParams:h,pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(d),!0}s=p}return!1}scheduleSetCursor(e){queueMicrotask(()=>{let t=this.domRefs;t?(t.input.focus(),P(t.input,e)):this.opts.setCursor?.(e)})}clearNewParamId(){this.store.set({newParamId:null})}startEditingParam(e){this.reEdit.start(e)}replaceEditingRange(e){return this.reEdit.replaceRange(e)}exitEditMode(){this.reEdit.exit()}handleCaretAfterInput(e){this.reEdit.caretAfterInput(e)}handleCaretMove(e){this.reEdit.caretMove(e)}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}handleTextChange(e){this.handleChange(e)}handleKeyDown(e){this.keyboardController.handleKeyDown(e)}setFocused(e){this.store.get().isFocused!==e&&this.store.set({isFocused:e})}subscribe(e){return this.store.subscribe(t=>e(t))}getState(){return this.store.get()}get listboxId(){return this._listboxId}get isReady(){return this.store.get().isReady}on(e,t){return this.emitter.on(e,t)}update(e){Object.assign(this.opts,e),e.mode!==void 0&&this.modeController?.setMode(e.mode),e.optionsPosition!==void 0&&(this.container.dataset.optionsPosition=e.optionsPosition),e.animations!==void 0&&(this.container.dataset.animations=e.animations?"on":"off"),e.pillPlacement!==void 0&&(this.container.dataset.pillPlacement=e.pillPlacement,this.store.set({})),(e.dropdownTrigger!==void 0||e.closeDropdownOnBlur!==void 0||e.showNonTappableOptions!==void 0)&&this.store.set({}),e.value!==void 0&&this.store.set({text:e.value}),e.completedParams!==void 0&&this.store.set({completedParams:e.completedParams})}selectOption(e){let t=this.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null){this.reEdit.selectOption(e);return}let i=Re(t,e);if(i&&(this.fireTelemetry("option",{raw_query:S(t.text,t.completedParams).rawQuery,selected_option:i.telemetry.selectedOption,other_options:i.telemetry.otherOptions}),this.store.set(i.patch),this.startSelectionAnimationTimer(),this.timers.clear(Fe),i.remainingActionable>0)){let r=i.consumedSuggestion;this.timers.schedule(Fe,()=>{this.store.set(s=>({suggestions:s.suggestions.filter(o=>o!==r)}))},Be)}}startSelectionAnimationTimer(){this.timers.schedule(yt,()=>this.store.set({inSelectionAnimation:!1}),Be)}fireTelemetry(e,t){let i=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");He({source:i,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}setupContainer(){this.container.classList.add("magicx-aia"),this.container.dataset.pillPlacement=this.renderMode==="dropdown"?"dropdown":this.opts.pillPlacement??"dropdown",this.container.dataset.optionsPosition=this.opts.optionsPosition??"below",this.container.dataset.animations=this.opts.animations??!0?"on":"off",this.modeController=new M(this.container,this.opts.mode??"auto")}buildAndRenderFull(){let e=this,t={store:this.store,listboxId:this.listboxId,get pillPlacement(){return e.opts.pillPlacement??"dropdown"},get onSubmit(){return e.emitter.hasListeners("submit")?e.emitSubmit:void 0},afterSubmit:()=>e.reset(),submitButton:this.opts.submitButton,autoFocus:this.opts.autoFocus??!0,selectOption:i=>this.selectOption(i),setActivePill:i=>this.pillsController.setActivePill(i),handleKeyDown:i=>this.keyboardController.handleKeyDown(i),handleChange:i=>this.handleChange(i),startEditingParam:i=>this.startEditingParam(i),handleCaretAfterInput:i=>this.handleCaretAfterInput(i),handleCaretMove:i=>this.handleCaretMove(i),replaceEditingRange:i=>this.replaceEditingRange(i)};this.domRefs=Le(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&de(this.domRefs,this.store.get(),t)}),de(this.domRefs,this.store.get(),t),this.subscribeNewParamTimer()}buildAndRenderDropdown(){let e={store:this.store,listboxId:this.listboxId,selectOption:t=>this.selectOption(t),setActivePill:t=>this.pillsController.setActivePill(t)};this.dropdownRefs=De(this.container,e),this.subscribeBatchedRender(()=>{this.dropdownRefs&&ce(this.dropdownRefs,this.store.get(),e)}),ce(this.dropdownRefs,this.store.get(),e),this.subscribeNewParamTimer()}subscribeBatchedRender(e){let t=!1;this.unsubscribers.push(this.store.subscribe(()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,t)=>{e.newParamId&&e.newParamId!==t.newParamId&&this.timers.schedule(bt,()=>this.store.set({newParamId:null}),vt)}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:r}=Pe(e,t.completedParams);r.length>0&&this.store.set({completedParams:i}),this.maybePromoteExactMatch(e)}maybeExitReEditOnNoMatch(){let e=this.store.get();if(!e.editingParam||e.editingAnchor==null||e.completedParams.some(a=>a.id===e.editingParam?.id))return;let t=e.caretOffset??e.editingAnchor,i=e.text.slice(e.editingAnchor,t);if(w(e.editingParam.options,i).some(a=>a.is_tappable))return;this.reEdit.exit();let{rawQuery:s,completedParams:o}=S(e.text,e.completedParams);this.fetchController.doFetch(s,o)}maybePromoteExactMatch(e){let t=this.store.get(),i=j({mode:"fresh",text:e,completedParams:t.completedParams,suggestions:t.suggestions,filterBase:t.filterBase,filterInProgress:t.filterInProgress});i&&this.store.set(i.patch)}};0&&(module.exports={AIAutocomplete,ModeController,buildQuery,createStore,cursorIsAtEnd,extractPlainText,getCursorOffset,getFooterHint,plainTextLength,previousGraphemeBoundary,renderEditableContent,setCursorOffset});
1058
+ `;var ne=class{constructor(){this.listeners={}}on(e,t){let i=(...r)=>t(...r),o=this.listeners[e];return o||(o=new Set,this.listeners[e]=o),o.add(i),()=>{this.listeners[e]?.delete(i)}}emit(e,...t){let i=this.listeners[e];if(i)for(let o of i)o(...t)}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var ie=class{constructor(){this.timers=new Map}schedule(e,t,i){this.clear(e);let o=setTimeout(()=>{this.timers.delete(e),t()},i);this.timers.set(e,o)}clear(e){let t=this.timers.get(e);t!==void 0&&(clearTimeout(t),this.timers.delete(e))}clearAll(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};var M=class{constructor(e,t="auto",i){this.container=e;this.mode=t;this.onResolve=i;this.mediaQuery=null;this.onSystemChange=e=>{this.setResolved(e.matches?"dark":"light")};this.apply()}setMode(e){this.detachListener(),this.mode=e,this.apply()}destroy(){this.detachListener()}apply(){this.mode==="auto"?(this.mediaQuery??(this.mediaQuery=window.matchMedia("(prefers-color-scheme: dark)")),this.mediaQuery.addEventListener("change",this.onSystemChange),this.setResolved(this.mediaQuery.matches?"dark":"light")):this.setResolved(this.mode)}setResolved(e){this.container.dataset.mode=e,this.onResolve?.(e)}detachListener(){this.mediaQuery?.removeEventListener("change",this.onSystemChange)}};function ht(n){return(n??N).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function xt(n){return k(n)?`Bearer ${await _(n).getToken()}`:F(n)}async function He(n){try{let e=ht(n.apiConfig?.endpoint),t=H(n.apiConfig),i=await xt(n.apiConfig);i&&(t.Authorization=i);let o=JSON.stringify({source:n.source,session_id:n.sessionId,type:n.type,at:new Date().toISOString(),query_data:n.queryData});await fetch(e,{method:"POST",headers:t,body:o})}catch{}}var bt="newParam",Fe="suggestionRemoval",yt="selectionAnimation",vt=650,St=0;function Pt(){return`:ac-${++St}:`}var Be=500;function Ke(){return{text:"",completedParams:[],suggestions:[],activeDropdownIndex:-1,newParamId:null,isLoading:!1,isReady:!1,error:null,filterBase:0,filterInProgress:!1,pillTapped:!1,skipNextFetch:!1,lastRawQuery:"",isFocused:!1,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:null,inSelectionAnimation:!1}}var oe=class{constructor(e,t={}){this.inputStore=te(Ke());this._listboxId=Pt();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new ie;this.emitter=new ne;this.sessionId=crypto.randomUUID();this.emitSubmit=e=>this.emitter.emit("submit",e);this.emitError=e=>this.emitter.emit("error",e);this.container=e,this.opts=t,this.renderMode=t.renderMode??"full",this.store=Ne(this.inputStore,i=>Ce(i,this.opts)),t.onSubmit&&this.emitter.on("submit",t.onSubmit),t.onError&&this.emitter.on("error",t.onError),t.onChange&&this.emitter.on("change",t.onChange),t.onParamsChange&&this.emitter.on("paramsChange",t.onParamsChange),t.onStateChange&&this.emitter.on("stateChange",t.onStateChange),t.onFocus&&this.emitter.on("focus",t.onFocus),t.onBlur&&this.emitter.on("blur",t.onBlur),t.value!==void 0&&this.store.set({text:t.value}),t.completedParams!==void 0&&this.store.set({completedParams:t.completedParams}),this.pillsController=new W(this.store,{onPillSelected:({rawQuery:i,selectedPill:o,otherPills:r})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:o,other_pills:r})}}),this.reEdit=new V({store:this.store,scheduleSetCursor:i=>this.scheduleSetCursor(i),fireTelemetry:(i,o)=>this.fireTelemetry(i,o),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer()}),this.fetchController=new B(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.emitter.hasListeners("error")?this.emitError:void 0,()=>this.sessionId,{onAutoMatch:({active:i,matched:o,rawQuery:r})=>{this.fireTelemetry("option",{raw_query:r,selected_option:o.text,other_options:(i.options??[]).filter(s=>s.text!==o.text).map(s=>s.text)})}}),this.keyboardController=new G(this.store,{columns:t.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.emitter.hasListeners("submit")?this.emitSubmit:void 0,getOptionsPosition:()=>this.opts.optionsPosition??"below",afterSubmit:this.renderMode==="full"?()=>this.reset():void 0,selectOption:i=>this.selectOption(i),removeParamAtCaret:i=>this.removeParamAtCaret(i),exitEditMode:()=>this.exitEditMode()}),this.unsubscribers.push(this.store.subscribe((i,o)=>{i.text!==o.text&&this.emitter.emit("change",i.text),i.completedParams!==o.completedParams&&this.emitter.emit("paramsChange",i.completedParams),i.isFocused!==o.isFocused&&(i.isFocused?this.emitter.emit("focus"):this.emitter.emit("blur")),this.emitter.emit("stateChange",i)})),this.unsubscribers.push(this.store.subscribe(()=>this.maybeExitReEditOnNoMatch())),this.renderMode!=="headless"&&(_e(),this.setupContainer()),this.renderMode==="full"?this.buildAndRenderFull():this.renderMode==="dropdown"&&this.buildAndRenderDropdown(),this.fetchController.start()}focus(){this.domRefs?.input.focus()}blur(){this.domRefs?.input.blur()}reset(){let e=this.store.get().isFocused;this.store.set({...Ke(),isFocused:e,skipNextFetch:!0}),this.sessionId=crypto.randomUUID(),this.fetchController.doFetch("",[])}destroy(){this.fetchController.dispose(),this.modeController?.destroy(),this.timers.clearAll(),this.emitter.clear();for(let e of this.unsubscribers)e();this.unsubscribers=[],this.domRefs?.abort.abort(),this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}setValue(e){this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e);let t=this.store.get().text.length;this.store.set({caretOffset:t,isFocused:!0}),this.scheduleSetCursor(t)}removeLastParam(){this.pillsController.removeLastParam()}removeParamAtCaret(e){let t=this.store.get(),{text:i,completedParams:o}=t,r=0;for(let s=0;s<o.length;s++){let a=o[s],c=i.indexOf(a.text,r);if(c===-1)continue;let l=c,p=c+a.text.length;if(e>l&&e<=p){let d=U(i,e),m=i.slice(0,d)+i.slice(e),h=o.filter((b,x)=>x!==s);return this.store.set(b=>({text:m,filterBase:Math.min(b.filterBase,m.length),completedParams:h,pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(d),!0}r=p}return!1}scheduleSetCursor(e){queueMicrotask(()=>{let t=this.domRefs;t?(t.input.focus(),P(t.input,e)):this.opts.setCursor?.(e)})}clearNewParamId(){this.store.set({newParamId:null})}startEditingParam(e){this.reEdit.start(e)}replaceEditingRange(e){return this.reEdit.replaceRange(e)}exitEditMode(){this.reEdit.exit()}handleCaretAfterInput(e){this.reEdit.caretAfterInput(e)}handleCaretMove(e){this.reEdit.caretMove(e)}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}handleTextChange(e){this.handleChange(e)}handleKeyDown(e){this.keyboardController.handleKeyDown(e)}setFocused(e){this.store.get().isFocused!==e&&this.store.set({isFocused:e})}subscribe(e){return this.store.subscribe(t=>e(t))}getState(){return this.store.get()}get listboxId(){return this._listboxId}get isReady(){return this.store.get().isReady}on(e,t){return this.emitter.on(e,t)}update(e){Object.assign(this.opts,e),e.mode!==void 0&&this.modeController?.setMode(e.mode),e.optionsPosition!==void 0&&(this.container.dataset.optionsPosition=e.optionsPosition),e.animations!==void 0&&(this.container.dataset.animations=e.animations?"on":"off"),e.pillPlacement!==void 0&&(this.container.dataset.pillPlacement=e.pillPlacement,this.store.set({})),(e.dropdownTrigger!==void 0||e.closeDropdownOnBlur!==void 0||e.showNonTappableOptions!==void 0)&&this.store.set({}),e.value!==void 0&&this.store.set({text:e.value}),e.completedParams!==void 0&&this.store.set({completedParams:e.completedParams})}selectOption(e){let t=this.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null){this.reEdit.selectOption(e);return}let i=Re(t,e);if(i&&(this.fireTelemetry("option",{raw_query:S(t.text,t.completedParams).rawQuery,selected_option:i.telemetry.selectedOption,other_options:i.telemetry.otherOptions}),this.store.set(i.patch),this.startSelectionAnimationTimer(),this.timers.clear(Fe),i.remainingActionable>0)){let o=i.consumedSuggestion;this.timers.schedule(Fe,()=>{this.store.set(r=>({suggestions:r.suggestions.filter(s=>s!==o)}))},Be)}}startSelectionAnimationTimer(){this.timers.schedule(yt,()=>this.store.set({inSelectionAnimation:!1}),Be)}fireTelemetry(e,t){let i=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");He({source:i,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}setupContainer(){this.container.classList.add("magicx-aia"),this.container.dataset.pillPlacement=this.renderMode==="dropdown"?"dropdown":this.opts.pillPlacement??"dropdown",this.container.dataset.optionsPosition=this.opts.optionsPosition??"below",this.container.dataset.animations=this.opts.animations??!0?"on":"off",this.modeController=new M(this.container,this.opts.mode??"auto")}buildAndRenderFull(){let e=this,t={store:this.store,listboxId:this.listboxId,get pillPlacement(){return e.opts.pillPlacement??"dropdown"},get onSubmit(){return e.emitter.hasListeners("submit")?e.emitSubmit:void 0},afterSubmit:()=>e.reset(),submitButton:this.opts.submitButton,autoFocus:this.opts.autoFocus??!0,selectOption:i=>this.selectOption(i),setActivePill:i=>this.pillsController.setActivePill(i),handleKeyDown:i=>this.keyboardController.handleKeyDown(i),handleChange:i=>this.handleChange(i),startEditingParam:i=>this.startEditingParam(i),handleCaretAfterInput:i=>this.handleCaretAfterInput(i),handleCaretMove:i=>this.handleCaretMove(i),replaceEditingRange:i=>this.replaceEditingRange(i)};this.domRefs=Le(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&de(this.domRefs,this.store.get(),t)}),de(this.domRefs,this.store.get(),t),this.subscribeNewParamTimer()}buildAndRenderDropdown(){let e={store:this.store,listboxId:this.listboxId,selectOption:t=>this.selectOption(t),setActivePill:t=>this.pillsController.setActivePill(t)};this.dropdownRefs=De(this.container,e),this.subscribeBatchedRender(()=>{this.dropdownRefs&&ce(this.dropdownRefs,this.store.get(),e)}),ce(this.dropdownRefs,this.store.get(),e),this.subscribeNewParamTimer()}subscribeBatchedRender(e){let t=!1;this.unsubscribers.push(this.store.subscribe(()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,t)=>{e.newParamId&&e.newParamId!==t.newParamId&&this.timers.schedule(bt,()=>this.store.set({newParamId:null}),vt)}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:o}=Pe(e,t.completedParams);o.length>0&&this.store.set({completedParams:i}),this.maybePromoteExactMatch(e)}maybeExitReEditOnNoMatch(){let e=this.store.get();if(!e.editingParam||e.editingAnchor==null||e.completedParams.some(a=>a.id===e.editingParam?.id))return;let t=e.caretOffset??e.editingAnchor,i=e.text.slice(e.editingAnchor,t);if(w(e.editingParam.options,i).some(a=>a.is_tappable))return;this.reEdit.exit();let{rawQuery:r,completedParams:s}=S(e.text,e.completedParams);this.fetchController.doFetch(r,s)}maybePromoteExactMatch(e){let t=this.store.get(),i=j({mode:"fresh",text:e,completedParams:t.completedParams,suggestions:t.suggestions,filterBase:t.filterBase,filterInProgress:t.filterInProgress});i&&this.store.set(i.patch)}};0&&(module.exports={AIAutocomplete,ModeController,buildQuery,createStore,cursorIsAtEnd,extractPlainText,getCursorOffset,getFooterHint,plainTextLength,previousGraphemeBoundary,renderEditableContent,setCursorOffset});
1046
1059
  //# sourceMappingURL=index.js.map