@magicx-eng/ai-autocomplete-vanilla 0.7.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +139 -2
- package/dist/index.d.mts +169 -8
- package/dist/index.d.ts +169 -8
- package/dist/index.js +219 -15
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +219 -15
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var N=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",_=`${Je}/api/suggest`,he=new WeakMap;function D(n){return n?.type==="accessToken"}function Ze(n){if(!(!n||D(n)))return n}function F(n){let e=he.get(n.getAccessToken);return e||(e=new N(n),he.set(n.getAccessToken,e)),e}function H(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function B(n){let e=Ze(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}var be="skipped";function M(n,e){if(e.length===0)return n;let t=new Set(n.map(r=>r.type)),i=e.filter(r=>!t.has(r.type)).map(r=>({placeholder:"",type:r.type,text:be,kind:null}));return i.length>0?[...n,...i]:n}var et="0.7.0",xe=!1;function tt(){return crypto.randomUUID()}function nt(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.text},kind:n.kind}}function it(n,e,t,i,r,o,s){let a=e.find(l=>l.type==="contact"&&l.metadata?.contact_account_count)?.metadata?.contact_account_count,d=typeof a=="number"?a:void 0;return{data:{raw_query:n,completed_params:M(e.map(l=>nt(l,t)),s??[]),...r&&r.length>0&&{identified_params:r.map(l=>({type:l.type,value:l.text}))},...o&&o.length>0&&{recently_suggested:o},...d!=null&&{contact_account_count:d}},meta:{request_id:tt(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:et,session_id:i}}}async function Se(n,e,t,i,r){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:r})}async function ye(n,e,t){let i=t.apiConfig,r=!t.maskCompletedText,o=it(n,e,r,t.sessionId,t.identifiedParams,t.recentlySuggested,t.skippedParams),s=H(i),a=i?.endpoint??_,d=JSON.stringify(o);if(D(i)){let c=F(i),u=await c.getToken(),f=await Se(a,s,u,d,t.signal);if(f.status===401){let h=await c.getToken(!0);f=await Se(a,s,h,d,t.signal)}if(!f.ok)throw new Error(`API error: ${f.status} ${f.statusText}`);return f.json()}let l=B(i);!l&&!xe&&(xe=!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:d,signal:t.signal});if(!p.ok)throw new Error(`API error: ${p.status} ${p.statusText}`);return p.json()}function v(n,e){let t=n,i={},r=[],o=[],s=0;for(let a of e){let d=(i[a.type]??0)+1;i[a.type]=d;let p=`{{${a.type.toUpperCase().replace(/\s+/g,"_")}_${d}}}`,c=f=>{let h=t.indexOf(a.text,f);for(;h!==-1&&o.some(b=>h<b.end&&h+a.text.length>b.start);)h=t.indexOf(a.text,h+1);return h},u=c(s);if(u===-1&&(u=c(0)),u!==-1){t=t.slice(0,u)+p+t.slice(u+a.text.length);let f=p.length-a.text.length;for(let h of o)h.start>=u+a.text.length&&(h.start+=f,h.end+=f);o.push({start:u,end:u+p.length}),s=u>=s?u+p.length:s+f}r.push({...a,placeholder:p})}return{rawQuery:t,completedParams:r}}function T(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function E(n,e,t){let i=n.slice(e);if(t||e===0||n[e-1]===" ")return i;let r=i.indexOf(" ");return r===-1?"":i.slice(r+1)}function Pe(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 o=0;o<i.length;o++){let s=i.slice(o).join(" ");if(r.startsWith(s.toLowerCase())){let a=t.length-s.length;return n.length-a}}return 0}function I(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 ve(n,e){return e?n.map(t=>{let i=e[t.type];return i?{...t,options:i("")}:t}):n}function Ce(n,e){let t=0,i=e;for(let r of n)t+=r.value.length,r.type!=="text"&&(i=Math.max(i,t));return i}function we(n,e){let t=0;for(let i of n){let r=t+i.value.length;if(i.type==="text"&&r>e&&i.value.slice(Math.max(e-t,0)).trim().length>0)return!1;t=r}return!0}function Te(n,e){let t=[],i=new Set;for(let r of[...n,...e])r.type==="placeholder"||i.has(r.type)||(i.add(r.type),t.push({type:r.type,text:r.text}));return t}function Ee(n,e,t){if(n===e)return t;let i=Math.min(n.length,e.length),r=0;for(;r<i&&n[r]===e[r];)r++;if(r>=t)return t;let o=0;for(;o<i-r&&n[n.length-1-o]===e[e.length-1-o];)o++;return n.length-o<=t?t+(e.length-n.length):null}function ne(n,e){let t=[],i=[],r=0;for(let o of e){let s=n.indexOf(o.text,r);if(s===-1){i.push(o);continue}t.push({start:s,end:s+o.text.length,param:o}),r=s+o.text.length}return{located:t,missing:i}}function Ie(n,e,t){let i=[],r=[],o=0;for(let s of t){let a=n.indexOf(s.text,o);for(;a!==-1&&e.some(d=>a<d.end&&a+s.text.length>d.start);)a=n.indexOf(s.text,a+1);if(a===-1){r.push(s);continue}i.push({start:a,end:a+s.text.length,param:s}),o=a+s.text.length}return{located:i,missing:r}}function Ae(n,e,t=[]){let i=ne(n,e).located,r=Ie(n,i,t).located,o=[...i.map(l=>({start:l.start,end:l.end,segment:{type:"completed",value:l.param.text,param:l.param}})),...r.map(l=>({start:l.start,end:l.end,segment:{type:"identified",value:l.param.text,param:l.param}}))].sort((l,p)=>l.start-p.start),s=[],a=0;for(let l of o)l.start>a&&s.push({type:"text",value:n.slice(a,l.start)}),s.push(l.segment),a=l.end;let d=n.slice(a);return d&&s.push({type:"text",value:d}),s}function Oe(n,e){let{located:t,missing:i}=ne(n,e);return{valid:t.map(r=>r.param),invalid:i}}function K(n,e,t){let i=ne(n,e).located,{located:r,missing:o}=Ie(n,i,t);return{valid:r.map(s=>s.param),invalid:o}}var rt=100,ot=300,st=2,U=class{constructor(e,t,i,r,o,s,a={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=r;this.getOnError=o;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 r=++this.fetchVersion,o=this.store.get().text.length;this.store.set({isLoading:!0,error:null});try{let s=this.store.get(),a=s.pendingSpan?Te(s.pendingSpan.snapshot,s.actionableSuggestions):void 0,d=await ye(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig(),identifiedParams:s.identifiedParams,recentlySuggested:a,skippedParams:s.skippedParams});if(r!==this.fetchVersion)return;let l=(d.data.input??[]).filter(x=>x.source==="identified").map(x=>({id:crypto.randomUUID(),type:x.type,text:x.text})),p=ve(d.data.suggestions??[],this.getOptionOverrides()),c=d.data.input??[],u=c[c.length-1],f=this.store.get().text,h,b;if(u?.state==="in_progress"){b=!0;let x=f.toLowerCase().lastIndexOf(u.text.toLowerCase());h=x!==-1?x:o}else b=!1,h=o;let m=p.filter(x=>x.type!=="placeholder")[0],g=null;if(m){let x=E(f,h,b),S=O(m.options,x);S&&(g={id:crypto.randomUUID(),placeholder:"",type:m.type,text:S.text,kind:S.kind,suggestionType:m.type,suggestionPlaceholder:m.text,options:m.options??[],metadata:S.metadata},p=p.filter(P=>P!==m),this.callbacks.onAutoMatch?.({active:m,matched:S,rawQuery:e}))}this.store.set(x=>{let S=g?[...x.completedParams,g]:x.completedParams,P=K(x.text,S,l).valid;return{suggestions:p,isLoading:!1,isReady:d.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:h,filterInProgress:b,identifiedParams:P,...g?{completedParams:S}:{}}})}catch(s){if(r===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 r=this.store.get();if(!r.text&&r.completedParams.length===0)return this.doFetch("",[]),!0;let o=r.suggestions.filter(g=>g.type==="placeholder").map(g=>g.text).join(" "),s=T(r.text,r.filterBase,o),a=E(r.text,s,r.filterInProgress),l=r.suggestions.filter(g=>g.type!=="placeholder")[0],c=(l?I(l.options,a):[]).filter(g=>g.is_tappable),u=l?O(l.options,a)!==null:!1,f=a.trim().length>0;if(c.length>0&&!u&&f||r.completedParams.length===0&&r.text.length>0&&o.length>0&&o.toLowerCase().startsWith(r.text.toLowerCase()))return!1;let{rawQuery:h,completedParams:b}=v(r.text,r.completedParams),y=h.length<r.lastRawQuery.length,m=Math.abs(h.length-r.lastRawQuery.length);return y||m>=i?(this.doFetch(h,b),!0):!1};this.debounceTimer=setTimeout(()=>{t(st)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},rt),this.slowDebounceTimer=setTimeout(()=>t(1),ot)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var De='[contenteditable="false"]',k;function at(){if(k!==void 0)return k;let n=globalThis.Intl.Segmenter;if(!n)return k=null,null;try{k=new n(void 0,{granularity:"grapheme"})}catch{k=null}return k??null}function $(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(De))return!0;t=t.parentNode}return!1}function Q(n){return(n.ownerDocument??document).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return $(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function q(n){let e=Q(n),t="",i=e.nextNode();for(;i;)t+=i.data,i=e.nextNode();return t}function ie(n){let e=Q(n),t=0,i=e.nextNode();for(;i;)t+=i.data.length,i=e.nextNode();return t}function w(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($(r,n)&&r!==n)return null;let o=0;for(let s=0;s<i&&s<r.childNodes.length;s++)o+=Me(r.childNodes[s],n);return o+ke(r,n)}return t.nodeType!==Node.TEXT_NODE||$(t,n)?null:ke(t,n)+i}function Me(n,e){if(n.nodeType===Node.TEXT_NODE)return $(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(De))return 0;let i=0;for(let r of Array.from(t.childNodes))i+=Me(r,e);return i}function ke(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 C(n,e){let t=n.ownerDocument??document,i=t.getSelection();if(!i)return;let r=Math.max(0,Math.min(e,ie(n))),o=Q(n),s=0,a=null,d=0,l=o.nextNode(),p=null;for(;l;){let u=l.data.length;if(r<s+u){a=l,d=r-s;break}if(r===s+u){let f=o.nextNode();f?(a=f,d=0):(a=l,d=u);break}s+=u,p=l,l=o.nextNode()}let c=t.createRange();if(a){let u=a.parentElement?.closest('strong[data-seg="completed"]');u&&u!==n&&n.contains(u)?d===0?c.setStartBefore(u):d===a.data.length?c.setStartAfter(u):c.setStart(a,d):c.setStart(a,d)}else p?c.setStart(p,p.data.length):c.setStart(n,0);c.collapse(!0),i.removeAllRanges(),i.addRange(c)}function re(n){let e=w(n);return e==null?!1:e>=ie(n)}function oe(n,e){if(e<=0)return 0;let t=at();if(!t)return e-1;let i=n.slice(0,e),r=0;for(let{index:o}of t.segment(i))o<e&&(r=o);return r}function L(n,e,t=[]){let{rawQuery:i,completedParams:r}=v(n,e);return{query:n.trim(),raw_query:i,completed_params:M(r,t)}}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")?re(n):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function lt(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?w(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,o=this.getEffectiveColumns(),s=r(),a=this.getTappableIndices(o);if((e.shiftKey||e.metaKey||e.ctrlKey||e.altKey)&&(e.key==="ArrowDown"||e.key==="ArrowUp"||e.key==="ArrowLeft"||e.key==="ArrowRight"))return;let d=this.ctx.getOptionsPosition()==="above";switch(e.key){case"ArrowDown":{let l=se(e.target,t),p=!!t.editingParam;if(!l&&!p&&t.activeDropdownIndex<0)break;if(t.activeDropdownIndex<0){if(d)break;if(e.preventDefault(),!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:a[0]??0});break}if(a.length===0)return;this.store.set({activeDropdownIndex:a[0]});break}if(e.preventDefault(),a.length===0)return;if(t.filteredOptions.length>0){let f=Math.floor((t.filteredOptions.length-1)/o);if(Math.floor(t.activeDropdownIndex/o)===f){this.store.set({activeDropdownIndex:-1});break}}let c=a.indexOf(t.activeDropdownIndex),u=c<a.length-1?c+1:0;this.store.set({activeDropdownIndex:a[u]});break}case"ArrowUp":{if(t.activeDropdownIndex<0){if(!d)break;let c=se(e.target,t),u=!!t.editingParam;if(!c&&!u)break;e.preventDefault();let f=this.firstTappableInBottomRow(o)??a[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:f});break}if(a.length===0)return;this.store.set({activeDropdownIndex:f});break}if(a.length===0)break;if(e.preventDefault(),t.activeDropdownIndex<o){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%o<o-1){let c=t.activeDropdownIndex+1;c<t.filteredOptions.length&&t.filteredOptions[c]?.is_tappable&&this.store.set({activeDropdownIndex:c})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let p=e.target.closest("[data-aia-input]")??e.target,c=t.editingTail;this.ctx.exitEditMode?.(),C(p,c);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%o>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?.(),C(l,p);break}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let l=lt(e.target);if(l==null)break;this.ctx.removeParamAtCaret(l)&&e.preventDefault();break}case"Enter":{e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable?this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i):s&&(s(L(t.text,t.completedParams,t.skippedParams)),this.ctx.afterSubmit?.());break}case"Tab":{let l=t.filteredOptions.map((u,f)=>u.is_tappable?f:-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),c;if(p<0)c=e.shiftKey?l.length-1:0;else{let u=e.shiftKey?-1:1;c=(p+u+l.length)%l.length}this.store.set({activeDropdownIndex:l[c]});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?.(),C(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 o=r;o<t.filteredOptions.length;o++)if(t.filteredOptions[o]?.is_tappable)return o;return null}getTappableIndices(e){let i=this.store.get().filteredOptions.map((o,s)=>o.is_tappable?s:-1).filter(o=>o!==-1),r=Array.from({length:e},()=>[]);for(let o of i)r[o%e].push(o);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 o=r.split(" ").filter(Boolean).length;if(o>0)return o}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(a=>a.type==="placeholder"),i=e.suggestions.filter(a=>a.type!=="placeholder");if(i.length===0)return;let r=i[0],o=i.slice(1),s=e.skippedParams.some(a=>a.type===r.type);this.store.set({suggestions:[...t,...o],pillTapped:o.length>0,activeDropdownIndex:-1,...s?{}:{skippedParams:[...e.skippedParams,{id:crypto.randomUUID(),type:r.type,suggestionPlaceholder:r.text}]}}),o.length===0&&this.ctx.fetchNow?.()}};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],o=i.filter((l,p)=>p!==e),s=t.suggestions.filter(l=>l.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:l}=v(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:l,selectedPill:r.text,otherPills:o.map(p=>p.text)})}let a=[...s,r,...o],d=this.store.peek({suggestions:a}).filteredOptions.findIndex(l=>l.is_tappable);this.store.set({suggestions:a,pillTapped:!0,activeDropdownIndex:d})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};function Le(n,e){let t=e.dropdownTrigger??"auto",i=e.closeDropdownOnBlur??!0,o=n.filteredOptionsLength>0||n.activePillHasNoOptions;if(n.inEditMode){let s=i?n.isFocused:!0;return o&&s}if(t==="auto"){let s=i?n.isFocused:!0,a=n.text.replace(/\s+$/,"").length,d=n.caretOffset==null||n.caretOffset>=a;return(o||n.isLoading)&&s&&d}return t==="manual"?(o||n.isLoading)&&n.pillTapped:!1}function Re(n,e){let t=Ae(n.text,n.completedParams,n.identifiedParams),i=n.suggestions.filter(g=>g.type!=="placeholder"),r=i[0],o=r?e.optionOverrides?.[r.type]:void 0,s=n.suggestions.filter(g=>g.type==="placeholder").map(g=>g.text).join(" "),a=T(n.text,Math.min(n.filterBase,n.text.length),s),l=n.lastRawQuery!==""||a>0?E(n.text,a,n.filterInProgress):"",p=r?o?o(l.trim()):r.options??[]:[],c=n.editingParam!=null&&n.editingAnchor!=null,u;if(c&&n.editingParam&&n.editingAnchor!=null){let g=n.editingParam.id,x=n.completedParams.some(A=>A.id===g),S=n.caretOffset??n.editingAnchor,P=x?"":n.text.slice(n.editingAnchor,S);u=I(n.editingParam.options,P)}else u=I(p,l);let f=e.showNonTappableOptions===!1;f&&(u=u.filter(g=>g.is_tappable));let h=g=>f?g.is_tappable:!0,b;if(c){let g=n.editingParam?.options??[];b=n.editingParam!=null&&g.filter(h).length===0}else{let g=r?o?o(""):r.options??[]:[];b=r!=null&&g.filter(h).length===0}let y=Le({inEditMode:c,filteredOptionsLength:u.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading,pillTapped:n.pillTapped,activePillHasNoOptions:b},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),m=y&&n.activeDropdownIndex>=0&&!!u[n.activeDropdownIndex]?.is_tappable;return{segments:t,actionableSuggestions:i,filteredOptions:u,placeholderText:s,isDropdownOpen:y,isActivePillSelected:m}}function j(n){return n.mode==="fresh"?dt(n):ct(n)}function dt(n){let{text:e,completedParams:t,suggestions:i,filterBase:r,filterInProgress:o}=n,a=i.filter(S=>S.type!=="placeholder")[0];if(!a?.options)return null;let d=i.filter(S=>S.type==="placeholder").map(S=>S.text).join(" "),l=T(e,r,d),p=E(e,l,o),c=O(a.options,p);if(!c)return null;let u=c.text.toLowerCase(),f=e.toLowerCase().lastIndexOf(u),h=f>=0?f:Math.max(0,e.length-c.text.length),b=h+c.text.length,y=e.slice(h,b),g=b<e.length&&e[b]===" "?b+1:b,x={id:crypto.randomUUID(),placeholder:"",type:a.type,text:y,kind:c.kind,suggestionType:a.type,suggestionPlaceholder:a.text,options:a.options??[],metadata:c.metadata};return{patch:{text:e,completedParams:[...t,x],suggestions:i.filter(S=>S!==a),filterBase:g,newParamId:x.id,caretOffset:g,activeDropdownIndex:-1},caretPos:g}}function ct(n){let{text:e,completedParams:t,editingParam:i,editingAnchor:r,editingTail:o}=n;if(t.some(x=>x.id===i.id))return null;let s=e.slice(r,o),a=O(i.options,s);if(!a)return null;let d=a.text.toLowerCase(),l=s.toLowerCase().lastIndexOf(d),p=r+Math.max(0,l),c=p+a.text.length,u=e.slice(p,c),h=c<e.length&&e[c]===" "?c+1:c,b={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:u,kind:a.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:a.metadata},y=t.length,m=0;for(let x=0;x<t.length;x++){let S=e.indexOf(t[x].text,m);if(S!==-1){if(S>=h){y=x;break}m=S+t[x].text.length}}let g=[...t];return g.splice(y,0,b),{patch:{text:e,completedParams:g,newParamId:b.id,filterBase:h,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:h,activeDropdownIndex:-1},caretPos:h}}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 r=0,o=-1;for(let s of t.completedParams){let a=t.text.indexOf(s.text,r);if(a!==-1){if(s.id===e){o=a;break}r=a+s.text.length}}o<0||this.deps.store.set({editingParam:i,editingAnchor:o,editingTail:o+i.text.length,caretOffset:o+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,o=t.editingTail;if(!i||r==null||o==null||!t.completedParams.some(d=>d.id===i.id))return!1;let s=t.text.slice(0,r)+e+t.text.slice(o),a=r+e.length;return this.deps.store.set(d=>({text:s,completedParams:d.completedParams.filter(l=>l.id!==i.id),editingTail:a,caretOffset:a,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(a),this.tryPromote(),!0}caretAfterInput(e){let t=this.deps.store.get(),i={caretOffset:e};t.editingParam&&t.editingAnchor!=null&&e!=null&&(e<t.editingAnchor?(i.editingParam=null,i.editingAnchor=null,i.editingTail=null,i.activeDropdownIndex=-1):t.editingTail!=null&&(i.editingTail=Math.max(t.editingTail,e))),this.deps.store.set(i),this.tryPromote()}caretMove(e){let t=this.deps.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null&&e!=null&&(e<t.editingAnchor||e>t.editingTail)){this.deps.store.set({caretOffset:e,editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1});return}this.deps.store.set({caretOffset:e})}selectOption(e){let t=this.deps.store.get(),i=t.editingParam,r=t.editingAnchor,o=t.editingTail;if(!i||r==null||o==null)return;this.deps.fireTelemetry("option",{raw_query:v(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:i.options.filter(m=>m.text!==e.text).map(m=>m.text)});let s=t.text.slice(0,r),a=t.text.slice(o),d=r===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,l=a.length===0||a[0]!==" ",p=l?`${d} `:d,c=s+p+a,u=r+p.length+(l?0:1),f={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:d,kind:e.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:e.metadata},h=t.completedParams.findIndex(m=>m.id===i.id),b=t.completedParams.filter(m=>m.id!==i.id),y=h>=0?Math.min(h,b.length):b.length;b.splice(y,0,f),this.deps.store.set({text:c,completedParams:b,newParamId:f.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))}};var Ne="https://ai-autocomplete.com";function ae(n=Ne){try{if(typeof window>"u"||!window.location)return n;let e=window.location.hostname;if(!e)return n;let t=new URL(n);return t.searchParams.set("utm_source",e),t.toString()}catch{return n}}function le(n,e){return n?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}var _e="data-aia-key";function X(n,e,t){let i=new Map;for(let s of Array.from(n.children)){let a=s.getAttribute(_e);a!=null&&i.set(a,s)}let r=new Set,o=[];for(let s=0;s<e.length;s++){let a=e[s],d=t.keyOf(a,s);r.add(d);let l=i.get(d);l||(l=t.create(a,s),l.setAttribute(_e,d)),t.update?.(l,a,s),n.children[s]!==l&&n.insertBefore(l,n.children[s]??null),o.push(l)}for(let[s,a]of i)r.has(s)||a.remove();return o}var Fe=[125,69];function He(n,e){return e?1:n===0?.7:n===1?.4:.2}function z(n,e,t,i,r=!1,o=!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)),o&&e.length===0){a.setAttribute("data-aia-pill-list-loading",""),a.innerHTML="";for(let d=0;d<Fe.length;d++){let l=Fe[d],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(He(d,!1)),a.appendChild(p)}return}o?a.setAttribute("data-aia-pill-list-loading",""):a.removeAttribute("data-aia-pill-list-loading");for(let d of a.querySelectorAll("[data-aia-pill-skeleton]"))d.remove();X(a,e,{keyOf:d=>`${d.type}-${d.text}`,create:d=>{let l=document.createElement("button");return l.type="button",l.tabIndex=-1,l.setAttribute("data-aia-pill",""),l.setAttribute("contenteditable","false"),l.textContent=d.text,l.addEventListener("mousedown",p=>p.preventDefault()),l},update:(d,l,p)=>{let c=d,u=s&&p===t&&!o,f=["magicx-aia-pill"];r&&f.push("magicx-aia-pill--rounded"),o&&f.push("magicx-aia-pill--skeleton"),c.className=f.join(" "),c.style.width="",c.style.opacity=String(He(p,u)),o?(c.setAttribute("data-aia-loading",""),c.disabled=!0,c.onclick=null):(c.removeAttribute("data-aia-loading"),c.disabled=!1,c.onclick=()=>i(p))}})}function de(n){n.querySelector(".magicx-aia-pill-list")?.remove()}function Be(n,e,t,i,r,o,s,a=""){let d=n.querySelector(".aia-grid");if(e.length===0){d?.remove();return}d||(d=document.createElement("div"),d.className="aia-grid magicx-aia-grid",d.setAttribute("data-scroll",""),d.style.setProperty("--aia-grid-min","250px"),d.style.setProperty("--aia-grid-max","1fr"),d.style.setProperty("--aia-grid-gap","0"),n.appendChild(d)),ut(d,e,t,i,r,o,s),pt(d,a)}function pt(n,e){n.dataset.aiaGroup!==e&&(n.dataset.aiaGroup=e,n.scrollTop=0)}function ut(n,e,t,i,r,o,s){let a=s?"1":"0";X(n,e,{keyOf:d=>`${d.text}\0${a}`,create:d=>mt(d,s),update:(d,l,p)=>{let c=p===t&&!s;d.id=`${o}-option-${p}`,d.dataset.aiaIndex=String(p),d.setAttribute("aria-selected",String(c)),d.classList.toggle("magicx-aia-option--highlighted",c),!s&&l.is_tappable?(d.onclick=()=>{d.classList.add("magicx-aia-option--pressed"),i(l),setTimeout(()=>d.classList.remove("magicx-aia-option--pressed"),500)},d.onmouseenter=()=>{let u=Number.parseInt(d.dataset.aiaIndex??"-1",10);u>=0&&r(u)}):(d.onclick=null,d.onmouseenter=null)}})}function mt(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 o=document.createElement("div");o.className="magicx-aia-streaks-vert",t.appendChild(o);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 d=document.createElement("span");d.className="magicx-aia-option-tag",d.textContent=n.tag,s.appendChild(d)}return t.appendChild(s),t}var gt=[159,119,164];function Y(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 J(n,e){let{filteredOptions:t,activeIndex:i,isOpen:r,isLoading:o,pills:s,showPills:a,isActivePillSelected:d,onSelect:l,onHighlight:p,onPillClick:c}=e,u=a&&s.length>0,f=t.length>0,h=r&&(f||u||o);if(h?n.classList.add("magicx-aia-dropdown--visible"):n.classList.remove("magicx-aia-dropdown--visible"),o?n.setAttribute("data-aia-loading",""):n.removeAttribute("data-aia-loading"),!h)return;let b=n.querySelector(".aia-stack");b||(b=document.createElement("div"),b.className="aia-stack",b.style.setProperty("--aia-stack-space","8px"),n.appendChild(b));let y=u||o&&a,m=b.querySelector(".magicx-aia-pill-bar");y?(m||(m=document.createElement("div"),m.className="magicx-aia-pill-bar aia-cluster",m.setAttribute("data-nowrap",""),m.setAttribute("data-aia-pillbar",""),b.insertBefore(m,b.firstChild)),z(m,s,0,c,!0,o,d)):m&&m.remove();let g=e.suggestions[0],x=g?`${g.type} ${g.text}`:"";Be(b,t,i,l,p,e.listboxId,o,x);let S=b.querySelector(".magicx-aia-skeleton-bars");if(o&&!f){if(!S){S=document.createElement("div"),S.className="magicx-aia-skeleton-bars",S.setAttribute("data-aia-skeleton-bars","");for(let Ye of gt){let te=document.createElement("span");te.className="magicx-aia-skeleton-bar",te.style.width=`${Ye}px`,S.appendChild(te)}b.appendChild(S)}}else S&&S.remove();let P=b.querySelector(".magicx-aia-footer")??ht(),A=i>=0&&!!t[i]?.is_tappable;ft(P,le(A,e.isInputEmpty)),b.lastElementChild!==P&&b.appendChild(P)}function ft(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 ht(){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 r=document.createElement("span");r.className="magicx-aia-footer-hint",r.textContent="to select",t.append(i,r);let o=document.createElement("a");o.className="aia-cluster magicx-aia-footer-brand-link",o.setAttribute("data-align","center"),o.href=ae(),o.target="_blank",o.rel="noopener noreferrer",o.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",o.append(s,a),e.append(t,o),n.append(e),n}function Ke(n,e){let t=Y(e.listboxId);return n.appendChild(t),{dropdown:t}}function ce(n,e,t){J(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 pe(n){let{input:e,segments:t,newParamId:i,editingParamId:r,placeholderText:o,isFocused:s}=n,a=t.length===0;e.dataset.aiaEmpty=a?"true":"false",a&&o?e.dataset.placeholder=o:delete e.dataset.placeholder;let d=t.map(y=>`${y.type}:${y.value}`).join("\0"),l=e.dataset.segKey??"",p=e.dataset.newParamId??"",c=e.dataset.editingParamId??"";if(d===l&&(i??"")===p&&(r??"")===c)return;let u=s?w(e):null;e.dataset.segKey=d,e.dataset.newParamId=i??"",e.dataset.editingParamId=r??"";let f=e.ownerDocument??document,h=f.createDocumentFragment(),b=0;for(let y of t)if(b+=y.value.length,y.type==="completed"){let m=f.createElement("strong");m.dataset.seg="completed",m.dataset.paramId=y.param.id;let g=y.param.id===i,x=y.param.id===r,S=["magicx-aia-segment","magicx-aia-segment--completed"];g&&S.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),x&&S.push("magicx-aia-segment--editing"),m.className=S.join(" "),m.textContent=y.value,h.appendChild(m)}else if(y.type==="identified"){let m=f.createElement("strong");m.dataset.seg="identified",m.dataset.paramId=y.param.id,m.className="magicx-aia-segment magicx-aia-segment--completed",m.textContent=y.value,h.appendChild(m)}else h.appendChild(f.createTextNode(y.value));e.replaceChildren(h),e.dataset.aiaTextLength=String(b),u!=null&&C(e,Math.max(0,Math.min(u,b)))}var bt='<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 Ue(){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=bt,n}function xt(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function $e(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 Qe(n,e){let{listboxId:t}=e,i=Y(t);n.appendChild(i);let r=document.createElement("div");r.className="magicx-aia-input-wrapper",n.appendChild(r);let o=document.createElement("div");o.className="magicx-aia-editor",o.setAttribute("data-aia-editor",""),r.appendChild(o);let s=document.createElement("div");s.className="magicx-aia-input",s.setAttribute("data-aia-input",""),s.setAttribute("contenteditable",xt()?"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"),o.appendChild(s);let a=document.createElement("span");a.className="magicx-aia-pill-list-container",a.setAttribute("data-aia-pill-list-container",""),o.appendChild(a);let d=null,l=null;e.submitButton===void 0?(d=Ue(),r.appendChild(d),l=d):e.submitButton!==null&&(l=e.submitButton,l.hasAttribute("data-aia-submit")||l.setAttribute("data-aia-submit",""),r.appendChild(l));let p=new AbortController,{signal:c}=p,u=!1,f=0,h=()=>{let m=q(s),x=m.length>0&&m[0]!==m[0].toUpperCase()?m[0].toUpperCase()+m.slice(1):m;e.handleChange(x)},b=()=>{let m=(s.ownerDocument??document).getSelection();if(!m||m.rangeCount===0)return null;let g=m.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};r.addEventListener("click",m=>{m.target?.closest("[data-aia-pill]")||s.focus()},{signal:c}),s.addEventListener("input",()=>{u||(f=performance.now(),h(),e.handleCaretAfterInput(w(s)))},{signal:c});let y=s.ownerDocument??document;if(y.addEventListener("selectionchange",()=>{let m=y.getSelection();if(!m||m.rangeCount===0||!s.contains(m.anchorNode))return;let g=b(),x=e.store.get().editingParam?.id??null;if(g&&g!==x){e.startEditingParam(g);return}performance.now()-f<50||e.handleCaretMove(w(s))},{signal:c}),s.addEventListener("compositionstart",()=>{u=!0},{signal:c}),s.addEventListener("compositionend",()=>{u=!1,h()},{signal:c}),s.addEventListener("beforeinput",m=>{let g=m,x=g.inputType;if(x==="insertParagraph"||x==="insertLineBreak"||x==="insertFromDrop"){m.preventDefault();return}if(x.startsWith("insert")||x.startsWith("delete")){let S=x.startsWith("delete")?"":g.data??"";e.replaceEditingRange(S)&&m.preventDefault()}},{signal:c}),s.addEventListener("paste",m=>{m.preventDefault();let g=(m.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!g)return;let x=s.ownerDocument??document,S=x.getSelection();if(!S||S.rangeCount===0)return;let P=S.getRangeAt(0);if(!s.contains(P.startContainer))return;P.deleteContents();let A=x.createTextNode(g);P.insertNode(A),P.setStartAfter(A),P.collapse(!0),S.removeAllRanges(),S.addRange(P),h()},{signal:c}),s.addEventListener("keydown",m=>e.handleKeyDown(m),{signal:c}),s.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:c}),s.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:c}),l&&l.addEventListener("click",m=>{let g=e.store.get();!(g.text||g.completedParams.length>0)||!e.onSubmit||(m.stopPropagation(),e.onSubmit(L(g.text,g.completedParams,g.skippedParams)),e.afterSubmit?.())},{signal:c}),e.autoFocus!==!1){s.focus();let m=s.ownerDocument??document,g=m.getSelection(),x=g&&g.rangeCount>0&&s.contains(g.anchorNode);if(g&&!x){let S=m.createRange();S.selectNodeContents(s),S.collapse(!0),g.removeAllRanges(),g.addRange(S)}}if(typeof ResizeObserver<"u"){let m=new ResizeObserver(()=>$e(s,a));m.observe(s),p.signal.addEventListener("abort",()=>m.disconnect(),{once:!0})}return{input:s,inlinePillContainer:a,dropdown:i,submitButton:d,abort:p}}function ue(n,e,t){let{input:i,inlinePillContainer:r,dropdown:o,submitButton:s}=n,{pillPlacement:a,setActivePill:d,selectOption:l,store:p}=t;i.setAttribute("aria-expanded",String(e.isDropdownOpen));let c=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(c?i.setAttribute("aria-activedescendant",c):i.removeAttribute("aria-activedescendant"),s){let y=!!e.text||e.completedParams.length>0;s.disabled=!y}let u=i.dataset.newParamId??"",f=e.newParamId!==null&&e.newParamId!==u;if(pe({input:i,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused}),a==="inline"){let y=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;y||e.actionableSuggestions.length>0?z(r,e.actionableSuggestions,0,d,!1,y,e.isActivePillSelected):de(r)}else de(r);$e(i,r),f?(i.focus(),C(i,e.caretOffset??e.text.length)):e.isFocused&&q(i)!==e.text&&C(i,e.text.length);let h=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:null,b=h??e.actionableSuggestions[0];J(o,{suggestions:b?[{...b,options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation,listboxId:t.listboxId,pills:h?[h]:e.actionableSuggestions,showPills:a==="dropdown",isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,onSelect:l,onHighlight:y=>p.set({activeDropdownIndex:y}),onPillClick:d})}function qe(n,e){let t=n.actionableSuggestions[0];if(!t)return null;let i=n.filterBase,r=n.text.slice(0,i),o=r.length===0&&n.text.length===0,s=r.length===0&&n.text.length>0&&n.placeholderText.length>0&&n.placeholderText.toLowerCase().startsWith(n.text.toLowerCase());(o||s)&&n.placeholderText&&(r=`${n.placeholderText} `);let a=Pe(r,e.text);a>0&&(r=r.slice(0,r.length-a));let d=r.length>0&&r[r.length-1]!==" ",l=`${r}${d?" ":""}${e.text} `,p=(o||s)&&l.length>0?l[0].toUpperCase()+l.slice(1):l,c=p.toLowerCase().lastIndexOf(e.text.toLowerCase()),u=c>=0?p.slice(c,c+e.text.length):e.text,f={id:crypto.randomUUID(),placeholder:"",type:t.type,text:u,kind:e.kind,suggestionType:t.type,suggestionPlaceholder:t.text,options:t.options??[],metadata:e.metadata},h=n.actionableSuggestions.length-1;return{patch:{text:p,filterBase:p.length,completedParams:[...n.completedParams,f],newParamId:f.id,caretOffset:p.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:h>0,inSelectionAnimation:!0,pendingSpan:null},telemetry:{selectedOption:e.text,otherOptions:n.filteredOptions.filter(b=>b.text!==e.text).map(b=>b.text)},consumedSuggestion:t,remainingActionable:h}}function me(n){let e=n,t=new Set,i=[],r=!1;return{get:()=>e,set:o=>{let s=typeof o=="function"?o(e):o,a=e;if(e={...e,...s},i.push([e,a]),!r){r=!0;try{let d=0;for(let l=i.shift();l;l=i.shift()){if(++d>1e4)throw i.length=0,new Error("createStore: notifications did not settle after 10000 deliveries \u2014 a listener is likely calling set() on every notification");let[p,c]=l;for(let u of t)u(p,c)}}catch(d){throw i.length=0,d}finally{r=!1}}},subscribe:o=>(t.add(o),()=>{t.delete(o)})}}function Ge(n,e){let t,i,r=o=>(o!==t&&(t=o,i=e(o)),i);return{get:()=>{let o=n.get();return{...o,...r(o)}},set:o=>{typeof o=="function"?n.set(s=>{let a={...s,...r(s)};return o(a)}):n.set(o)},peek:o=>{let s={...n.get(),...o};return{...s,...e(s)}},subscribe:o=>n.subscribe((s,a)=>{let d={...a,...r(a)},l={...s,...r(s)};o(l,d)})}}var ge=!1;function We(){if(ge||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){ge=!0;return}ge=!0;let n=document.createElement("style");n.setAttribute("data-magicx-aia",""),n.textContent=St,document.head.appendChild(n)}var St=`@layer layout {
|
|
1
|
+
var _=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 st="https://api.ai-autocomplete.com",H=`${st}/api/suggest`,ve=new WeakMap;function L(i){return i?.type==="accessToken"}function at(i){if(!(!i||L(i)))return i}function F(i){let e=ve.get(i.getAccessToken);return e||(e=new _(i),ve.set(i.getAccessToken,e)),e}function B(i){return{"Content-Type":"application/json",...i?.appIdentifier&&{"X-App-Identifier":i.appIdentifier},...i?.headers}}function K(i){let e=at(i),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}var Ce="skipped";function M(i,e){if(e.length===0)return i;let t=new Set(i.map(r=>r.type)),n=e.filter(r=>!t.has(r.type)).map(r=>({placeholder:"",type:r.type,text:Ce,kind:null}));return n.length>0?[...i,...n]:i}var lt="0.9.0",we=!1;function dt(){return crypto.randomUUID()}function ct(i,e){return{placeholder:i.placeholder,type:i.type,...e&&{text:i.text},kind:i.kind}}function pt(i,e,t,n,r,o,a){let s=e.find(l=>l.type==="contact"&&l.metadata?.contact_account_count)?.metadata?.contact_account_count,d=typeof s=="number"?s:void 0;return{data:{raw_query:i,completed_params:M(e.map(l=>ct(l,t)),a??[]),...r&&r.length>0&&{identified_params:r.map(l=>({type:l.type,value:l.text}))},...o&&o.length>0&&{recently_suggested:o},...d!=null&&{contact_account_count:d}},meta:{request_id:dt(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:lt,session_id:n}}}async function Ee(i,e,t,n,r){return fetch(i,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:n,signal:r})}async function Te(i,e,t){let n=t.apiConfig,r=!t.maskCompletedText,o=pt(i,e,r,t.sessionId,t.identifiedParams,t.recentlySuggested,t.skippedParams),a=B(n),s=n?.endpoint??H,d=JSON.stringify(o);if(L(n)){let p=F(n),u=await p.getToken(),f=await Ee(s,a,u,d,t.signal);if(f.status===401){let h=await p.getToken(!0);f=await Ee(s,a,h,d,t.signal)}if(!f.ok)throw new Error(`API error: ${f.status} ${f.statusText}`);return f.json()}let l=K(n);!l&&!we&&(we=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),l&&(a.Authorization=l);let c=await fetch(s,{method:"POST",headers:a,body:d,signal:t.signal});if(!c.ok)throw new Error(`API error: ${c.status} ${c.statusText}`);return c.json()}function v(i,e){let t=i,n={},r=[],o=[],a=0;for(let s of e){let d=(n[s.type]??0)+1;n[s.type]=d;let c=`{{${s.type.toUpperCase().replace(/\s+/g,"_")}_${d}}}`,p=f=>{let h=t.indexOf(s.text,f);for(;h!==-1&&o.some(y=>h<y.end&&h+s.text.length>y.start);)h=t.indexOf(s.text,h+1);return h},u=p(a);if(u===-1&&(u=p(0)),u!==-1){t=t.slice(0,u)+c+t.slice(u+s.text.length);let f=c.length-s.text.length;for(let h of o)h.start>=u+s.text.length&&(h.start+=f,h.end+=f);o.push({start:u,end:u+c.length}),a=u>=a?u+c.length:a+f}r.push({...s,placeholder:c})}return{rawQuery:t,completedParams:r}}function T(i,e,t){return e>0||!t?e:i.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function U(i,e,t){return e===0&&i.length>0&&t.length>0&&t.toLowerCase().startsWith(i.toLowerCase())}function A(i,e,t){let n=i.slice(e);if(t||e===0||i[e-1]===" ")return n;let r=n.indexOf(" ");return r===-1?"":n.slice(r+1)}function Ae(i,e){let t=i.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let n=t.split(" "),r=e.toLowerCase();for(let o=0;o<n.length;o++){let a=n.slice(o).join(" ");if(r.startsWith(a.toLowerCase())){let s=t.length-a.length;return i.length-s}}return 0}function I(i,e){if(!i)return[];let t=e.trimStart();if(!t)return i;let n=t.toLowerCase();return i.filter(r=>!r.is_tappable||r.text.toLowerCase().includes(n))}function O(i,e){if(!i)return null;let t=e.trim();if(!t)return null;let n=t.toLowerCase();return i.find(r=>r.is_tappable&&r.text.toLowerCase()===n)??null}function Ie(i,e){return e?i.map(t=>{let n=e[t.type];if(!n)return t;let r=n("");return r?{...t,options:r}:t}):i}function Oe(i,e){let t=0,n=e;for(let r of i)t+=r.value.length,r.type!=="text"&&(n=Math.max(n,t));return n}function ke(i,e){let t=0;for(let n of i){let r=t+n.value.length;if(n.type==="text"&&r>e&&n.value.slice(Math.max(e-t,0)).trim().length>0)return!1;t=r}return!0}function De(i,e){let t=[],n=new Set;for(let r of[...i,...e])r.type==="placeholder"||n.has(r.type)||(n.add(r.type),t.push({type:r.type,text:r.text}));return t}function Le(i,e,t){if(i===e)return t;let n=Math.min(i.length,e.length),r=0;for(;r<n&&i[r]===e[r];)r++;if(r>=t)return t;let o=0;for(;o<n-r&&i[i.length-1-o]===e[e.length-1-o];)o++;return i.length-o<=t?t+(e.length-i.length):null}function se(i,e){let t=[],n=[],r=0;for(let o of e){let a=i.indexOf(o.text,r);if(a===-1){n.push(o);continue}t.push({start:a,end:a+o.text.length,param:o}),r=a+o.text.length}return{located:t,missing:n}}function Me(i,e,t){let n=[],r=[],o=0;for(let a of t){let s=i.indexOf(a.text,o);for(;s!==-1&&e.some(d=>s<d.end&&s+a.text.length>d.start);)s=i.indexOf(a.text,s+1);if(s===-1){r.push(a);continue}n.push({start:s,end:s+a.text.length,param:a}),o=s+a.text.length}return{located:n,missing:r}}function Re(i,e,t=[]){let n=se(i,e).located,r=Me(i,n,t).located,o=[...n.map(l=>({start:l.start,end:l.end,segment:{type:"completed",value:l.param.text,param:l.param}})),...r.map(l=>({start:l.start,end:l.end,segment:{type:"identified",value:l.param.text,param:l.param}}))].sort((l,c)=>l.start-c.start),a=[],s=0;for(let l of o)l.start>s&&a.push({type:"text",value:i.slice(s,l.start)}),a.push(l.segment),s=l.end;let d=i.slice(s);return d&&a.push({type:"text",value:d}),a}function Ne(i,e){let{located:t,missing:n}=se(i,e);return{valid:t.map(r=>r.param),invalid:n}}function $(i,e,t){let n=se(i,e).located,{located:r,missing:o}=Me(i,n,t);return{valid:r.map(a=>a.param),invalid:o}}function ut(i){if(i instanceof Error)return i;try{return new Error(String(i))}catch{return new Error("Unknown error")}}var mt=100,gt=300,ft=2,q=class{constructor(e,t,n,r,o,a,s={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=n;this.getMaskCompletedText=r;this.getOnError=o;this.getSessionId=a;this.callbacks=s;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null}start(){this.doFetch("",[]);let e=this.store.get().text,t=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(n=>{(n.text!==e||n.completedParams!==t)&&(e=n.text,t=n.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let n=new AbortController;this.abortController=n;let r=++this.fetchVersion,o=this.store.get().text.length;try{this.callbacks.onRequest?.({query:this.store.get().text,signal:n.signal,isCurrent:()=>r===this.fetchVersion})}catch{}try{this.store.set({isLoading:!0,error:null});let a=this.store.get(),s=a.pendingSpan?De(a.pendingSpan.snapshot,a.actionableSuggestions):void 0,d=await Te(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:n.signal,apiConfig:this.getApiConfig(),identifiedParams:a.identifiedParams,recentlySuggested:s,skippedParams:a.skippedParams});if(r!==this.fetchVersion)return;let l=(d.data.input??[]).filter(x=>x.source==="identified").map(x=>({id:crypto.randomUUID(),type:x.type,text:x.text})),c=Ie(d.data.suggestions??[],this.getOptionOverrides()),p=d.data.input??[],u=p[p.length-1],f=this.store.get().text,h,y;if(u?.state==="in_progress"){y=!0;let x=f.toLowerCase().lastIndexOf(u.text.toLowerCase());h=x!==-1?x:o}else y=!1,h=o;let g=c.filter(x=>x.type!=="placeholder")[0],m=null;if(g){let x=A(f,h,y),S=O(g.options,x);S&&(m={id:crypto.randomUUID(),placeholder:"",type:g.type,text:S.text,kind:S.kind,suggestionType:g.type,suggestionPlaceholder:g.text,options:g.options??[],metadata:S.metadata},c=c.filter(P=>P!==g),this.callbacks.onAutoMatch?.({active:g,matched:S,rawQuery:e}))}this.store.set(x=>{let S=m?[...x.completedParams,m]:x.completedParams,P=$(x.text,S,l).valid;return{suggestions:c,isLoading:!1,isReady:d.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:h,filterInProgress:y,identifiedParams:P,...m?{completedParams:S}:{}}})}catch(a){let s=ut(a);r===this.fetchVersion&&(this.store.set({error:s,isLoading:!1}),this.getOnError()?.(s))}finally{if(r===this.fetchVersion&&this.store.get().isLoading)try{this.store.set({isLoading:!1})}catch{}}}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}let t=n=>{let r=this.store.get();if(!r.text&&r.completedParams.length===0)return this.doFetch("",[]),!0;let o=r.suggestions.filter(m=>m.type==="placeholder").map(m=>m.text).join(" "),a=T(r.text,r.filterBase,o),s=A(r.text,a,r.filterInProgress),l=r.suggestions.filter(m=>m.type!=="placeholder")[0],p=(l?I(l.options,s):[]).filter(m=>m.is_tappable),u=l?O(l.options,s)!==null:!1,f=s.trim().length>0;if(p.length>0&&!u&&f||U(r.text,r.completedParams.length,o))return!1;let{rawQuery:h,completedParams:y}=v(r.text,r.completedParams),b=h.length<r.lastRawQuery.length,g=Math.abs(h.length-r.lastRawQuery.length);return b||g>=n?(this.doFetch(h,y),!0):!1};this.debounceTimer=setTimeout(()=>{t(ft)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},mt),this.slowDebounceTimer=setTimeout(()=>t(1),gt)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var He='[contenteditable="false"]',k;function ht(){if(k!==void 0)return k;let i=globalThis.Intl.Segmenter;if(!i)return k=null,null;try{k=new i(void 0,{granularity:"grapheme"})}catch{k=null}return k??null}function Q(i,e){let t=i;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(He))return!0;t=t.parentNode}return!1}function G(i){return(i.ownerDocument??document).createTreeWalker(i,NodeFilter.SHOW_TEXT,{acceptNode(e){return Q(e,i)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function W(i){let e=G(i),t="",n=e.nextNode();for(;n;)t+=n.data,n=e.nextNode();return t}function ae(i){let e=G(i),t=0,n=e.nextNode();for(;n;)t+=n.data.length,n=e.nextNode();return t}function w(i){let e=(i.ownerDocument??document).getSelection();if(!e||e.rangeCount===0)return null;let t=e.anchorNode,n=e.anchorOffset;if(!t||!i.contains(t))return null;if(t.nodeType===Node.ELEMENT_NODE){let r=t;if(Q(r,i)&&r!==i)return null;let o=0;for(let a=0;a<n&&a<r.childNodes.length;a++)o+=Fe(r.childNodes[a],i);return o+_e(r,i)}return t.nodeType!==Node.TEXT_NODE||Q(t,i)?null:_e(t,i)+n}function Fe(i,e){if(i.nodeType===Node.TEXT_NODE)return Q(i,e)?0:i.data.length;if(i.nodeType!==Node.ELEMENT_NODE)return 0;let t=i;if(t.matches(He))return 0;let n=0;for(let r of Array.from(t.childNodes))n+=Fe(r,e);return n}function _e(i,e){let t=G(e),n=0,r=t.nextNode();for(;r;){if(r===i||i.nodeType===Node.ELEMENT_NODE&&i.contains(r))return n;n+=r.data.length,r=t.nextNode()}return n}function C(i,e){let t=i.ownerDocument??document,n=t.getSelection();if(!n)return;let r=Math.max(0,Math.min(e,ae(i))),o=G(i),a=0,s=null,d=0,l=o.nextNode(),c=null;for(;l;){let u=l.data.length;if(r<a+u){s=l,d=r-a;break}if(r===a+u){let f=o.nextNode();f?(s=f,d=0):(s=l,d=u);break}a+=u,c=l,l=o.nextNode()}let p=t.createRange();if(s){let u=s.parentElement?.closest('strong[data-seg="completed"]');u&&u!==i&&i.contains(u)?d===0?p.setStartBefore(u):d===s.data.length?p.setStartAfter(u):p.setStart(s,d):p.setStart(s,d)}else c?p.setStart(c,c.data.length):p.setStart(i,0);p.collapse(!0),n.removeAllRanges(),n.addRange(p)}function le(i){let e=w(i);return e==null?!1:e>=ae(i)}function de(i,e){if(e<=0)return 0;let t=ht();if(!t)return e-1;let n=i.slice(0,e),r=0;for(let{index:o}of t.segment(n))o<e&&(r=o);return r}function R(i,e,t=[]){let{rawQuery:n,completedParams:r}=v(i,e);return{query:i.trim(),raw_query:n,completed_params:M(r,t)}}function ce(i,e){return i instanceof HTMLTextAreaElement||i instanceof HTMLInputElement?i.selectionStart!=null&&i.selectionStart===i.value.length:i instanceof HTMLElement&&i.hasAttribute("data-aia-input")?le(i):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function pe(i){return i instanceof HTMLElement&&i.hasAttribute("data-aia-input")?w(i):null}var j=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:n,getOnSubmit:r}=this.ctx,o=this.getEffectiveColumns(),a=r(),s=this.getTappableIndices(o);if((e.shiftKey||e.metaKey||e.ctrlKey||e.altKey)&&(e.key==="ArrowDown"||e.key==="ArrowUp"||e.key==="ArrowLeft"||e.key==="ArrowRight"))return;let d=this.ctx.getOptionsPosition()==="above";switch(e.key){case"ArrowDown":{let l=ce(e.target,t),c=!!t.editingParam;if(!l&&!c&&t.activeDropdownIndex<0)break;if(t.activeDropdownIndex<0){if(d)break;if(e.preventDefault(),!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:s[0]??0});break}if(s.length===0)return;this.store.set({activeDropdownIndex:s[0]});break}if(e.preventDefault(),s.length===0)return;if(t.filteredOptions.length>0){let f=Math.floor((t.filteredOptions.length-1)/o);if(Math.floor(t.activeDropdownIndex/o)===f){this.store.set({activeDropdownIndex:-1});break}}let p=s.indexOf(t.activeDropdownIndex),u=p<s.length-1?p+1:0;this.store.set({activeDropdownIndex:s[u]});break}case"ArrowUp":{if(t.activeDropdownIndex<0){if(!d)break;let p=ce(e.target,t),u=!!t.editingParam;if(!p&&!u)break;e.preventDefault();let f=this.firstTappableInBottomRow(o)??s[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:f});break}if(s.length===0)return;this.store.set({activeDropdownIndex:f});break}if(s.length===0)break;if(e.preventDefault(),t.activeDropdownIndex<o){this.store.set({activeDropdownIndex:-1});break}let l=s.indexOf(t.activeDropdownIndex),c=l>0?l-1:s.length-1;this.store.set({activeDropdownIndex:s[c]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%o<o-1){let p=t.activeDropdownIndex+1;p<t.filteredOptions.length&&t.filteredOptions[p]?.is_tappable&&this.store.set({activeDropdownIndex:p})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let c=e.target.closest("[data-aia-input]")??e.target,p=t.editingTail;this.ctx.exitEditMode?.(),C(c,p);break}ce(e.target,t)&&t.actionableSuggestions.length>=1&&(e.preventDefault(),this.removeActivePill());break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%o>0){let l=t.activeDropdownIndex-1;l>=0&&t.filteredOptions[l]?.is_tappable&&this.store.set({activeDropdownIndex:l});break}if(!t.editingParam&&this.ctx.startEditingParamAtCaret){let l=pe(e.target);l!=null&&this.ctx.startEditingParamAtCaret(l)}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let l=e.target.closest("[data-aia-input]")??e.target,c=t.editingAnchor;this.ctx.exitEditMode?.(),C(l,c);break}if(this.ctx.startEditingParamAtCaret){let l=pe(e.target);l!=null&&this.ctx.startEditingParamAtCaret(l)&&e.preventDefault()}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let l=pe(e.target);if(l==null)break;this.ctx.removeParamAtCaret(l)&&e.preventDefault();break}case"Enter":{e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable?this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,n):a&&a(R(t.text,t.completedParams,t.skippedParams))&&this.ctx.afterSubmit?.();break}case"Tab":{let l=t.filteredOptions.map((u,f)=>u.is_tappable?f:-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 c=l.indexOf(t.activeDropdownIndex),p;if(c<0)p=e.shiftKey?l.length-1:0;else{let u=e.shiftKey?-1:1;p=(c+u+l.length)%l.length}this.store.set({activeDropdownIndex:l[p]});break}case"Escape":{if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){let l=e.target.closest("[data-aia-input]")??e.target,c=t.editingTail;this.ctx.exitEditMode?.(),C(l,c)}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 o=r;o<t.filteredOptions.length;o++)if(t.filteredOptions[o]?.is_tappable)return o;return null}getTappableIndices(e){let n=this.store.get().filteredOptions.map((o,a)=>o.is_tappable?a:-1).filter(o=>o!==-1),r=Array.from({length:e},()=>[]);for(let o of n)r[o%e].push(o);return r.flat()}getEffectiveColumns(){let e=document.getElementById(this.ctx.listboxId);if(!e)return this.ctx.columns;let n=document.getElementById(`${this.ctx.listboxId}-option-0`)?.parentElement??null;for(;n;){let r=getComputedStyle(n).gridTemplateColumns;if(r&&r!=="none"){let o=r.split(" ").filter(Boolean).length;if(o>0)return o}if(n===e)break;n=n.parentElement}return this.ctx.columns}clickOrSelect(e,t,n){let r=document.getElementById(`${n}-option-${e}`);r?r.click():this.ctx.selectOption(t[e])}removeActivePill(){let e=this.store.get(),t=e.suggestions.filter(s=>s.type==="placeholder"),n=e.suggestions.filter(s=>s.type!=="placeholder");if(n.length===0)return;let r=n[0],o=n.slice(1),a=e.skippedParams.some(s=>s.type===r.type);this.store.set({suggestions:[...t,...o],pillTapped:o.length>0,activeDropdownIndex:-1,...a?{}:{skippedParams:[...e.skippedParams,{id:crypto.randomUUID(),type:r.type,suggestionPlaceholder:r.text}]}}),o.length===0&&this.ctx.fetchNow?.()}};var V=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),n=t.suggestions.filter(l=>l.type!=="placeholder");if(e<0||e>=n.length)return;let r=n[e],o=n.filter((l,c)=>c!==e),a=t.suggestions.filter(l=>l.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:l}=v(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:l,selectedPill:r.text,otherPills:o.map(c=>c.text)})}let s=[...a,r,...o],d=this.store.peek({suggestions:s}).filteredOptions.findIndex(l=>l.is_tappable);this.store.set({suggestions:s,pillTapped:!0,activeDropdownIndex:d})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};var X=class{constructor(e,t){this.store=e;this.getConfig=t;this.hasLoggedError=!1}async run(e,t,n){let r=this.getConfig();if(r){if(e.trim().length===0){this.clear(n);return}try{let o=await r.fetch(e,t);if(t.aborted||!n())return;let a=r.transform(o),s=Array.isArray(a)?a:[],d=r.limit!=null?s.slice(0,r.limit):s;if(t.aborted||!n())return;this.commit(d)}catch(o){if(t.aborted||bt(o))return;this.logOnce(o),this.clear(n)}}}clearNow(){this.commit([])}clear(e){e()&&this.commit([])}commit(e){e.length===0&&this.store.get().products.length===0||this.store.set({products:e})}logOnce(e){this.hasLoggedError||(this.hasLoggedError=!0,console.warn("[AIAutocomplete] products.fetch/transform failed \u2014 the product strip is hidden. Later failures on this instance are not logged.",e))}};function bt(i){return i instanceof Error&&i.name==="AbortError"}function Be(i,e){let t=e.dropdownTrigger??"auto",n=e.closeDropdownOnBlur??!0,a=i.filteredOptionsLength>0||i.activePillHasNoOptions||i.hasProducts;if(i.inEditMode){let s=n?i.isFocused:!0;return a&&s}if(t==="auto"){let s=n?i.isFocused:!0,d=i.text.replace(/\s+$/,"").length,l=i.caretOffset==null||i.caretOffset>=d;return(a||i.isLoading)&&s&&l}return t==="manual"?(a||i.isLoading)&&i.pillTapped:!1}function Ke(i,e){let t=Re(i.text,i.completedParams,i.identifiedParams),n=i.suggestions.filter(m=>m.type!=="placeholder"),r=n[0],o=r?e.optionOverrides?.[r.type]:void 0,a=i.suggestions.filter(m=>m.type==="placeholder").map(m=>m.text).join(" "),s=T(i.text,Math.min(i.filterBase,i.text.length),a),l=s===0&&U(i.text,i.completedParams.length,a)?"":A(i.text,s,i.filterInProgress),c=r?o?o(l.trim())??r.options??[]:r.options??[]:[],p=i.editingParam!=null&&i.editingAnchor!=null,u;if(p&&i.editingParam&&i.editingAnchor!=null){let m=i.editingParam.id,x=i.completedParams.some(E=>E.id===m),S=i.caretOffset??i.editingAnchor,P=x?"":i.text.slice(i.editingAnchor,S);u=I(i.editingParam.options,P)}else u=I(c,l);let f=e.showNonTappableOptions===!1;f&&(u=u.filter(m=>m.is_tappable));let h=m=>f?m.is_tappable:!0,y;if(p){let m=i.editingParam?.options??[];y=i.editingParam!=null&&m.filter(h).length===0}else{let m=r?o?o("")??r.options??[]:r.options??[]:[];y=r!=null&&m.filter(h).length===0}let b=Be({inEditMode:p,filteredOptionsLength:u.length,isFocused:i.isFocused,text:i.text,caretOffset:i.caretOffset,isLoading:i.isLoading,pillTapped:i.pillTapped,activePillHasNoOptions:y,hasProducts:i.products.length>0},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),g=b&&i.activeDropdownIndex>=0&&!!u[i.activeDropdownIndex]?.is_tappable;return{segments:t,actionableSuggestions:n,filteredOptions:u,placeholderText:a,isDropdownOpen:b,isActivePillSelected:g}}function z(i){return i.mode==="fresh"?xt(i):yt(i)}function xt(i){let{text:e,completedParams:t,suggestions:n,filterBase:r,filterInProgress:o}=i,s=n.filter(S=>S.type!=="placeholder")[0];if(!s?.options)return null;let d=n.filter(S=>S.type==="placeholder").map(S=>S.text).join(" "),l=T(e,r,d),c=A(e,l,o),p=O(s.options,c);if(!p)return null;let u=p.text.toLowerCase(),f=e.toLowerCase().lastIndexOf(u),h=f>=0?f:Math.max(0,e.length-p.text.length),y=h+p.text.length,b=e.slice(h,y),m=y<e.length&&e[y]===" "?y+1:y,x={id:crypto.randomUUID(),placeholder:"",type:s.type,text:b,kind:p.kind,suggestionType:s.type,suggestionPlaceholder:s.text,options:s.options??[],metadata:p.metadata};return{patch:{text:e,completedParams:[...t,x],suggestions:n.filter(S=>S!==s),filterBase:m,newParamId:x.id,caretOffset:m,activeDropdownIndex:-1},caretPos:m}}function yt(i){let{text:e,completedParams:t,editingParam:n,editingAnchor:r,editingTail:o}=i;if(t.some(x=>x.id===n.id))return null;let a=e.slice(r,o),s=O(n.options,a);if(!s)return null;let d=s.text.toLowerCase(),l=a.toLowerCase().lastIndexOf(d),c=r+Math.max(0,l),p=c+s.text.length,u=e.slice(c,p),h=p<e.length&&e[p]===" "?p+1:p,y={id:crypto.randomUUID(),placeholder:"",type:n.suggestionType,text:u,kind:s.kind,suggestionType:n.suggestionType,suggestionPlaceholder:n.suggestionPlaceholder,options:n.options,metadata:s.metadata},b=t.length,g=0;for(let x=0;x<t.length;x++){let S=e.indexOf(t[x].text,g);if(S!==-1){if(S>=h){b=x;break}g=S+t[x].text.length}}let m=[...t];return m.splice(b,0,y),{patch:{text:e,completedParams:m,newParamId:y.id,filterBase:h,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:h,activeDropdownIndex:-1},caretPos:h}}function Y(i,e,t){let n=i.slice(0,e),r=i.slice(t),o=(n===""||n.endsWith(" "))&&r.startsWith(" ");return o&&(r=r.slice(1)),{text:n+r,removed:t-e+(o?1:0)}}var J=class{constructor(e){this.deps=e}start(e){let t=this.deps.store.get();if(t.editingParam?.id===e)return;let n=t.completedParams.find(a=>a.id===e);if(!n)return;let r=0,o=-1;for(let a of t.completedParams){let s=t.text.indexOf(a.text,r);if(s!==-1){if(a.id===e){o=s;break}r=s+a.text.length}}o<0||this.deps.store.set({editingParam:n,editingAnchor:o,editingTail:o+n.text.length,caretOffset:o+n.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(),n=t.editingParam,r=t.editingAnchor,o=t.editingTail;if(!n||r==null||o==null||!t.completedParams.some(d=>d.id===n.id))return!1;let{text:a}=e===""?Y(t.text,r,o):{text:t.text.slice(0,r)+e+t.text.slice(o)},s=r+e.length;return this.deps.store.set(d=>({text:a,completedParams:d.completedParams.filter(l=>l.id!==n.id),editingTail:s,caretOffset:s,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(s),this.tryPromote(),!0}caretAfterInput(e){let t=this.deps.store.get(),n={caretOffset:e};t.editingParam&&t.editingAnchor!=null&&e!=null&&(e<t.editingAnchor?(n.editingParam=null,n.editingAnchor=null,n.editingTail=null,n.activeDropdownIndex=-1):t.editingTail!=null&&(n.editingTail=Math.max(t.editingTail,e))),this.deps.store.set(n),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(),n=t.editingParam,r=t.editingAnchor,o=t.editingTail;if(!n||r==null||o==null)return;this.deps.fireTelemetry("option",{raw_query:v(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:n.options.filter(g=>g.text!==e.text).map(g=>g.text)});let a=t.text.slice(0,r),s=t.text.slice(o),d=r===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,l=s.length===0||s[0]!==" ",c=l?`${d} `:d,p=a+c+s,u=r+c.length+(l?0:1),f={id:crypto.randomUUID(),placeholder:"",type:n.suggestionType,text:d,kind:e.kind,suggestionType:n.suggestionType,suggestionPlaceholder:n.suggestionPlaceholder,options:n.options,metadata:e.metadata},h=t.completedParams.findIndex(g=>g.id===n.id),y=t.completedParams.filter(g=>g.id!==n.id),b=h>=0?Math.min(h,y.length):y.length;y.splice(b,0,f),this.deps.store.set({text:p,completedParams:y,newParamId:f.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=z({mode:"edit",text:e.text,completedParams:e.completedParams,editingParam:e.editingParam,editingAnchor:e.editingAnchor,editingTail:e.editingTail});t&&(this.deps.store.set(t.patch),this.deps.scheduleSetCursor(t.caretPos))}};var Ue="https://ai-autocomplete.com";function ue(i=Ue){try{if(typeof window>"u"||!window.location)return i;let e=window.location.hostname;if(!e)return i;let t=new URL(i);return t.searchParams.set("utm_source",e),t.toString()}catch{return i}}function me(i,e){return i?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}var $e="data-aia-key";function D(i,e,t){let n=new Map;for(let a of Array.from(i.children)){let s=a.getAttribute($e);s!=null&&n.set(s,a)}let r=new Set,o=[];for(let a=0;a<e.length;a++){let s=e[a],d=t.keyOf(s,a);r.add(d);let l=n.get(d);l||(l=t.create(s,a),l.setAttribute($e,d)),t.update?.(l,s,a),i.children[a]!==l&&i.insertBefore(l,i.children[a]??null),o.push(l)}for(let[a,s]of n)r.has(a)||s.remove();return o}var qe=[125,69];function Qe(i,e){return e?1:i===0?.7:i===1?.4:.2}function Z(i,e,t,n,r=!1,o=!1,a=!1){let s=i.querySelector(".magicx-aia-pill-list");if(s||(s=document.createElement("span"),s.className="magicx-aia-pill-list",i.appendChild(s)),o&&e.length===0){s.setAttribute("data-aia-pill-list-loading",""),s.innerHTML="";for(let d=0;d<qe.length;d++){let l=qe[d],c=document.createElement("span");c.setAttribute("data-aia-pill-skeleton",""),c.className=`magicx-aia-pill magicx-aia-pill--skeleton${r?" magicx-aia-pill--rounded":""}`,c.style.width=`${l}px`,c.style.opacity=String(Qe(d,!1)),s.appendChild(c)}return}o?s.setAttribute("data-aia-pill-list-loading",""):s.removeAttribute("data-aia-pill-list-loading");for(let d of s.querySelectorAll("[data-aia-pill-skeleton]"))d.remove();D(s,e,{keyOf:d=>`${d.type}-${d.text}`,create:d=>{let l=document.createElement("button");return l.type="button",l.tabIndex=-1,l.setAttribute("data-aia-pill",""),l.setAttribute("contenteditable","false"),l.textContent=d.text,l.addEventListener("mousedown",c=>c.preventDefault()),l},update:(d,l,c)=>{let p=d,u=a&&c===t&&!o,f=["magicx-aia-pill"];r&&f.push("magicx-aia-pill--rounded"),o&&f.push("magicx-aia-pill--skeleton"),p.className=f.join(" "),p.style.width="",p.style.opacity=String(Qe(c,u)),o?(p.setAttribute("data-aia-loading",""),p.disabled=!0,p.onclick=null):(p.removeAttribute("data-aia-loading"),p.disabled=!1,p.onclick=()=>n(c))}})}function ge(i){i.querySelector(".magicx-aia-pill-list")?.remove()}var St="Products";function Ge(i,e,t,n,r){let o=i.querySelector(".magicx-aia-products");if(e.length===0){o?.remove();return}if(!o){o=document.createElement("section"),o.className="magicx-aia-products",o.setAttribute("data-aia-products",""),o.setAttribute("role","group"),o.setAttribute("aria-labelledby",`${t}-products-label`);let s=document.createElement("div");s.className="magicx-aia-products-label",s.id=`${t}-products-label`,s.textContent=St;let d=document.createElement("div");d.className="magicx-aia-products-row",d.setAttribute("data-aia-products-row",""),o.append(s,d),i.appendChild(o)}let a=o.querySelector(".magicx-aia-products-row");a&&D(a,e,{keyOf:s=>Pt(s),create:s=>vt(s,n,r),update:(s,d,l)=>{s.id=`${t}-product-${l}`,s.dataset.aiaIndex=String(l)}})}function fe(i,e){let t=i.querySelectorAll("[data-aia-product]");for(let n of t)n.tabIndex=e?0:-1}function Pt(i){return[i.id,i.title,i.url,i.imageUrl,i.price,i.vendor].map(e=>e??"").join("\0")}function vt(i,e,t){let n=document.createElement("a");n.className="magicx-aia-product",n.setAttribute("data-aia-product",""),n.setAttribute("role","option"),n.setAttribute("aria-selected","false"),n.href=i.url,n.tabIndex=0;let r=document.createElement("span");if(r.className="magicx-aia-product-media",i.imageUrl){let s=document.createElement("img");s.className="magicx-aia-product-image",s.src=i.imageUrl,s.alt="",s.loading="lazy",s.decoding="async",r.appendChild(s)}else r.setAttribute("data-aia-product-placeholder","");n.appendChild(r);let o=document.createElement("span");if(o.className="magicx-aia-product-body",i.vendor){let s=document.createElement("span");s.className="magicx-aia-product-vendor",s.textContent=i.vendor,o.appendChild(s)}let a=document.createElement("span");if(a.className="magicx-aia-product-title",a.textContent=i.title,o.appendChild(a),i.price){let s=document.createElement("span");s.className="magicx-aia-product-price",s.textContent=i.price,o.appendChild(s)}return n.appendChild(o),n.addEventListener("click",s=>{s.metaKey||s.ctrlKey||s.shiftKey||s.altKey||s.button!==0||(s.preventDefault(),e(i))}),n.addEventListener("keydown",s=>{s.key!=="Enter"&&s.key!==" "||(s.preventDefault(),e(i))}),n.addEventListener("focus",()=>t(!0)),n.addEventListener("blur",s=>{s.relatedTarget?.closest("[data-aia-dropdown]")||t(!1)}),n}function We(i,e,t,n,r,o,a,s=""){let d=i.querySelector(".aia-grid");if(e.length===0){d?.remove();return}d||(d=document.createElement("div"),d.className="aia-grid magicx-aia-grid",d.setAttribute("data-scroll",""),d.style.setProperty("--aia-grid-min","250px"),d.style.setProperty("--aia-grid-max","1fr"),d.style.setProperty("--aia-grid-gap","0"),i.appendChild(d)),wt(d,e,t,n,r,o,a),Ct(d,s)}function Ct(i,e){i.dataset.aiaGroup!==e&&(i.dataset.aiaGroup=e,i.scrollTop=0)}function wt(i,e,t,n,r,o,a){let s=a?"1":"0";D(i,e,{keyOf:d=>`${d.text}\0${s}`,create:d=>Et(d,a),update:(d,l,c)=>{let p=c===t&&!a;d.id=`${o}-option-${c}`,d.dataset.aiaIndex=String(c),d.setAttribute("aria-selected",String(p)),d.classList.toggle("magicx-aia-option--highlighted",p),!a&&l.is_tappable?(d.onclick=()=>{d.classList.add("magicx-aia-option--pressed"),n(l),setTimeout(()=>d.classList.remove("magicx-aia-option--pressed"),500)},d.onmouseenter=()=>{let u=Number.parseInt(d.dataset.aiaIndex??"-1",10);u>=0&&r(u)}):(d.onclick=null,d.onmouseenter=null)}})}function Et(i,e){let t=document.createElement("div");t.setAttribute("role","option"),t.setAttribute("data-aia-option",""),e&&t.setAttribute("data-aia-loading",""),t.tabIndex=e||!i.is_tappable?-1:0;let n=["magicx-aia-option"];i.is_tappable?n.push("magicx-aia-option--tappable"):n.push("magicx-aia-option--non-tappable"),t.className=n.join(" ");let r=document.createElement("div");r.className="magicx-aia-streaks",t.appendChild(r);let o=document.createElement("div");o.className="magicx-aia-streaks-vert",t.appendChild(o);let a=document.createElement("span");a.className="magicx-aia-option-content";let s=document.createElement("span");if(s.className="magicx-aia-option-text",s.textContent=i.icon?`${i.icon} ${i.text}`:i.text,a.appendChild(s),i.tag){let d=document.createElement("span");d.className="magicx-aia-option-tag",d.textContent=i.tag,a.appendChild(d)}return t.appendChild(a),t}var Tt=[159,119,164];function ee(i){let e=document.createElement("div");return e.id=i,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",t=>t.preventDefault()),e}function te(i,e){let{filteredOptions:t,activeIndex:n,isOpen:r,isLoading:o,pills:a,showPills:s,isActivePillSelected:d,onSelect:l,onHighlight:c,onPillClick:p}=e,u=s&&a.length>0,f=t.length>0,h=e.products.length>0,y=r&&(f||u||o||h);if(y?i.classList.add("magicx-aia-dropdown--visible"):i.classList.remove("magicx-aia-dropdown--visible"),o?i.setAttribute("data-aia-loading",""):i.removeAttribute("data-aia-loading"),!y){fe(i,!1);return}h?i.setAttribute("data-aia-has-products",""):i.removeAttribute("data-aia-has-products");let b=i.querySelector(".aia-stack");b||(b=document.createElement("div"),b.className="aia-stack",b.style.setProperty("--aia-stack-space","8px"),i.appendChild(b));let g=u||o&&s,m=b.querySelector(".magicx-aia-pill-bar");g?(m||(m=document.createElement("div"),m.className="magicx-aia-pill-bar aia-cluster",m.setAttribute("data-nowrap",""),m.setAttribute("data-aia-pillbar",""),b.insertBefore(m,b.firstChild)),Z(m,a,0,p,!0,o,d)):m&&m.remove();let x=e.suggestions[0],S=x?`${x.type} ${x.text}`:"";We(b,t,n,l,c,e.listboxId,o,S);let P=b.querySelector(".magicx-aia-skeleton-bars");if(o&&!f){if(!P){P=document.createElement("div"),P.className="magicx-aia-skeleton-bars",P.setAttribute("data-aia-skeleton-bars","");for(let ot of Tt){let oe=document.createElement("span");oe.className="magicx-aia-skeleton-bar",oe.style.width=`${ot}px`,P.appendChild(oe)}b.appendChild(P)}}else P&&P.remove();Ge(b,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange),fe(i,!0);let E=b.querySelector(".magicx-aia-footer")??Ot(),rt=n>=0&&!!t[n]?.is_tappable;It(E,me(rt,e.isInputEmpty)),E.isConnected||b.appendChild(E),At(b,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"])}function At(i,e){let t=e.map(n=>i.querySelector(`:scope > ${n}`)).filter(n=>n!==null);for(let n=0;n<t.length;n++)i.children[n]!==t[n]&&i.insertBefore(t[n],i.children[n]??null)}function It(i,{key:e,hint:t}){let n=i.querySelector(".magicx-aia-footer-key"),r=i.querySelector(".magicx-aia-footer-hint");!n||!r||(n.textContent!==e&&(n.textContent=e),r.textContent!==t&&(r.textContent=t))}function Ot(){let i=document.createElement("footer");i.className="magicx-aia-footer",i.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 n=document.createElement("kbd");n.className="magicx-aia-footer-key",n.textContent="tab";let r=document.createElement("span");r.className="magicx-aia-footer-hint",r.textContent="to select",t.append(n,r);let o=document.createElement("a");o.className="aia-cluster magicx-aia-footer-brand-link",o.setAttribute("data-align","center"),o.href=ue(),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 s=document.createElement("span");return s.className="magicx-aia-footer-badge",s.textContent="Autocomplete",o.append(a,s),e.append(t,o),i.append(e),i}function je(i,e){let t=ee(e.listboxId);return i.appendChild(t),{dropdown:t}}function he(i,e,t){te(i.dropdown,{suggestions:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,onSelect:t.selectOption,onHighlight:n=>t.store.set({activeDropdownIndex:n}),onPillClick:t.setActivePill,onProductSelect:t.selectProduct,onProductFocusChange:n=>t.store.set({isFocused:n})})}function be(i){let{input:e,segments:t,newParamId:n,editingParamId:r,placeholderText:o,isFocused:a}=i,s=t.length===0;e.dataset.aiaEmpty=s?"true":"false",s&&o?e.dataset.placeholder=o:delete e.dataset.placeholder;let d=t.map(b=>`${b.type}:${b.value}`).join("\0"),l=e.dataset.segKey??"",c=e.dataset.newParamId??"",p=e.dataset.editingParamId??"";if(d===l&&(n??"")===c&&(r??"")===p)return;let u=a?w(e):null;e.dataset.segKey=d,e.dataset.newParamId=n??"",e.dataset.editingParamId=r??"";let f=e.ownerDocument??document,h=f.createDocumentFragment(),y=0;for(let b of t)if(y+=b.value.length,b.type==="completed"){let g=f.createElement("strong");g.dataset.seg="completed",g.dataset.paramId=b.param.id;let m=b.param.id===n,x=b.param.id===r,S=["magicx-aia-segment","magicx-aia-segment--completed"];m&&S.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),x&&S.push("magicx-aia-segment--editing"),g.className=S.join(" "),g.textContent=b.value,h.appendChild(g)}else if(b.type==="identified"){let g=f.createElement("strong");g.dataset.seg="identified",g.dataset.paramId=b.param.id,g.className="magicx-aia-segment magicx-aia-segment--completed",g.textContent=b.value,h.appendChild(g)}else h.appendChild(f.createTextNode(b.value));e.replaceChildren(h),e.dataset.aiaTextLength=String(y),u!=null&&C(e,Math.max(0,Math.min(u,y)))}var kt='<svg width="18" height="18" viewBox="0 0 18 18" fill="none" role="img" aria-label="Submit"><path d="M9 14V4M9 4L4 9M9 4L14 9" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';function Ve(){let i=document.createElement("button");return i.type="button",i.className="magicx-aia-submit",i.setAttribute("aria-label","Submit"),i.setAttribute("data-aia-submit",""),i.innerHTML=kt,i}function Dt(){let i=document.createElement("div");return i.setAttribute("contenteditable","plaintext-only"),i.contentEditable==="plaintext-only"}function Xe(i,e){let t=e.firstElementChild;if(!t){e.removeAttribute("data-aia-pill-wrapped");return}let n=t.getBoundingClientRect(),r=i.getBoundingClientRect();n.top>=r.bottom-2?e.setAttribute("data-aia-pill-wrapped",""):e.removeAttribute("data-aia-pill-wrapped")}function ze(i,e){let{listboxId:t}=e,n=ee(t);i.appendChild(n);let r=document.createElement("div");r.className="magicx-aia-input-wrapper",i.appendChild(r);let o=document.createElement("div");o.className="magicx-aia-editor",o.setAttribute("data-aia-editor",""),r.appendChild(o);let a=document.createElement("div");a.className="magicx-aia-input",a.setAttribute("data-aia-input",""),a.setAttribute("contenteditable",Dt()?"plaintext-only":"true"),a.setAttribute("role","combobox"),a.setAttribute("aria-autocomplete","list"),a.setAttribute("aria-haspopup","listbox"),a.setAttribute("aria-controls",t),a.setAttribute("aria-expanded","false"),a.setAttribute("spellcheck","true"),a.setAttribute("enterkeyhint","send"),o.appendChild(a);let s=document.createElement("span");s.className="magicx-aia-pill-list-container",s.setAttribute("data-aia-pill-list-container",""),o.appendChild(s);let d=null,l=null;e.submitButton===void 0?(d=Ve(),r.appendChild(d),l=d):e.submitButton!==null&&(l=e.submitButton,l.hasAttribute("data-aia-submit")||l.setAttribute("data-aia-submit",""),r.appendChild(l));let c=new AbortController,{signal:p}=c,u=!1,f=0,h=()=>{let g=W(a),x=g.length>0&&g[0]!==g[0].toUpperCase()?g[0].toUpperCase()+g.slice(1):g;e.handleChange(x)},y=()=>{let g=(a.ownerDocument??document).getSelection();if(!g||g.rangeCount===0)return null;let m=g.anchorNode;return!m||!a.contains(m)?null:(m.nodeType===Node.ELEMENT_NODE?m:m.parentElement)?.closest('strong[data-seg="completed"][data-param-id]')?.dataset.paramId??null};r.addEventListener("click",g=>{g.target?.closest("[data-aia-pill]")||a.focus()},{signal:p}),a.addEventListener("input",()=>{u||(f=performance.now(),h(),e.handleCaretAfterInput(w(a)))},{signal:p});let b=a.ownerDocument??document;if(b.addEventListener("selectionchange",()=>{let g=b.getSelection();if(!g||g.rangeCount===0||!a.contains(g.anchorNode))return;let m=y(),x=e.store.get().editingParam?.id??null;if(m&&m!==x){e.startEditingParam(m);return}performance.now()-f<50||e.handleCaretMove(w(a))},{signal:p}),a.addEventListener("compositionstart",()=>{u=!0},{signal:p}),a.addEventListener("compositionend",()=>{u=!1,h()},{signal:p}),a.addEventListener("beforeinput",g=>{let m=g,x=m.inputType;if(x==="insertParagraph"||x==="insertLineBreak"||x==="insertFromDrop"){g.preventDefault();return}if(x.startsWith("insert")||x.startsWith("delete")){let S=x.startsWith("delete")?"":m.data??"";e.replaceEditingRange(S)&&g.preventDefault()}},{signal:p}),a.addEventListener("paste",g=>{g.preventDefault();let m=(g.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!m)return;let x=a.ownerDocument??document,S=x.getSelection();if(!S||S.rangeCount===0)return;let P=S.getRangeAt(0);if(!a.contains(P.startContainer))return;P.deleteContents();let E=x.createTextNode(m);P.insertNode(E),P.setStartAfter(E),P.collapse(!0),S.removeAllRanges(),S.addRange(P),h()},{signal:p}),a.addEventListener("keydown",g=>e.handleKeyDown(g),{signal:p}),a.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:p}),a.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:p}),l&&l.addEventListener("click",g=>{let m=e.store.get();if(!(!!m.text||m.completedParams.length>0)||!e.onSubmit)return;g.stopPropagation(),e.onSubmit(R(m.text,m.completedParams,m.skippedParams))&&e.afterSubmit?.()},{signal:p}),e.autoFocus!==!1){a.focus();let g=a.ownerDocument??document,m=g.getSelection(),x=m&&m.rangeCount>0&&a.contains(m.anchorNode);if(m&&!x){let S=g.createRange();S.selectNodeContents(a),S.collapse(!0),m.removeAllRanges(),m.addRange(S)}}if(typeof ResizeObserver<"u"){let g=new ResizeObserver(()=>Xe(a,s));g.observe(a),c.signal.addEventListener("abort",()=>g.disconnect(),{once:!0})}return{input:a,inlinePillContainer:s,dropdown:n,submitButton:d,abort:c}}function xe(i,e,t){let{input:n,inlinePillContainer:r,dropdown:o,submitButton:a}=i,{pillPlacement:s,setActivePill:d,selectOption:l,store:c}=t;n.setAttribute("aria-expanded",String(e.isDropdownOpen));let p=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(p?n.setAttribute("aria-activedescendant",p):n.removeAttribute("aria-activedescendant"),a){let b=!!e.text||e.completedParams.length>0;a.disabled=!b}let u=n.dataset.newParamId??"",f=e.newParamId!==null&&e.newParamId!==u;if(be({input:n,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused}),s==="inline"){let b=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;b||e.actionableSuggestions.length>0?Z(r,e.actionableSuggestions,0,d,!1,b,e.isActivePillSelected):ge(r)}else ge(r);Xe(n,r),f?(n.focus(),C(n,e.caretOffset??e.text.length)):e.isFocused&&W(n)!==e.text&&C(n,e.text.length);let h=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:null,y=h??e.actionableSuggestions[0];te(o,{suggestions:y?[{...y,options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation,listboxId:t.listboxId,pills:h?[h]:e.actionableSuggestions,showPills:s==="dropdown",isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,onSelect:l,onHighlight:b=>c.set({activeDropdownIndex:b}),onPillClick:d,onProductSelect:t.selectProduct,onProductFocusChange:b=>c.set({isFocused:b})})}function Ye(i,e){let t=i.actionableSuggestions[0];if(!t)return null;let n=i.filterBase,r=i.text.slice(0,n),o=r.length===0&&i.text.length===0,a=r.length===0&&i.text.length>0&&i.placeholderText.length>0&&i.placeholderText.toLowerCase().startsWith(i.text.toLowerCase());(o||a)&&i.placeholderText&&(r=`${i.placeholderText} `);let s=Ae(r,e.text);s>0&&(r=r.slice(0,r.length-s));let d=r.length>0&&r[r.length-1]!==" ",l=`${r}${d?" ":""}${e.text} `,c=(o||a)&&l.length>0?l[0].toUpperCase()+l.slice(1):l,p=c.toLowerCase().lastIndexOf(e.text.toLowerCase()),u=p>=0?c.slice(p,p+e.text.length):e.text,f={id:crypto.randomUUID(),placeholder:"",type:t.type,text:u,kind:e.kind,suggestionType:t.type,suggestionPlaceholder:t.text,options:t.options??[],metadata:e.metadata},h=i.actionableSuggestions.length-1;return{patch:{text:c,filterBase:c.length,completedParams:[...i.completedParams,f],newParamId:f.id,caretOffset:c.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:h>0,inSelectionAnimation:!0,pendingSpan:null},telemetry:{selectedOption:e.text,otherOptions:i.filteredOptions.filter(y=>y.text!==e.text).map(y=>y.text)},consumedSuggestion:t,remainingActionable:h}}function ye(i){let e=i,t=new Set,n=[],r=!1;return{get:()=>e,set:o=>{let a=typeof o=="function"?o(e):o,s=e;if(e={...e,...a},n.push([e,s]),!r){r=!0;try{let d=0;for(let l=n.shift();l;l=n.shift()){if(++d>1e4)throw n.length=0,new Error("createStore: notifications did not settle after 10000 deliveries \u2014 a listener is likely calling set() on every notification");let[c,p]=l;for(let u of t)u(c,p)}}catch(d){throw n.length=0,d}finally{r=!1}}},subscribe:o=>(t.add(o),()=>{t.delete(o)})}}function Je(i,e){let t,n,r=o=>(o!==t&&(t=o,n=e(o)),n);return{get:()=>{let o=i.get();return{...o,...r(o)}},set:o=>{typeof o=="function"?i.set(a=>{let s={...a,...r(a)};return o(s)}):i.set(o)},peek:o=>{let a={...i.get(),...o};return{...a,...e(a)}},subscribe:o=>i.subscribe((a,s)=>{let d={...s,...r(s)},l={...a,...r(a)};o(l,d)})}}var Se=!1;function Ze(){if(Se||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){Se=!0;return}Se=!0;let i=document.createElement("style");i.setAttribute("data-magicx-aia",""),i.textContent=Lt,document.head.appendChild(i)}var Lt=`@layer layout {
|
|
2
2
|
.aia-stack {
|
|
3
3
|
display: flex;
|
|
4
4
|
flex-direction: column;
|
|
@@ -168,7 +168,7 @@ var N=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;t
|
|
|
168
168
|
display: inline-block;
|
|
169
169
|
padding: 4px 6px;
|
|
170
170
|
border-radius: 999px;
|
|
171
|
-
background: var(--aia-completed-pill-bg, rgba(189, 189, 189, 0.
|
|
171
|
+
background: var(--aia-completed-pill-bg, rgba(189, 189, 189, 0.105));
|
|
172
172
|
color: var(--aia-completed-pill-color, var(--aia-written-text-color, #fff));
|
|
173
173
|
font-size: var(--aia-pill-font-size, 14px);
|
|
174
174
|
font-weight: 400;
|
|
@@ -309,9 +309,9 @@ var N=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;t
|
|
|
309
309
|
/* Solid surface is the default (matches the Figma components). Opt into the
|
|
310
310
|
frosted-glass look with data-aia-surface="glass". */
|
|
311
311
|
background: var(--aia-surface, #ffffff);
|
|
312
|
-
border: 1px solid var(--aia-dropdown-border,
|
|
312
|
+
border: 1px solid var(--aia-dropdown-border, rgba(231, 231, 231, 0.5));
|
|
313
313
|
border-radius: 18px;
|
|
314
|
-
box-shadow: var(--aia-dropdown-shadow, 0 8px 12px rgba(0, 0, 0, 0.
|
|
314
|
+
box-shadow: var(--aia-dropdown-shadow, 0 8px 12px rgba(0, 0, 0, 0.05));
|
|
315
315
|
}
|
|
316
316
|
|
|
317
317
|
.magicx-aia-dropdown[data-aia-surface="glass"] {
|
|
@@ -378,6 +378,178 @@ var N=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;t
|
|
|
378
378
|
}
|
|
379
379
|
}
|
|
380
380
|
|
|
381
|
+
/* ===================================================================
|
|
382
|
+
Product strip \u2014 an opt-in section below the options grid.
|
|
383
|
+
|
|
384
|
+
Every colour resolves through the same --aia-* chain the options use.
|
|
385
|
+
Nothing here is allowed to say \`color: inherit\`: the dropdown paints a
|
|
386
|
+
background but never sets a \`color\`, so an inheriting node would pick up the
|
|
387
|
+
HOST PAGE's text colour and render black text on a dark panel. For the same
|
|
388
|
+
reason there is no \`prefers-color-scheme\` rule anywhere in this section \u2014
|
|
389
|
+
the panel's darkness comes from --aia-surface, which is independent of the
|
|
390
|
+
OS setting.
|
|
391
|
+
=================================================================== */
|
|
392
|
+
.magicx-aia-products {
|
|
393
|
+
display: flex;
|
|
394
|
+
flex-direction: column;
|
|
395
|
+
gap: 6px;
|
|
396
|
+
/* Matches the grid's own 8px inline padding so the section label lines up
|
|
397
|
+
with the option text above it. */
|
|
398
|
+
padding: 0 8px;
|
|
399
|
+
min-width: 0;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
.magicx-aia-products-label {
|
|
403
|
+
font-family: inherit;
|
|
404
|
+
font-size: var(--aia-products-label-font-size, 11px);
|
|
405
|
+
font-weight: 500;
|
|
406
|
+
line-height: 18px;
|
|
407
|
+
letter-spacing: 0.02em;
|
|
408
|
+
color: var(
|
|
409
|
+
--aia-products-label-color,
|
|
410
|
+
var(--aia-option-color, var(--aia-color-text-muted, #c1c4cb))
|
|
411
|
+
);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/* The scroll container. Horizontal overflow is confined here \u2014 the dropdown
|
|
415
|
+
itself is \`overflow: hidden\`, so the page can never gain a sideways
|
|
416
|
+
scrollbar no matter how many cards there are. \`overscroll-behavior-x\` stops
|
|
417
|
+
a trackpad fling at either end from chaining out to the page. */
|
|
418
|
+
.magicx-aia-products-row {
|
|
419
|
+
display: flex;
|
|
420
|
+
gap: var(--aia-product-gap, 8px);
|
|
421
|
+
min-width: 0;
|
|
422
|
+
overflow-x: auto;
|
|
423
|
+
overflow-y: hidden;
|
|
424
|
+
overscroll-behavior-x: contain;
|
|
425
|
+
padding-bottom: 2px;
|
|
426
|
+
/* Hide the scrollbar chrome across all three engines while leaving the box
|
|
427
|
+
scrollable by trackpad, wheel, touch and keyboard. Firefox + the old Edge
|
|
428
|
+
property first, WebKit/Blink via the pseudo-element below. */
|
|
429
|
+
scrollbar-width: none;
|
|
430
|
+
-ms-overflow-style: none;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
.magicx-aia-products-row::-webkit-scrollbar {
|
|
434
|
+
display: none;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/* Card. Fixed width so the row is a predictable set of columns; the body
|
|
438
|
+
column below stretches to fill whatever height the tallest card needs. */
|
|
439
|
+
.magicx-aia-product {
|
|
440
|
+
flex: 0 0 auto;
|
|
441
|
+
display: flex;
|
|
442
|
+
flex-direction: column;
|
|
443
|
+
gap: 6px;
|
|
444
|
+
width: var(--aia-product-card-width, 116px);
|
|
445
|
+
padding: 6px;
|
|
446
|
+
border-radius: 10px;
|
|
447
|
+
background: var(--aia-product-bg, transparent);
|
|
448
|
+
/* Explicit, never inherited \u2014 see the section header. */
|
|
449
|
+
color: var(--aia-option-color, var(--aia-color-text-muted, #c1c4cb));
|
|
450
|
+
text-decoration: none;
|
|
451
|
+
cursor: pointer;
|
|
452
|
+
transition: background-color 150ms ease;
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
.magicx-aia-product:hover {
|
|
456
|
+
background: var(--aia-product-bg-active, var(--aia-option-bg, transparent));
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/* Focus is the only cue a keyboard user gets, so it is a real ring rather than
|
|
460
|
+
a background change. Drawn INSIDE the card (negative offset): the row is a
|
|
461
|
+
scroll container with clipped overflow, so an outset ring is cut off on the
|
|
462
|
+
first and last cards and on every card's top and bottom edge. */
|
|
463
|
+
.magicx-aia-product:focus-visible {
|
|
464
|
+
outline: 2px solid var(--aia-product-focus-ring, var(--aia-option-color-selected, currentColor));
|
|
465
|
+
outline-offset: -2px;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/* Square media tile. aspect-ratio (not a fixed height) keeps it square at any
|
|
469
|
+
--aia-product-card-width a consumer sets. */
|
|
470
|
+
.magicx-aia-product-media {
|
|
471
|
+
display: block;
|
|
472
|
+
position: relative;
|
|
473
|
+
width: 100%;
|
|
474
|
+
aspect-ratio: 1 / 1;
|
|
475
|
+
border-radius: 8px;
|
|
476
|
+
overflow: hidden;
|
|
477
|
+
background: var(--aia-product-media-bg, var(--aia-skeleton-bg, rgba(189, 189, 189, 0.25)));
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
.magicx-aia-product-image {
|
|
481
|
+
display: block;
|
|
482
|
+
width: 100%;
|
|
483
|
+
height: 100%;
|
|
484
|
+
object-fit: cover;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/* Placeholder tile for a product with no image \u2014 a faint glyph on the same
|
|
488
|
+
media fill, so a card without art reads as "no photo" instead of broken. */
|
|
489
|
+
.magicx-aia-product-media[data-aia-product-placeholder]::after {
|
|
490
|
+
content: "";
|
|
491
|
+
position: absolute;
|
|
492
|
+
inset: 30%;
|
|
493
|
+
border-radius: 3px;
|
|
494
|
+
border: 1.5px solid var(--aia-product-placeholder-color, var(--aia-option-color, #c1c4cb));
|
|
495
|
+
opacity: 0.35;
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/* The text column. Only the title is guaranteed; vendor and price render no
|
|
499
|
+
element at all when absent, so the gap can't reserve space for a missing
|
|
500
|
+
line. */
|
|
501
|
+
.magicx-aia-product-body {
|
|
502
|
+
display: flex;
|
|
503
|
+
flex-direction: column;
|
|
504
|
+
gap: 2px;
|
|
505
|
+
min-width: 0;
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
.magicx-aia-product-vendor {
|
|
509
|
+
font-family: inherit;
|
|
510
|
+
font-size: var(--aia-product-vendor-font-size, 10px);
|
|
511
|
+
line-height: 14px;
|
|
512
|
+
color: var(
|
|
513
|
+
--aia-product-vendor-color,
|
|
514
|
+
var(--aia-option-color, var(--aia-color-text-muted, #c1c4cb))
|
|
515
|
+
);
|
|
516
|
+
opacity: 0.8;
|
|
517
|
+
/* Vendor names are frequently long \u2014 one line, clipped. */
|
|
518
|
+
overflow: hidden;
|
|
519
|
+
white-space: nowrap;
|
|
520
|
+
text-overflow: ellipsis;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
.magicx-aia-product-title {
|
|
524
|
+
font-family: inherit;
|
|
525
|
+
font-size: var(--aia-product-title-font-size, 12px);
|
|
526
|
+
font-weight: 400;
|
|
527
|
+
line-height: 16px;
|
|
528
|
+
/* The card's most prominent text uses the same token the *highlighted*
|
|
529
|
+
option text does, so it stays legible on any --aia-surface a consumer
|
|
530
|
+
sets \u2014 light or dark \u2014 without a second theming control. */
|
|
531
|
+
color: var(
|
|
532
|
+
--aia-product-title-color,
|
|
533
|
+
var(--aia-option-color-selected, var(--aia-color-text-default, #fff))
|
|
534
|
+
);
|
|
535
|
+
display: -webkit-box;
|
|
536
|
+
-webkit-line-clamp: 2;
|
|
537
|
+
line-clamp: 2;
|
|
538
|
+
-webkit-box-orient: vertical;
|
|
539
|
+
overflow: hidden;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
.magicx-aia-product-price {
|
|
543
|
+
font-family: inherit;
|
|
544
|
+
font-size: var(--aia-product-price-font-size, 11px);
|
|
545
|
+
font-weight: 500;
|
|
546
|
+
line-height: 15px;
|
|
547
|
+
color: var(
|
|
548
|
+
--aia-product-price-color,
|
|
549
|
+
var(--aia-option-color-selected, var(--aia-color-text-default, #fff))
|
|
550
|
+
);
|
|
551
|
+
}
|
|
552
|
+
|
|
381
553
|
/* --- Footer (keyboard hint + AI-Autocomplete branding) ---
|
|
382
554
|
The footer insets its own 8px horizontally so it stays clear of the
|
|
383
555
|
dropdown's rounded edges. The top inset (--aia-footer-gap) adds breathing
|
|
@@ -973,7 +1145,15 @@ var N=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;t
|
|
|
973
1145
|
--aia-primitive-neutral-750-a35: rgba(189, 189, 189, 0.35);
|
|
974
1146
|
--aia-primitive-neutral-750-a30: rgba(189, 189, 189, 0.3);
|
|
975
1147
|
--aia-primitive-neutral-750-a15: rgba(189, 189, 189, 0.15);
|
|
1148
|
+
/* a105 is a15 lightened 30% (0.15 -> 0.105) \u2014 a fainter tint of the same
|
|
1149
|
+
gray, not a new color. Light mode only: over a WHITE surface a weaker
|
|
1150
|
+
tint is lighter, but over the dark theme's black surface it would be
|
|
1151
|
+
darker, so dark mode keeps a15. */
|
|
1152
|
+
--aia-primitive-neutral-750-a105: rgba(189, 189, 189, 0.105);
|
|
976
1153
|
--aia-primitive-neutral-700-a40: rgba(176, 176, 176, 0.4);
|
|
1154
|
+
/* Exactly 0.5, unlike the older 750-a50 above (0.51). */
|
|
1155
|
+
--aia-primitive-neutral-900-a50: rgba(231, 231, 231, 0.5);
|
|
1156
|
+
--aia-primitive-neutral-400-a50: rgba(74, 74, 74, 0.5);
|
|
977
1157
|
}
|
|
978
1158
|
|
|
979
1159
|
/* Light mode defaults (base) \u2014 public --aia-* vars resolve to primitives */
|
|
@@ -985,10 +1165,11 @@ var N=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;t
|
|
|
985
1165
|
--aia-shadow:
|
|
986
1166
|
inset 0 1px 0 rgba(255, 255, 255, 0.9), 0 1px 2px rgba(16, 24, 40, 0.1),
|
|
987
1167
|
0 8px 24px rgba(16, 24, 40, 0.16);
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
--aia-dropdown-
|
|
1168
|
+
/* Half-strength stroke: neutral-900 (was #e5e7eb \u2014 snapped to palette,
|
|
1169
|
+
\u03942) at 50% alpha over the surface, so the hairline lands exactly
|
|
1170
|
+
halfway between its old value and the white behind it. */
|
|
1171
|
+
--aia-dropdown-border: var(--aia-primitive-neutral-900-a50);
|
|
1172
|
+
--aia-dropdown-shadow: 0 8px 12px rgba(0, 0, 0, 0.05);
|
|
992
1173
|
/* Suggestion pills (Figma "ParamPill"): transparent fill + dashed border;
|
|
993
1174
|
per-pill opacity via getPillOpacity. --aia-pill-bg is retained for
|
|
994
1175
|
consumer overrides but the default ParamPill no longer paints a fill. */
|
|
@@ -1001,7 +1182,7 @@ var N=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;t
|
|
|
1001
1182
|
primary-color regular-weight text. -active is the hover / tapped (re-edit)
|
|
1002
1183
|
highlight \u2014 an alpha over the input background, so one value works in both
|
|
1003
1184
|
themes. */
|
|
1004
|
-
--aia-completed-pill-bg: var(--aia-primitive-neutral-750-
|
|
1185
|
+
--aia-completed-pill-bg: var(--aia-primitive-neutral-750-a105);
|
|
1005
1186
|
--aia-completed-pill-bg-active: var(--aia-primitive-neutral-750-a35);
|
|
1006
1187
|
--aia-completed-pill-color: var(--aia-primitive-neutral-0);
|
|
1007
1188
|
|
|
@@ -1040,10 +1221,10 @@ var N=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;t
|
|
|
1040
1221
|
--aia-shadow:
|
|
1041
1222
|
inset 0 1px 0 rgba(255, 255, 255, 0.06), 0 1px 2px rgba(0, 0, 0, 0.4),
|
|
1042
1223
|
0 8px 24px rgba(0, 0, 0, 0.5);
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
--aia-dropdown-shadow: 0 8px 12px rgba(0, 0, 0, 0.
|
|
1224
|
+
/* Half-strength stroke \u2014 neutral-400 (was #484848 \u2014 snapped to palette,
|
|
1225
|
+
\u03942) at 50% alpha; see the light-mode note above. */
|
|
1226
|
+
--aia-dropdown-border: var(--aia-primitive-neutral-400-a50);
|
|
1227
|
+
--aia-dropdown-shadow: 0 8px 12px rgba(0, 0, 0, 0.05);
|
|
1047
1228
|
/* Suggestion pills (Figma "ParamPill"): transparent fill + dashed border. */
|
|
1048
1229
|
--aia-pill-bg: var(--aia-primitive-neutral-750);
|
|
1049
1230
|
--aia-pill-color: var(--aia-primitive-neutral-700);
|
|
@@ -1051,7 +1232,11 @@ var N=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;t
|
|
|
1051
1232
|
--aia-pill-font-size: 14px;
|
|
1052
1233
|
|
|
1053
1234
|
/* Completed params (Figma "RichTextPill") \u2014 dark theme (design source):
|
|
1054
|
-
white text on a faint-gray chip. -active is the hover / tapped highlight.
|
|
1235
|
+
white text on a faint-gray chip. -active is the hover / tapped highlight.
|
|
1236
|
+
Deliberately still a15 while light mode moved to a105: the fill is a light
|
|
1237
|
+
gray tinting the surface, so thinning it lightens over white but DARKENS
|
|
1238
|
+
over this theme's black. Lightening the dark chip means a stronger tint,
|
|
1239
|
+
which is a design call, not a mechanical one \u2014 left for design to make. */
|
|
1055
1240
|
--aia-completed-pill-bg: var(--aia-primitive-neutral-750-a15);
|
|
1056
1241
|
--aia-completed-pill-bg-active: var(--aia-primitive-neutral-750-a35);
|
|
1057
1242
|
--aia-completed-pill-color: var(--aia-primitive-neutral-1000);
|
|
@@ -1108,6 +1293,25 @@ var N=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;t
|
|
|
1108
1293
|
--aia-footer-fade-inset: calc(-1 * var(--aia-footer-fade-lead)) 0 0;
|
|
1109
1294
|
}
|
|
1110
1295
|
|
|
1296
|
+
/* Product strip present: the footer no longer sits on the scrolling option
|
|
1297
|
+
list \u2014 the strip is between them \u2014 so there is nothing to ride up over and
|
|
1298
|
+
nothing to reserve. Zeroing the band HERE, where it is defined, is the fix:
|
|
1299
|
+
the pull is a property of "footer directly over the list", not of the grid,
|
|
1300
|
+
and any section rendered after the grid would otherwise inherit it and land
|
|
1301
|
+
on top of the last option row. Cancelling it from the new section's own
|
|
1302
|
+
rules would leave the next section after that to rediscover the same bug.
|
|
1303
|
+
Both edges are zeroed because optionsPosition="above" flips which one is in
|
|
1304
|
+
play. */
|
|
1305
|
+
[data-aia-dropdown][data-aia-has-products] {
|
|
1306
|
+
--aia-grid-scroll-bottom: 0px;
|
|
1307
|
+
--aia-grid-overlap-bottom: 0px;
|
|
1308
|
+
--aia-grid-scroll-top: 0px;
|
|
1309
|
+
--aia-grid-overlap-top: 0px;
|
|
1310
|
+
/* The fade exists to dissolve rows sliding under the footer. With the strip
|
|
1311
|
+
in between it has nothing to dissolve and would just wash over the cards. */
|
|
1312
|
+
--aia-footer-fade-lead: 0px;
|
|
1313
|
+
}
|
|
1314
|
+
|
|
1111
1315
|
/* The reserved band the footer overlaps, kept OUT of \`@layer layout\` on
|
|
1112
1316
|
purpose. A consumer reset (\`* { margin: 0; padding: 0 }\`, Tailwind's
|
|
1113
1317
|
preflight, \u2026) is unlayered, and an unlayered declaration beats every layered
|
|
@@ -1186,5 +1390,5 @@ var N=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;t
|
|
|
1186
1390
|
animation-duration: 0s !important;
|
|
1187
1391
|
transition-duration: 0s !important;
|
|
1188
1392
|
}
|
|
1189
|
-
`;var Z=class{constructor(){this.listeners={}}on(e,t){let i=(...o)=>t(...o),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 ee=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 R=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 yt(n){return(n??_).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function Pt(n){return D(n)?`Bearer ${await F(n).getToken()}`:B(n)}async function je(n){try{let e=yt(n.apiConfig?.endpoint),t=H(n.apiConfig),i=await Pt(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 vt="newParam",Ve="suggestionRemoval",Ct="selectionAnimation",wt=650,Tt=0;function Et(){return`:ac-${++Tt}:`}var Xe=500;function ze(){return{text:"",completedParams:[],identifiedParams:[],skippedParams:[],pendingSpan:null,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 fe=class{constructor(e,t={}){this.inputStore=me(ze());this._listboxId=Et();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new ee;this.emitter=new Z;this.sessionId=crypto.randomUUID();this.emitSubmit=e=>this.emitter.emit("submit",e);this.emitError=e=>this.emitter.emit("error",e);this.container=e,this.opts=t,this.renderMode=t.renderMode??"full",this.store=Ge(this.inputStore,i=>Re(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:o})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:r,other_pills:o})}}),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 U(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:o})=>{this.fireTelemetry("option",{raw_query:o,selected_option:r.text,other_options:(i.options??[]).filter(s=>s.text!==r.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(),fetchNow:()=>this.fetchNow()}),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.unsubscribers.push(this.store.subscribe((i,r)=>{if(i.text===r.text&&i.completedParams===r.completedParams||i.identifiedParams.length===0)return;let{valid:o,invalid:s}=K(i.text,i.completedParams,i.identifiedParams);s.length>0&&this.store.set({identifiedParams:o})})),this.unsubscribers.push(this.store.subscribe((i,r)=>{let o=i.pendingSpan;if(!o||i.text===r.text&&i.completedParams===r.completedParams&&i.identifiedParams===r.identifiedParams)return;let s=o.anchor;if(i.text!==r.text){let d=Ee(r.text,i.text,s);if(d===null){this.store.set({pendingSpan:null});return}s=d}i.text.slice(s).trim().length===0||we(i.segments,s)?this.store.set({pendingSpan:null}):s!==o.anchor&&this.store.set({pendingSpan:{anchor:s,snapshot:o.snapshot}})})),this.renderMode!=="headless"&&(We(),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({...ze(),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,o=0;for(let s=0;s<r.length;s++){let a=r[s],d=i.indexOf(a.text,o);if(d===-1)continue;let l=d,p=d+a.text.length;if(e>l&&e<=p){let c=oe(i,e),u=i.slice(0,c)+i.slice(e),f=r.filter((h,b)=>b!==s);return this.store.set(h=>({text:u,filterBase:Math.min(h.filterBase,u.length),completedParams:f,pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(c),!0}o=p}return!1}scheduleSetCursor(e){queueMicrotask(()=>{let t=this.domRefs;t?(t.input.focus(),C(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=qe(t,e);if(i&&(this.fireTelemetry("option",{raw_query:v(t.text,t.completedParams).rawQuery,selected_option:i.telemetry.selectedOption,other_options:i.telemetry.otherOptions}),this.store.set(i.patch),this.startSelectionAnimationTimer(),this.timers.clear(Ve),i.remainingActionable>0)){let r=i.consumedSuggestion;this.timers.schedule(Ve,()=>{this.store.set(o=>({suggestions:o.suggestions.filter(s=>s!==r)}))},Xe)}}startSelectionAnimationTimer(){this.timers.schedule(Ct,()=>this.store.set({inSelectionAnimation:!1}),Xe)}fireTelemetry(e,t){let i=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");je({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 R(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=Qe(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&ue(this.domRefs,this.store.get(),t)}),ue(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=Ke(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(vt,()=>this.store.set({newParamId:null}),wt)}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:r}=Oe(e,t.completedParams);r.length>0&&this.store.set({completedParams:i}),this.maybePromoteExactMatch(e),this.maybeOpenPendingSpan()}maybeOpenPendingSpan(){let e=this.store.get();if(e.pendingSpan||e.actionableSuggestions.length===0)return;let t=T(e.text,Math.min(e.filterBase,e.text.length),e.placeholderText),i=Ce(e.segments,t);e.text.slice(i).trim().length!==0&&this.store.set({pendingSpan:{anchor:i,snapshot:e.actionableSuggestions}})}maybeExitReEditOnNoMatch(){let e=this.store.get();if(!e.editingParam||e.editingAnchor==null||e.completedParams.some(o=>o.id===e.editingParam?.id))return;let t=e.caretOffset??e.editingAnchor,i=e.text.slice(e.editingAnchor,t);I(e.editingParam.options,i).some(o=>o.is_tappable)||(this.reEdit.exit(),this.fetchNow())}fetchNow(){let e=this.store.get(),{rawQuery:t,completedParams:i}=v(e.text,e.completedParams);this.fetchController.doFetch(t,i)}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)}};export{fe as AIAutocomplete,Ne as ATTRIBUTION_URL,R as ModeController,be as SKIPPED_PARAM_TEXT,ae as buildAttributionUrl,v as buildQuery,L as buildSubmitResult,me as createStore,re as cursorIsAtEnd,q as extractPlainText,w as getCursorOffset,le as getFooterHint,ie as plainTextLength,oe as previousGraphemeBoundary,pe as renderEditableContent,C as setCursorOffset,M as withSkippedParams};
|
|
1393
|
+
`;var ne=class{constructor(){this.reported=new Set}run(e,t){try{return t()}catch(n){this.report(e,n,e);return}}runListener(e,t,n=e){try{return t(),!0}catch(r){return this.report(e,r,n),!1}}report(e,t,n){this.reported.has(n)||(this.reported.add(n),console.error(`[AIAutocomplete] "${e}" threw. The error is contained \u2014 SDK state is unaffected. Later failures of "${e}" on this instance are not logged.`,t))}};var ie=class{constructor(e){this.boundary=e;this.listeners={};this.keys=new WeakMap;this.registrationCount=0}on(e,t){let n=`${String(e)}#${++this.registrationCount}`,r=(...a)=>t(...a);this.keys.set(r,n);let o=this.listeners[e];return o||(o=new Set,this.listeners[e]=o),o.add(r),()=>{this.listeners[e]?.delete(r)}}emit(e,...t){let n=this.listeners[e];if(!n)return!0;let r=!0;for(let o of n)this.boundary.runListener(String(e),()=>o(...t),this.keys.get(o)??String(e))||(r=!1);return r}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var re=class{constructor(){this.timers=new Map}schedule(e,t,n){this.clear(e);let r=setTimeout(()=>{this.timers.delete(e),t()},n);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 N=class{constructor(e,t="auto",n){this.container=e;this.mode=t;this.onResolve=n;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 Mt(i){return(i??H).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function Rt(i){return L(i)?`Bearer ${await F(i).getToken()}`:K(i)}async function et(i){try{let e=Mt(i.apiConfig?.endpoint),t=B(i.apiConfig),n=await Rt(i.apiConfig);n&&(t.Authorization=n);let r=JSON.stringify({source:i.source,session_id:i.sessionId,type:i.type,at:new Date().toISOString(),query_data:i.queryData});await fetch(e,{method:"POST",headers:t,body:r})}catch{}}var Nt="newParam",tt="suggestionRemoval",_t="selectionAnimation",Ht=650,Ft=0;function Bt(){return`:ac-${++Ft}:`}var nt=500;function it(){return{text:"",completedParams:[],identifiedParams:[],skippedParams:[],pendingSpan:null,suggestions:[],products:[],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 Pe=class{constructor(e,t={}){this.inputStore=ye(it());this._listboxId=Bt();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new re;this.boundary=new ne;this.subscriberCount=0;this.emitter=new ie(this.boundary);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=Je(this.inputStore,n=>Ke(n,this.deriveOpts())),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.onProductSelect&&this.emitter.on("productSelect",t.onProductSelect),t.value!==void 0&&this.store.set({text:t.value}),t.completedParams!==void 0&&this.store.set({completedParams:t.completedParams}),this.pillsController=new V(this.store,{onPillSelected:({rawQuery:n,selectedPill:r,otherPills:o})=>{this.fireTelemetry("pill",{raw_query:n,selected_pill:r,other_pills:o})}}),this.reEdit=new J({store:this.store,scheduleSetCursor:n=>this.scheduleSetCursor(n),fireTelemetry:(n,r)=>this.fireTelemetry(n,r),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer()}),this.productsController=new X(this.store,()=>this.opts.products),this.fetchController=new q(this.store,()=>this.opts.apiConfig,()=>this.deriveOpts().optionOverrides,()=>this.opts.maskCompletedText,()=>this.emitter.hasListeners("error")?this.emitError:void 0,()=>this.sessionId,{onRequest:({query:n,signal:r,isCurrent:o})=>{this.productsController.run(n,r,o).catch(()=>{})},onAutoMatch:({active:n,matched:r,rawQuery:o})=>{this.fireTelemetry("option",{raw_query:o,selected_option:r.text,other_options:(n.options??[]).filter(a=>a.text!==r.text).map(a=>a.text)})}}),this.keyboardController=new j(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:n=>this.selectOption(n),removeParamAtCaret:n=>this.removeParamAtCaret(n),startEditingParamAtCaret:n=>this.startEditingParamAtCaret(n),exitEditMode:()=>this.exitEditMode(),fetchNow:()=>this.fetchNow()}),this.unsubscribers.push(this.store.subscribe((n,r)=>{n.text!==r.text&&this.emitter.emit("change",n.text),n.completedParams!==r.completedParams&&this.emitter.emit("paramsChange",n.completedParams),n.isFocused!==r.isFocused&&(n.isFocused?this.emitter.emit("focus"):this.emitter.emit("blur")),this.emitter.emit("stateChange",n)})),this.unsubscribers.push(this.store.subscribe(()=>this.maybeExitReEditOnNoMatch())),this.unsubscribers.push(this.store.subscribe((n,r)=>{if(n.text===r.text&&n.completedParams===r.completedParams||n.identifiedParams.length===0)return;let{valid:o,invalid:a}=$(n.text,n.completedParams,n.identifiedParams);a.length>0&&this.store.set({identifiedParams:o})})),this.unsubscribers.push(this.store.subscribe((n,r)=>{let o=n.pendingSpan;if(!o||n.text===r.text&&n.completedParams===r.completedParams&&n.identifiedParams===r.identifiedParams)return;let a=o.anchor;if(n.text!==r.text){let d=Le(r.text,n.text,a);if(d===null){this.store.set({pendingSpan:null});return}a=d}n.text.slice(a).trim().length===0||ke(n.segments,a)?this.store.set({pendingSpan:null}):a!==o.anchor&&this.store.set({pendingSpan:{anchor:a,snapshot:o.snapshot}})})),this.renderMode!=="headless"&&(Ze(),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({...it(),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()}findChipSpanAt(e){let t=0;for(let n of this.store.get().segments){let r=t;if(t+=n.value.length,n.type!=="text"&&e>r&&e<=t)return{kind:n.type,param:n.param,start:r,end:t}}return null}withoutChip(e,t){return t.kind==="completed"?{completedParams:e.completedParams.filter(n=>n.id!==t.param.id)}:{identifiedParams:e.identifiedParams.filter(n=>n.id!==t.param.id)}}removeParamAtCaret(e){let t=this.findChipSpanAt(e);if(!t)return!1;let{text:n}=this.store.get(),{start:r,end:o}=t;if(e===o){let{text:d,removed:l}=Y(n,r,o);return this.store.set(c=>({text:d,filterBase:Math.min(c.filterBase>r?Math.max(r,c.filterBase-l):c.filterBase,d.length),...this.withoutChip(c,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(r),!0}let a=de(n,e),s=n.slice(0,a)+n.slice(e);return this.store.set(d=>({text:s,filterBase:Math.min(d.filterBase,s.length),...this.withoutChip(d,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(a),!0}startEditingParamAtCaret(e){let t=this.findChipSpanAt(e);return!t||t.kind!=="completed"||t.end!==e?!1:(this.reEdit.start(t.param.id),this.store.get().editingParam?.id===t.param.id)}scheduleSetCursor(e){queueMicrotask(()=>{let t=this.domRefs;if(t)t.input.focus(),C(t.input,e);else{let n=this.opts.setCursor;n&&this.boundary.runListener("setCursor",()=>n(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})}selectProduct(e){this.emitter.emit("productSelect",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){let t=`subscribe#${++this.subscriberCount}`;return this.store.subscribe(n=>{this.boundary.runListener("subscribe",()=>e(n),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){let t=this.opts.products;Object.assign(this.opts,e),"products"in e&&e.products!==t&&this.productsController.clearNow(),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 n=Ye(t,e);if(n&&(this.fireTelemetry("option",{raw_query:v(t.text,t.completedParams).rawQuery,selected_option:n.telemetry.selectedOption,other_options:n.telemetry.otherOptions}),this.store.set(n.patch),this.startSelectionAnimationTimer(),this.timers.clear(tt),n.remainingActionable>0)){let r=n.consumedSuggestion;this.timers.schedule(tt,()=>{this.store.set(o=>({suggestions:o.suggestions.filter(a=>a!==r)}))},nt)}}startSelectionAnimationTimer(){this.timers.schedule(_t,()=>this.store.set({inSelectionAnimation:!1}),nt)}fireTelemetry(e,t){let n=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");et({source:n,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}deriveOpts(){let e=this.opts.optionOverrides;if(!e)return this.opts;if(e!==this.rawOverrides){this.rawOverrides=e;let t={};for(let[n,r]of Object.entries(e))t[n]=o=>this.boundary.run(`optionOverrides.${n}`,()=>r(o));this.wrappedOverrides=t}return{...this.opts,optionOverrides:this.wrappedOverrides}}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 N(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:n=>this.selectOption(n),setActivePill:n=>this.pillsController.setActivePill(n),selectProduct:n=>this.selectProduct(n),handleKeyDown:n=>this.keyboardController.handleKeyDown(n),handleChange:n=>this.handleChange(n),startEditingParam:n=>this.startEditingParam(n),handleCaretAfterInput:n=>this.handleCaretAfterInput(n),handleCaretMove:n=>this.handleCaretMove(n),replaceEditingRange:n=>this.replaceEditingRange(n)};this.domRefs=ze(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&xe(this.domRefs,this.store.get(),t)}),xe(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),selectProduct:t=>this.selectProduct(t)};this.dropdownRefs=je(this.container,e),this.subscribeBatchedRender(()=>{this.dropdownRefs&&he(this.dropdownRefs,this.store.get(),e)}),he(this.dropdownRefs,this.store.get(),e),this.subscribeNewParamTimer()}subscribeBatchedRender(e){let t=!1;this.unsubscribers.push(this.store.subscribe(()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,t)=>{e.newParamId&&e.newParamId!==t.newParamId&&this.timers.schedule(Nt,()=>this.store.set({newParamId:null}),Ht)}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:n,invalid:r}=Ne(e,t.completedParams);r.length>0&&this.store.set({completedParams:n}),this.maybePromoteExactMatch(e),this.maybeOpenPendingSpan()}maybeOpenPendingSpan(){let e=this.store.get();if(e.pendingSpan||e.actionableSuggestions.length===0)return;let t=T(e.text,Math.min(e.filterBase,e.text.length),e.placeholderText),n=Oe(e.segments,t);e.text.slice(n).trim().length!==0&&this.store.set({pendingSpan:{anchor:n,snapshot:e.actionableSuggestions}})}maybeExitReEditOnNoMatch(){let e=this.store.get();if(!e.editingParam||e.editingAnchor==null||e.completedParams.some(o=>o.id===e.editingParam?.id))return;let t=e.caretOffset??e.editingAnchor,n=e.text.slice(e.editingAnchor,t);I(e.editingParam.options,n).some(o=>o.is_tappable)||(this.reEdit.exit(),this.fetchNow())}fetchNow(){let e=this.store.get(),{rawQuery:t,completedParams:n}=v(e.text,e.completedParams);this.fetchController.doFetch(t,n)}maybePromoteExactMatch(e){let t=this.store.get(),n=z({mode:"fresh",text:e,completedParams:t.completedParams,suggestions:t.suggestions,filterBase:t.filterBase,filterInProgress:t.filterInProgress});n&&this.store.set(n.patch)}};export{Pe as AIAutocomplete,Ue as ATTRIBUTION_URL,N as ModeController,Ce as SKIPPED_PARAM_TEXT,ue as buildAttributionUrl,v as buildQuery,R as buildSubmitResult,ye as createStore,le as cursorIsAtEnd,W as extractPlainText,w as getCursorOffset,me as getFooterHint,ae as plainTextLength,de as previousGraphemeBoundary,be as renderEditableContent,C as setCursorOffset,M as withSkippedParams};
|
|
1190
1394
|
//# sourceMappingURL=index.mjs.map
|