@magicx-eng/ai-autocomplete-vanilla 0.26.1 → 0.26.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +12 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
function Ke(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9]+/).filter(Boolean).map(e=>e.toLowerCase())}function B(n){let e=Ke(n);return e.length>0?e.join(" "):n}var Q=["January","February","March","April","May","June","July","August","September","October","November","December"],ue=["S","M","T","W","T","F","S"],Gt=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],$t="aiaDate",qt="aiaDay",Bt=n=>String(n).padStart(2,"0");function D(n){return`${n.getFullYear()}-${Bt(n.getMonth()+1)}-${Bt(n.getDate())}`}function Qe(n){return new Date(n.getFullYear(),n.getMonth(),n.getDate())}function bi(n){let e=Qe(n).getTime()-Qe(new Date).getTime();return Math.round(e/864e5)}function Vt(n){let e=bi(n);return e>=0&&e<7?Gt[n.getDay()]:Y(n)}function Y(n){return n.getFullYear()===new Date().getFullYear()?`${Q[n.getMonth()]} ${n.getDate()}`:`${Q[n.getMonth()]} ${n.getDate()} ${n.getFullYear()}`}function pe(n){if(!n)return null;let e=Gt.findIndex(a=>a.toLowerCase()===n.trim().toLowerCase());if(e>=0){let a=Qe(new Date),l=(e-a.getDay()+7)%7;return new Date(a.getFullYear(),a.getMonth(),a.getDate()+l)}let t=/^\s*([A-Za-z]+)\s+(\d{1,2})(?:\s+(\d{4}))?\s*$/.exec(n);if(!t)return null;let i=Q.findIndex(a=>a.toLowerCase()===t[1].toLowerCase());if(i<0)return null;let o=Number(t[2]),s=t[3]?Number(t[3]):new Date().getFullYear(),r=new Date(s,i,o);return r.getMonth()!==i||r.getDate()!==o?null:r}function Ye(n){return`${Q[n.month]} ${n.year}`}function je(){let n=new Date;return{year:n.getFullYear(),month:n.getMonth()}}function Ut(n){return{year:n.getFullYear(),month:n.getMonth()}}function ze(n,e){let t=new Date(n.year,n.month+e,1);return{year:t.getFullYear(),month:t.getMonth()}}function Wt(){return{text:"",is_tappable:!1,kind:null}}function Xe(n){let e=new Date(n.year,n.month,1).getDay(),t=new Date(n.year,n.month+1,0).getDate(),i=[];for(let o=0;o<e;o++)i.push(Wt());for(let o=1;o<=t;o++){let s=new Date(n.year,n.month,o);i.push({text:Vt(s),is_tappable:!0,kind:null,metadata:{[$t]:D(s),[qt]:o}})}for(;i.length%ue.length!==0;)i.push(Wt());return i}function Je(n){let e=pe(n);return e?D(e):null}function k(n){let e=n?.metadata?.[$t];return typeof e=="string"?e:null}function Ze(n){let e=n?.metadata?.[qt];return typeof e=="number"?e:null}function yi(n){return n.replace(/(\d+)(?:st|nd|rd|th)\b/g,"$1")}function Kt(n){let e=n.toLowerCase().replace(/\.$/,"");return e.length<3?-1:Q.findIndex(t=>t.toLowerCase().startsWith(e))}function Si(n,e,t){let i=new Date(t.getFullYear(),n,e);if(i.getMonth()!==n||i.getDate()!==e)return null;let o=new Date(t.getFullYear(),t.getMonth(),t.getDate());if(i>=o)return i;let s=new Date(t.getFullYear()+1,n,e);return s.getMonth()===n&&s.getDate()===e?s:null}function Qt(n,e,t){let i=new Date(n,e,t);return i.getMonth()===e&&i.getDate()===t?i:null}function W(n,e={}){if(!n)return null;let t=e.today??new Date,i=yi(n.trim().toLowerCase()).replace(/\s+/g," "),o=/^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(i);if(o){let l=Qt(Number(o[1]),Number(o[2])-1,Number(o[3]));return l?D(l):null}let s=/^([a-z]+)\.? (\d{1,2})(?:,? (\d{4}))?$/.exec(i);if(s){let l=Kt(s[1]);if(l>=0)return me(l,Number(s[2]),s[3],t)}let r=/^(\d{1,2}) (?:of )?([a-z]+)\.?(?:,? (\d{4}))?$/.exec(i);if(r){let l=Kt(r[2]);if(l>=0)return me(l,Number(r[1]),r[3],t)}let a=/^(\d{1,2})[/\-.](\d{1,2})(?:[/\-.](\d{2,4}))?$/.exec(i);if(a){let l=Number(a[1]),c=Number(a[2]);return l>12&&c<=12?me(c-1,l,a[3],t):c>12&&l<=12?me(l-1,c,a[3],t):null}return null}function me(n,e,t,i){if(t){if(t.length!==4)return null;let s=Qt(Number(t),n,e);return s?D(s):null}let o=Si(n,e,i);return o?D(o):null}function et(n,e={}){let t=n.isoDate;return typeof t=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t)?t:W(n.text,e)}var jt=" - ",nt="aiaDateRangeStart",it="aiaDateRangeEnd";function te(n,e){return n<=e?{start:n,end:e}:{start:e,end:n}}var tt=/^\d{4}-\d{2}-\d{2}$/;function Yt(n){if(!tt.test(n))return null;let[e,t,i]=n.split("-").map(Number),o=new Date(e,t-1,i);return o.getMonth()===t-1&&o.getDate()===i?o:null}var xi=/\s+(?:to|through|thru|until|til|till)\s+/g,vi=/[-–—]/g;function Pi(n){let e=[];for(let t of[xi,vi]){t.lastIndex=0;let i=t.exec(n);for(;i!==null;)e.push([n.slice(0,i.index),n.slice(i.index+i[0].length)]),i=t.exec(n)}return e}function j(n,e={}){if(!n)return null;let t=new Set,i=null;for(let[o,s]of Pi(n.trim())){let r=W(o.trim(),e);if(!r)continue;let a=W(s.trim(),e);!a||a<r||(t.add(`${r}|${a}`),i={start:r,end:a})}return t.size===1?i:null}function zt(n){let e=Yt(n.start),t=Yt(n.end);return!e||!t?"":n.start===n.end?Y(e):`${Y(e)}${jt}${Y(t)}`}function Xt(n,e){let t=te(n,e);return{text:zt(t),is_tappable:!0,kind:null,metadata:{[nt]:t.start,[it]:t.end}}}function ne(n,e={}){let t=n?.metadata?.[nt],i=n?.metadata?.[it];return typeof t=="string"&&typeof i=="string"&&tt.test(t)&&tt.test(i)?te(t,i):j(n?.text,e)}function E(n){return n==="date"||n==="date-range"}var Ei=new Set(["date","dates"]),wi=new Set(["range","ranges","span","period","window"]),Jt=3;function Ti(n){let e={single:0,range:0};if(!n)return e;for(let t of n)t.is_tappable&&(j(t.text)!==null?e.range+=1:W(t.text)!==null&&(e.single+=1));return e}function G(n){if(!n)return"options";let e=n.formatType;if(e==="date"||e==="options"||e==="date-range")return e;let t=Ti(n.options);if(t.single+t.range>=Jt&&t.range>t.single)return"date-range";let i=Ke(n.type);return i.some(o=>Ei.has(o))?i.some(o=>wi.has(o))?"date-range":"date":t.single>=Jt?"date":"options"}var fe=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 Ci="https://api.ai-autocomplete.com",ge=`${Ci}/api/suggest`,Zt=new WeakMap;function ie(n){return n?.type==="accessToken"}function Ai(n){if(!(!n||ie(n)))return n}function he(n){let e=Zt.get(n.getAccessToken);return e||(e=new fe(n),Zt.set(n.getAccessToken,e)),e}function be(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function ye(n){let e=Ai(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}function oe(n){return n.map(e=>({type:e.type,value:e.text}))}var en="skipped";function re(n,e){if(e.length===0)return n;let t=new Set(n.map(o=>o.type)),i=e.filter(o=>!t.has(o.type)).map(o=>({placeholder:"",type:o.type,text:en,kind:null}));return i.length>0?[...n,...i]:n}var Oi="0.26.1",tn=!1;function Ii(){return crypto.randomUUID()}function Ri(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.text},kind:n.kind}}function Di(n,e,t,i,o,s,r,a,l){let c=e.find(u=>u.type==="contact"&&u.metadata?.contact_account_count)?.metadata?.contact_account_count,d=typeof c=="number"?c:void 0;return{data:{raw_query:n,completed_params:re(e.map(u=>Ri(u,t)),a??[]),...s&&s.length>0&&{identified_params:oe(s)},...r&&r.length>0&&{recently_suggested:r},...d!=null&&{contact_account_count:d},...l!==void 0&&{additional_context:l}},meta:{request_id:Ii(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:Oi,session_id:i,source:o}}}async function nn(n,e,t,i,o){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:o})}async function on(n,e,t){let i=t.apiConfig,o=!t.maskCompletedText,s=Di(n,e,o,t.sessionId,t.source,t.identifiedParams,t.recentlySuggested,t.skippedParams,t.additionalContext),r=be(i),a=i?.endpoint??ge,l=JSON.stringify(s);if(ie(i)){let u=he(i),f=await u.getToken(),g=await nn(a,r,f,l,t.signal);if(g.status===401){let h=await u.getToken(!0);g=await nn(a,r,h,l,t.signal)}if(!g.ok)throw new Error(`API error: ${g.status} ${g.statusText}`);return g.json()}let c=ye(i);!c&&!tn&&(tn=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),c&&(r.Authorization=c);let d=await fetch(a,{method:"POST",headers:r,body:l,signal:t.signal});if(!d.ok)throw new Error(`API error: ${d.status} ${d.statusText}`);return d.json()}function I(n,e){let t=n,i={},o=[],s=[],r=0;for(let a of e){let l=(i[a.type]??0)+1;i[a.type]=l;let d=`{{${a.type.toUpperCase().replace(/\s+/g,"_")}_${l}}}`,u=g=>{let h=t.indexOf(a.text,g);for(;h!==-1&&s.some(y=>h<y.end&&h+a.text.length>y.start);)h=t.indexOf(a.text,h+1);return h},f=u(r);if(f===-1&&(f=u(0)),f!==-1){t=t.slice(0,f)+d+t.slice(f+a.text.length);let g=d.length-a.text.length;for(let h of s)h.start>=f+a.text.length&&(h.start+=g,h.end+=g);s.push({start:f,end:f+d.length}),r=f>=r?f+d.length:r+g}o.push({...a,placeholder:d})}return{rawQuery:t,completedParams:o}}function F(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function Se(n,e,t){return e===0&&n.length>0&&t.length>0&&t.toLowerCase().startsWith(n.toLowerCase())}function $(n,e,t){let i=n.slice(e);if(t||e===0||n[e-1]===" ")return i;let o=i.indexOf(" ");return o===-1?"":i.slice(o+1)}function rn(n,e){let t=n.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let i=t.split(" "),o=e.toLowerCase();for(let s=0;s<i.length;s++){let r=i.slice(s).join(" ");if(o.startsWith(r.toLowerCase())){let a=t.length-r.length;return n.length-a}}return 0}function q(n,e){if(!n)return[];let t=e.trimStart();if(!t)return n;let i=t.toLowerCase();return n.filter(o=>!o.is_tappable||o.text.toLowerCase().includes(i))}function z(n,e){if(!n)return null;let t=e.trim();if(!t)return null;let i=t.toLowerCase();return n.find(o=>o.is_tappable&&o.text.toLowerCase()===i)??null}function sn(n,e){return e?n.map(t=>e[t.type]?{...t,options:[]}:t):n}function an(n,e){let t=0,i=e;for(let o of n)t+=o.value.length,o.type!=="text"&&(i=Math.max(i,t));return i}function ln(n,e){let t=0;for(let i of n){let o=t+i.value.length;if(i.type==="text"&&o>e&&i.value.slice(Math.max(e-t,0)).trim().length>0)return!1;t=o}return!0}function dn(n,e){let t=[],i=new Set;for(let o of[...n,...e])o.type==="placeholder"||i.has(o.type)||(i.add(o.type),t.push({type:o.type,text:o.text}));return t}function cn(n,e,t){if(n===e)return t;let i=Math.min(n.length,e.length),o=0;for(;o<i&&n[o]===e[o];)o++;if(o>=t)return t;let s=0;for(;s<i-o&&n[n.length-1-s]===e[e.length-1-s];)s++;return n.length-s<=t?t+(e.length-n.length):null}function ot(n,e){let t=[],i=[],o=0;for(let s of e){let r=n.indexOf(s.text,o);if(r===-1){i.push(s);continue}t.push({start:r,end:r+s.text.length,param:s}),o=r+s.text.length}return{located:t,missing:i}}function un(n,e,t){let i=[],o=[],s=0;for(let r of t){let a=n.indexOf(r.text,s);for(;a!==-1&&e.some(l=>a<l.end&&a+r.text.length>l.start);)a=n.indexOf(r.text,a+1);if(a===-1){o.push(r);continue}i.push({start:a,end:a+r.text.length,param:r}),s=a+r.text.length}return{located:i,missing:o}}function pn(n,e,t=[]){let i=ot(n,e).located,o=un(n,i,t).located,s=[...i.map(c=>({start:c.start,end:c.end,segment:{type:"completed",value:c.param.text,param:c.param}})),...o.map(c=>({start:c.start,end:c.end,segment:{type:"identified",value:c.param.text,param:c.param}}))].sort((c,d)=>c.start-d.start),r=[],a=0;for(let c of s)c.start>a&&r.push({type:"text",value:n.slice(a,c.start)}),r.push(c.segment),a=c.end;let l=n.slice(a);return l&&r.push({type:"text",value:l}),r}function mn(n,e){let{located:t,missing:i}=ot(n,e);return{valid:t.map(o=>o.param),invalid:i}}function xe(n,e,t){let i=ot(n,e).located,{located:o,missing:s}=un(n,i,t);return{valid:o.map(r=>r.param),invalid:s}}function Li(n){if(n instanceof Error)return n;try{return new Error(String(n))}catch{return new Error("Unknown error")}}var Mi=100,ki=300,_i=2,ve=class{constructor(e,t,i,o,s,r,a,l,c={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=o;this.getOnError=s;this.getSessionId=r;this.getSource=a;this.getAdditionalContext=l;this.callbacks=c;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null}start(){this.doFetch("",[]);let e=this.store.get().text,t=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(i=>{(i.text!==e||i.completedParams!==t)&&(e=i.text,t=i.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let i=new AbortController;this.abortController=i;let o=++this.fetchVersion,s=this.store.get().text.length;try{this.callbacks.onRequest?.({query:this.store.get().text,signal:i.signal,isCurrent:()=>o===this.fetchVersion})}catch{}try{this.store.set({isLoading:!0,error:null});let r=this.store.get(),a=r.pendingSpan?dn(r.pendingSpan.snapshot,r.actionableSuggestions):void 0,l=await on(e,t,{sessionId:this.getSessionId(),source:this.getSource(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig(),identifiedParams:r.identifiedParams,recentlySuggested:a,skippedParams:r.skippedParams,additionalContext:this.getAdditionalContext()});if(o!==this.fetchVersion)return;let c=(l.data.input??[]).filter(x=>x.source==="identified").map(x=>({id:crypto.randomUUID(),type:x.type,text:x.text})),d=sn(l.data.suggestions??[],this.getOptionOverrides()),u=l.data.input??[],f=u[u.length-1],g=this.store.get().text,h,y;if(f?.state==="in_progress"){y=!0;let x=g.toLowerCase().lastIndexOf(f.text.toLowerCase());h=x!==-1?x:s}else y=!1,h=s;let p=d.filter(x=>x.type!=="placeholder")[0],m=null;if(p&&!E(G(p))){let x=$(g,h,y),w=z(p.options,x);w&&(m={id:crypto.randomUUID(),placeholder:"",type:p.type,text:w.text,kind:w.kind,suggestionType:p.type,suggestionPlaceholder:p.text,options:p.options??[],metadata:w.metadata,icon:w.icon,icon_svg:w.icon_svg},d=d.filter(T=>T!==p),this.callbacks.onAutoMatch?.({active:p,matched:w,rawQuery:e}))}let b=l.data.custom_fields??null,S=this.callbacks.productsForResponse?.(b);this.store.set(x=>{let w=m?[...x.completedParams,m]:x.completedParams,T=xe(x.text,w,c).valid,_=new Set(r.skippedParams.map(C=>C.id)),N=new Set(x.skippedParams.filter(C=>!_.has(C.id)).map(C=>C.type));return{suggestions:N.size>0?d.filter(C=>C.type==="placeholder"||!N.has(C.type)):d,isLoading:!1,isReady:l.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:h,filterInProgress:y,identifiedParams:T,customFields:b,...S!==void 0?{products:S}:{},...m?{completedParams:w}:{}}}),this.callbacks.onResponse?.()}catch(r){let a=Li(r);o===this.fetchVersion&&(this.store.set({error:a,isLoading:!1}),this.getOnError()?.(a))}finally{if(o===this.fetchVersion&&this.store.get().isLoading)try{this.store.set({isLoading:!1})}catch{}}}attemptNow(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}this.attemptFetch(1,!0)}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}this.debounceTimer=setTimeout(()=>{this.attemptFetch(_i)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},Mi),this.slowDebounceTimer=setTimeout(()=>this.attemptFetch(1),ki)}attemptFetch(e,t=!1){let i=this.store.get();if(!i.text&&i.completedParams.length===0)return this.doFetch("",[]),!0;let o=this.callbacks.consumerTick?.(i,e)??"no";if(o==="asked")return!0;if(o==="owns")return!1;let s=i.suggestions.filter(S=>S.type==="placeholder").map(S=>S.text).join(" "),r=F(i.text,i.filterBase,s),a=$(i.text,r,i.filterInProgress),c=i.suggestions.filter(S=>S.type!=="placeholder")[0],d=E(i.activeFormatType),f=(c&&!d?q(c.options,a):[]).filter(S=>S.is_tappable),g=c&&!d?z(c.options,a)!==null:!1,h=a.trim().length>0;if(f.length>0&&!g&&h||Se(i.text,i.completedParams.length,s))return!1;let{rawQuery:y,completedParams:v}=I(i.text,i.completedParams),p=y.length<i.lastRawQuery.length,m=Math.abs(y.length-i.lastRawQuery.length),b=t&&y!==i.lastRawQuery;return p||m>=e||b?(this.doFetch(y,v),!0):!1}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};function Ni(n){return n.nodeType===Node.DOCUMENT_NODE?!0:n.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in n}function V(n){let e=typeof n.getRootNode=="function"?n.getRootNode():null;return e&&Ni(e)?e:n.ownerDocument??n}function A(n){return n.ownerDocument??n}function Fi(n){return n.nodeType===Node.DOCUMENT_FRAGMENT_NODE}function fn(n){let e=V(n);return!Fi(e)||typeof e.getSelection=="function"?null:e}function gn(n){let e=fn(n);if(!e)return null;let t=A(n).getSelection?.();return!t||typeof t.getComposedRanges!="function"?null:e}function hn(n,e){let t=n,i;try{i=t.getComposedRanges({shadowRoots:[e]})}catch{i=t.getComposedRanges(e)}return i.length>0?i[0]:null}function rt(n){let t=V(n).getSelection?.();return t||(A(n).getSelection?.()??null)}function U(n){let e=rt(n);if(!e||e.rangeCount===0)return null;let t=gn(n);if(t){let i=hn(e,t);return i?{node:i.startContainer,offset:i.startOffset,collapsed:i.startContainer===i.endContainer&&i.startOffset===i.endOffset}:null}return e.anchorNode?{node:e.anchorNode,offset:e.anchorOffset,collapsed:e.isCollapsed}:null}function Pe(n){let e=rt(n);if(!e||e.rangeCount===0)return null;let t=gn(n);if(!t)return e.getRangeAt(0);let i=hn(e,t);if(!i)return null;let o=A(n).createRange();return o.setStart(i.startContainer,i.startOffset),o.setEnd(i.endContainer,i.endOffset),o}function se(n,e,t){let i=rt(n);if(!i)return null;if(fn(n))return i.collapse(e,t),i;let o=A(n).createRange();return o.setStart(e,t),o.collapse(!0),i.removeAllRanges(),i.addRange(o),i}function Ee(n,e){let t=n?V(n):typeof document<"u"?document:null;return t?typeof t.getElementById=="function"?t.getElementById(e):typeof document<"u"?document.getElementById(e):null:null}var we=2,Hi="magicx-aia";function bn(n){return n==="auto"||n==="scroll"||n==="hidden"||n==="overlay"}function Bi(n){let e=A(n),t=e.defaultView;if(!t?.getComputedStyle)return null;let i=n;for(;i&&i!==e.body&&i!==e.documentElement;){let o=i.scrollWidth>i.clientWidth,s=i.scrollHeight>i.clientHeight;if(o||s){let r=t.getComputedStyle(i);if(o&&bn(r.overflowX)||s&&bn(r.overflowY))return i}if(i.classList.contains(Hi))return null;i=i.parentElement}return null}function st(n){let e=Pe(n);if(!e||!e.collapsed||!n.contains(e.startContainer))return;let t=Bi(n);if(!t||typeof e.getBoundingClientRect!="function")return;let i=e.getBoundingClientRect();if(i.height===0)return;let o=t.getBoundingClientRect();if(t.scrollWidth>t.clientWidth){let s=o.left+t.clientLeft,r=s+t.clientWidth;i.right>r?t.scrollLeft+=i.right-r+we:i.left<s&&(t.scrollLeft-=s-i.left+we)}if(t.scrollHeight>t.clientHeight){let s=o.top+t.clientTop,r=s+t.clientHeight;i.bottom>r?t.scrollTop+=i.bottom-r+we:i.top<s&&(t.scrollTop-=s-i.top+we)}}var xn='[contenteditable="false"]',Wi="strong[data-param-id]",X;function Gi(){if(X!==void 0)return X;let n=globalThis.Intl.Segmenter;if(!n)return X=null,null;try{X=new n(void 0,{granularity:"grapheme"})}catch{X=null}return X??null}function Te(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(xn))return!0;t=t.parentNode}return!1}function Ce(n){return A(n).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return Te(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function Ae(n){let e=Ce(n),t="",i=e.nextNode();for(;i;)t+=i.data,i=e.nextNode();return t}function at(n){let e=Ce(n),t=0,i=e.nextNode();for(;i;)t+=i.data.length,i=e.nextNode();return t}function M(n){let e=U(n);if(!e)return null;let t=e.node,i=e.offset;if(!n.contains(t))return null;if(t.nodeType===Node.ELEMENT_NODE){let o=t;if(Te(o,n)&&o!==n)return null;let s=0;for(let r=0;r<i&&r<o.childNodes.length;r++)s+=vn(o.childNodes[r],n);return s+yn(o,n)}return t.nodeType!==Node.TEXT_NODE||Te(t,n)?null:yn(t,n)+i}function vn(n,e){if(n.nodeType===Node.TEXT_NODE)return Te(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(xn))return 0;let i=0;for(let o of Array.from(t.childNodes))i+=vn(o,e);return i}function yn(n,e){let t=Ce(e),i=0,o=t.nextNode();for(;o;){if(o===n||n.nodeType===Node.ELEMENT_NODE&&n.contains(o))return i;i+=o.data.length,o=t.nextNode()}return i}function R(n,e){let t=A(n),i=Math.max(0,Math.min(e,at(n))),o=Ce(n),s=0,r=null,a=0,l=o.nextNode(),c=null;for(;l;){let u=l.data.length;if(i<s+u){r=l,a=i-s;break}if(i===s+u){let f=o.nextNode();f?(r=f,a=0):(r=l,a=u);break}s+=u,c=l,l=o.nextNode()}let d=t.createRange();if(r){let u=r.parentElement?.closest('strong[data-seg="completed"]');u&&u!==n&&n.contains(u)?a===0?d.setStartBefore(u):a===r.data.length?d.setStartAfter(u):d.setStart(r,a):d.setStart(r,a)}else c?d.setStart(c,c.data.length):d.setStart(n,0);d.collapse(!0),se(n,d.startContainer,d.startOffset)&&($i(n,d,i),st(n))}function Sn(n,e){if(!n||!e.contains(n))return null;let i=(n.nodeType===Node.ELEMENT_NODE?n:n.parentElement)?.closest(Wi)??null;return i&&e.contains(i)?i:null}function $i(n,e,t){let i=Sn(U(n)?.node??null,n);if(i&&i!==Sn(e.startContainer,n)){n.dataset.aiaCaretEscapedChip=`${t}:${i.dataset.paramId}`;return}delete n.dataset.aiaCaretEscapedChip}function Pn(n,e){let t=n.dataset.aiaCaretEscapedChip;if(!t)return!1;let i=M(n);return i!==null&&t===`${i}:${e}`}function En(n){return V(n).activeElement===n}function lt(n){let e=M(n);return e==null?!1:e>=at(n)}function dt(n,e){if(e<=0)return 0;let t=Gi();if(!t)return e-1;let i=n.slice(0,e),o=0;for(let{index:s}of t.segment(i))s<e&&(o=s);return o}function K(n,e,t=[],i={}){let{rawQuery:o,completedParams:s}=I(n,e);return{query:n.trim(),raw_query:o,completed_params:re(s,t),identified_params:oe(i.identifiedParams??[]),is_ready:i.isReady??!1,...i.customFields?{custom_fields:i.customFields}:{}}}function ct(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")?lt(n):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function ut(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?M(n):null}var Oe=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:o}=this.ctx,s=e.target instanceof Node?e.target:null,r=this.getEffectiveColumns(s),a=o(),l=this.getTappableIndices(r);if((e.shiftKey||e.metaKey||e.ctrlKey||e.altKey)&&(e.key==="ArrowDown"||e.key==="ArrowUp"||e.key==="ArrowLeft"||e.key==="ArrowRight"))return;let c=this.ctx.getOptionsPosition()==="above";switch(e.key){case"ArrowDown":{let d=ct(e.target,t),u=!!t.editingParam;if(!d&&!u&&t.activeDropdownIndex<0)break;if(t.activeDropdownIndex<0){if(c)break;e.preventDefault();let h=E(t.activeFormatType)?this.dateEntryIndex(t,!1):l[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:h});break}if(l.length===0)return;this.store.set({activeDropdownIndex:h});break}if(e.preventDefault(),l.length===0)return;if(E(t.activeFormatType)){this.stepDateWeek(t,7);break}if(t.filteredOptions.length>0){let h=Math.floor((t.filteredOptions.length-1)/r);if(Math.floor(t.activeDropdownIndex/r)===h){this.store.set({activeDropdownIndex:-1});break}}let f=l.indexOf(t.activeDropdownIndex),g=f<l.length-1?f+1:0;this.store.set({activeDropdownIndex:l[g]});break}case"ArrowUp":{if(t.activeDropdownIndex<0){if(!c)break;let f=ct(e.target,t),g=!!t.editingParam;if(!f&&!g)break;e.preventDefault();let h=E(t.activeFormatType)?this.dateEntryIndex(t,!0):this.firstTappableInBottomRow(r)??l[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:h});break}if(l.length===0)return;this.store.set({activeDropdownIndex:h});break}if(l.length===0)break;if(e.preventDefault(),E(t.activeFormatType)){this.stepDateWeek(t,-7);break}if(t.activeDropdownIndex<r){this.store.set({activeDropdownIndex:-1});break}let d=l.indexOf(t.activeDropdownIndex),u=d>0?d-1:l.length-1;this.store.set({activeDropdownIndex:l[u]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),E(t.activeFormatType)){this.stepDateDay(t,1);break}if(t.activeDropdownIndex%r<r-1){let f=t.activeDropdownIndex+1;f<t.filteredOptions.length&&t.filteredOptions[f]?.is_tappable&&this.store.set({activeDropdownIndex:f})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let u=e.target.closest("[data-aia-input]")??e.target,f=t.editingTail;this.ctx.exitEditMode?.(),R(u,f);break}ct(e.target,t)&&t.actionableSuggestions.length>=1&&(e.preventDefault(),this.ctx.skipActivePill());break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),E(t.activeFormatType)){this.stepDateDay(t,-1);break}if(t.activeDropdownIndex%r>0){let d=t.activeDropdownIndex-1;d>=0&&t.filteredOptions[d]?.is_tappable&&this.store.set({activeDropdownIndex:d});break}if(!t.editingParam&&this.ctx.startEditingParamAtCaret){let d=ut(e.target);d!=null&&this.ctx.startEditingParamAtCaret(d)}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let d=e.target.closest("[data-aia-input]")??e.target,u=t.editingAnchor;this.ctx.exitEditMode?.(),R(d,u);break}if(this.ctx.startEditingParamAtCaret){let d=ut(e.target);d!=null&&this.ctx.startEditingParamAtCaret(d)&&e.preventDefault()}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let d=ut(e.target);if(d==null)break;this.ctx.removeParamAtCaret(d)&&e.preventDefault();break}case"Enter":{e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable?this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i,s):a&&a(K(t.text,t.completedParams,t.skippedParams,{identifiedParams:t.identifiedParams,isReady:t.isReady,customFields:t.customFields}))&&this.ctx.afterSubmit?.();break}case"Tab":{let d=t.filteredOptions.map((g,h)=>g.is_tappable?h:-1).filter(g=>g!==-1);if(d.length===0)break;if(!t.isDropdownOpen){if(t.actionableSuggestions.length===0)break;e.preventDefault();let g=e.shiftKey?d[d.length-1]:d[0];this.store.set({pillTapped:!0,activeDropdownIndex:g});break}e.preventDefault();let u=d.indexOf(t.activeDropdownIndex),f;if(u<0)f=e.shiftKey?d.length-1:0;else{let g=e.shiftKey?-1:1;f=(u+g+d.length)%d.length}this.store.set({activeDropdownIndex:d[f]});break}case"Escape":{if(t.dateRangeStart){this.store.set({pendingRangeStart:null});break}if(t.editingIdentified){this.ctx.exitEditingIdentified?.(),this.store.set({activeDropdownIndex:-1});break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){let d=e.target.closest("[data-aia-input]")??e.target,u=t.editingTail;this.ctx.exitEditMode?.(),R(d,u)}this.store.set({activeDropdownIndex:-1});break}}}firstTappableInBottomRow(e){let t=this.store.get();if(t.filteredOptions.length===0)return null;let o=Math.floor((t.filteredOptions.length-1)/e)*e;for(let s=o;s<t.filteredOptions.length;s++)if(t.filteredOptions[s]?.is_tappable)return s;return null}dateEntryIndex(e,t){let i=D(new Date),o=e.filteredOptions.findIndex(r=>k(r)===i);if(o>=0)return o;let s=e.filteredOptions.map((r,a)=>r.is_tappable?a:-1).filter(r=>r!==-1);return(t?s[s.length-1]:s[0])??0}stepDateDay(e,t){for(let i=e.activeDropdownIndex+t;i>=0&&i<e.filteredOptions.length;i+=t)if(e.filteredOptions[i]?.is_tappable){this.store.set({activeDropdownIndex:i});return}}stepDateWeek(e,t){let i=e.activeDropdownIndex+t;this.store.set({activeDropdownIndex:e.filteredOptions[i]?.is_tappable?i:-1})}getTappableIndices(e){let i=this.store.get().filteredOptions.map((s,r)=>s.is_tappable?r:-1).filter(s=>s!==-1),o=Array.from({length:e},()=>[]);for(let s of i)o[s%e].push(s);return o.flat()}getEffectiveColumns(e){let t=Ee(e,this.ctx.listboxId);if(!t)return this.ctx.columns;let o=Ee(e,`${this.ctx.listboxId}-option-0`)?.parentElement??null;for(;o;){let s=getComputedStyle(o).gridTemplateColumns;if(s&&s!=="none"){let r=s.split(" ").filter(Boolean).length;if(r>0)return r}if(o===t)break;o=o.parentElement}return this.ctx.columns}clickOrSelect(e,t,i,o){let s=Ee(o,`${i}-option-${e}`);s?s.click():this.ctx.selectOption(t[e])}};var Ie=class{constructor(e,t,i={}){this.store=e;this.getOverrides=t;this.callbacks=i;this.unsubscribe=null;this.current=null;this.version=0;this.lastMiss=null;this.hasLoggedError=!1}start(){this.unsubscribe=this.store.subscribe(e=>this.sync(e)),this.sync(this.store.get())}dispose(){this.unsubscribe?.(),this.unsubscribe=null,this.cancel(),this.current=null}reset(){this.cancel(),this.current=null,this.lastMiss=null}refresh(){this.reset(),this.sync(this.store.get())}hasOverride(e){return!!this.getOverrides()?.[e]}owns(e,t){return this.hasOverride(e)&&!this.missCovers(e,t)}tick(e,t){let i=this.resolveTarget(e);if(!i||this.missCovers(i.type,i.query))return"no";let o=this.current;if(o&&o.key===i.key){if(o.query===i.query)return"owns";let s=Math.abs(i.query.length-o.query.length),r=i.query.length<o.query.length;if(t>1&&!r&&s<t)return"owns"}return this.ask(i),"asked"}sync(e){let t=this.resolveTarget(e);if(!t){this.current&&(this.cancel(),this.current=null),e.optionSearch&&this.store.set({optionSearch:null});return}this.current&&this.current.key===t.key||this.ask(t)}resolveTarget(e){if(E(e.activeFormatType)||e.editingIdentified)return null;let t=e.editingParam;if(t&&e.editingAnchor!=null)return this.hasOverride(t.suggestionType)?{mode:"edit",key:t.id,type:t.suggestionType,suggestion:{type:t.suggestionType,text:t.suggestionPlaceholder,required:!0,options:t.options},query:e.optionQuery}:null;let i=e.actionableSuggestions[0];return!i||!this.hasOverride(i.type)?null:{mode:"pill",key:i,type:i.type,suggestion:i,query:e.optionQuery}}missCovers(e,t){return this.lastMiss!=null&&this.lastMiss.type===e&&this.lastMiss.query===t}ask(e){this.cancel();let t=this.getOverrides()?.[e.type],i=++this.version;if(!t||this.missCovers(e.type,e.query)){this.current={key:e.key,type:e.type,query:e.query,abort:null},this.setSearch(e,"done");return}let o=new AbortController;this.current={key:e.key,type:e.type,query:e.query,abort:o};let s;try{s=t(e.query,o.signal,e.suggestion)}catch(r){this.logOnce(r),this.commit(e,[],i);return}if(Array.isArray(s)){this.commit(e,s,i);return}this.setSearch(e,"loading"),this.await(e,s,o.signal,i)}async await(e,t,i,o){let s;try{let r=await t;if(i.aborted||o!==this.version)return;s=Array.isArray(r)?r:[]}catch(r){if(i.aborted||o!==this.version||qi(r))return;this.logOnce(r),s=[]}this.commit(e,s,o)}commit(e,t,i){if(i!==this.version)return;let o=this.resolveTarget(this.store.get());if(!o||o.key!==e.key)return;t.length===0?this.lastMiss={type:e.type,query:e.query}:this.lastMiss?.type===e.type&&(this.lastMiss=null);let s={type:e.type,query:e.query,status:"done"};if(e.mode==="edit")this.store.set(r=>({editingParam:r.editingParam&&r.editingParam.id===e.key?{...r.editingParam,options:t}:r.editingParam,optionSearch:s}));else{let r={...e.suggestion,options:t};this.current&&this.current.key===e.key&&(this.current.key=r),this.store.set(a=>({suggestions:a.suggestions.map(l=>l===e.suggestion?r:l),optionSearch:s}))}t.length===0?this.callbacks.onMiss?.(e.mode,e.query):this.callbacks.onAnswer?.(e.mode,e.query)}setSearch(e,t){let i=this.store.get().optionSearch;i&&i.type===e.type&&i.query===e.query&&i.status===t||this.store.set({optionSearch:{type:e.type,query:e.query,status:t}})}cancel(){this.current?.abort?.abort(),this.version++}logOnce(e){this.hasLoggedError||(this.hasLoggedError=!0,console.warn("[AIAutocomplete] an optionOverrides entry threw or rejected \u2014 treated as no options. Later failures on this instance are not logged.",e))}};function qi(n){return n instanceof Error&&n.name==="AbortError"}var Re=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),i=t.suggestions.filter(c=>c.type!=="placeholder");if(e<0||e>=i.length)return;let o=i[e],s=i.filter((c,d)=>d!==e),r=t.suggestions.filter(c=>c.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:c}=I(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:c,selectedPill:o.text,otherPills:s.map(d=>d.text)})}let a=[...r,o,...s],l=this.store.peek({suggestions:a}).filteredOptions.findIndex(c=>c.is_tappable);this.store.set({suggestions:a,pillTapped:!0,activeDropdownIndex:l})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};var Tn="/products/",wn="https://relative.invalid";function Vi(n){if(!n)return;let e;try{e=new URL(n,`${wn}/`)}catch{return}if(!(e.protocol!=="http:"&&e.protocol!=="https:"))return n.startsWith("/")?e.origin===wn?n:void 0:/^https?:\/\//i.test(n)?n:void 0}function Cn(n){let e=Vi(n.item_url)??(n.handle?`${Tn}${encodeURIComponent(n.handle)}`:void 0);return{id:n.source_id,title:n.title,...e&&{url:e},imageUrl:n.image_url||null,...n.price&&{price:n.price},...n.vendor&&{vendor:n.vendor}}}function pt(n){return(n?.items.matched??[]).map(Cn)}var De=class{constructor(e,t,i=()=>!0){this.store=e;this.getConfig=t;this.isEnabled=i;this.hasLoggedError=!1}forResponse(e){if(!this.isEnabled())return[];if(!this.getConfig())return pt(e)}async run(e,t,i){if(!this.isEnabled())return;let o=this.getConfig();if(!o)return;if(e.trim().length===0){this.clear(i);return}let s=()=>t.aborted||!i()||!this.owns(o);try{let r=await o.fetch(e,t);if(s())return;let a=o.transform(r),l=Array.isArray(a)?a:[],c=o.limit!=null?l.slice(0,o.limit):l;if(s())return;this.commit(c)}catch(r){if(t.aborted||Ui(r)||(this.logOnce(r),s()))return;this.clear(i)}}owns(e){return this.isEnabled()&&this.getConfig()===e}resync(){let e=this.forResponse(this.store.get().customFields);this.commit(e??[])}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 Ui(n){return n instanceof Error&&n.name==="AbortError"}var Le="(max-width: 768px)";var Ki="var(--aia-option-row-height, 37px)",Qi="var(--aia-grid-scroll-top, 0px) + var(--aia-grid-scroll-bottom, 0px)";function An(n,e){return e?mt(1,Math.min(n,5)):mt(1,Math.min(n,4))}function mt(n,e){return{cols:n,rows:e,maxHeight:`calc(${e} * ${Ki} + ${Qi})`}}function gt(n,e){return!e&&n>=5}function ht(n,e,t,i){if(!(!e&&n>=5&&Yi(t,i))){let r=An(n,e);return{...r,template:ft(r.cols),scrollHintIndices:!e&&n>r.rows?[r.rows-1]:[]}}let s=6;return{...mt(2,3),template:ft(2),scrollHintIndices:n>s?[s-2,s-1]:[]}}function Yi(n,e){return!n||n.length===0||e==null||e<=0||n.some(i=>i<=0)?!1:Math.ceil(Math.max(...n))*2<=e}function bt(n){if(typeof document>"u")return null;let e=Array.from(n.querySelectorAll("[data-aia-option]"));if(e.length===0)return null;let t=document.createElement("div");t.style.cssText="position:absolute;visibility:hidden;left:-9999px;top:0;";for(let r of e){let a=r.cloneNode(!0);a.removeAttribute("id"),a.removeAttribute("role"),a.removeAttribute("aria-selected"),a.style.whiteSpace="nowrap",a.style.width="max-content",t.appendChild(a)}n.appendChild(t);let i=Array.from(t.children).map(r=>r.offsetWidth);t.remove();let o=getComputedStyle(n),s=n.clientWidth-(Number.parseFloat(o.paddingLeft)||0)-(Number.parseFloat(o.paddingRight)||0)-(Number.parseFloat(o.columnGap)||0);return{rowWidths:i,gridWidth:s}}function ft(n){return Array.from({length:n},()=>"minmax(0,1fr)").join(" ")}function yt(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(Le).matches}function On(n,e){let t=e.dropdownTrigger??"auto",i=e.closeDropdownOnBlur??!0,r=n.filteredOptionsLength>0||n.activePillHasNoOptions||n.hasProducts;if(n.inEditMode){let a=i?n.isFocused:!0;return r&&a}if(t==="auto"){let a=i?n.isFocused:!0,l=n.text.replace(/\s+$/,"").length,c=n.caretOffset==null||n.caretOffset>=l;return(r||n.isLoading)&&a&&c}return t==="manual"?(r||n.isLoading)&&n.pillTapped:!1}function ae(n){if(n.editingIdentified){let{type:t,anchor:i}=n.editingIdentified;return`identified:${t}@${i}`}return n.editingParam!=null&&n.editingAnchor!=null?`edit:${n.editingParam?.id}`:`pill:${n.actionableSuggestions[0]?.type??""}`}function In(n){if(!n)return je();let[e,t]=n.split("-").map(Number);return{year:e,month:t-1}}function ji(n){let e=pe(n);return e?Ut(e):je()}function Rn(n,e){let t=pn(n.text,n.completedParams,n.identifiedParams),i=n.suggestions.filter(P=>P.type!=="placeholder"),o=i[0],s=n.suggestions.filter(P=>P.type==="placeholder").map(P=>P.text).join(" "),r=F(n.text,Math.min(n.filterBase,n.text.length),s),l=r===0&&Se(n.text,n.completedParams.length,s)?"":$(n.text,r,n.filterInProgress),c=o?.options??[],d=n.editingParam!=null&&n.editingAnchor!=null,u,f,g,h;if(d&&n.editingParam&&n.editingAnchor!=null){let P=n.editingParam.id,L=n.completedParams.some(hi=>hi.id===P),ee=n.caretOffset??n.editingAnchor,Ht=L?"":n.text.slice(n.editingAnchor,ee);f=Ht.trim(),g=n.editingParam.options,h=n.editingParam.suggestionType,u=q(n.editingParam.options,Ht)}else f=l.trim(),g=c,h=o?.type,u=q(c,l);let y=n.optionSearch,v=y!=null&&h!=null&&y.type===h;v&&y.status==="done"&&y.query===f&&(u=g);let p=v&&y.status==="loading",m=e.showNonTappableOptions===!1;m&&(u=u.filter(P=>P.is_tappable));let b=n.editingIdentified,S=d?n.editingParam&&{type:n.editingParam.suggestionType,options:n.editingParam.options}:o,x=b?b.format:G(S),w=d&&E(x)?ne(n.editingParam):null;w&&(x="date-range");let T=null,_=null;if(E(x)){let P=ae({...n,actionableSuggestions:i}),L=n.dateViewMonth;T=L&&L.key===P?{year:L.year,month:L.month}:b?In(b.iso):w?In(w.start):ji(n.editingParam?.text),u=Xe(T);let ee=n.pendingRangeStart;x==="date-range"&&ee&&ee.key===P&&(_=ee.iso)}let N=P=>m?P.is_tappable:!0,O;if(d){let P=n.editingParam?.options??[];O=n.editingParam!=null&&P.filter(N).length===0}else O=o!=null&&c.filter(N).length===0;let C=On({inEditMode:d||b!=null,filteredOptionsLength:u.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading||p,pillTapped:n.pillTapped,activePillHasNoOptions:O,hasProducts:n.products.length>0},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),Ue=C&&n.activeDropdownIndex>=0&&!!u[n.activeDropdownIndex]?.is_tappable;return{segments:t,actionableSuggestions:i,filteredOptions:u,activeFormatType:x,dateView:T,dateRangeStart:_,placeholderText:s,optionQuery:f,isSearchingOptions:p,isDropdownOpen:C,isActivePillSelected:Ue}}function Me(n){return n.mode==="fresh"?zi(n):Xi(n)}function zi(n){let{text:e,completedParams:t,suggestions:i,filterBase:o,filterInProgress:s}=n,a=i.filter(S=>S.type!=="placeholder")[0];if(!a?.options)return null;let l=i.filter(S=>S.type==="placeholder").map(S=>S.text).join(" "),c=F(e,o,l),d=$(e,c,s),u=z(a.options,d);if(!u)return null;let f=u.text.toLowerCase(),g=e.toLowerCase().lastIndexOf(f),h=g>=0?g:Math.max(0,e.length-u.text.length),y=h+u.text.length,v=e.slice(h,y),m=y<e.length&&e[y]===" "?y+1:y,b={id:crypto.randomUUID(),placeholder:"",type:a.type,text:v,kind:u.kind,suggestionType:a.type,suggestionPlaceholder:a.text,options:a.options??[],metadata:u.metadata,icon:u.icon,icon_svg:u.icon_svg};return{patch:{text:e,completedParams:[...t,b],suggestions:i.filter(S=>S!==a),filterBase:m,newParamId:b.id,caretOffset:m,activeDropdownIndex:-1},caretPos:m}}function Xi(n){let{text:e,completedParams:t,editingParam:i,editingAnchor:o,editingTail:s}=n;if(t.some(b=>b.id===i.id))return null;let r=e.slice(o,s),a=z(i.options,r);if(!a)return null;let l=a.text.toLowerCase(),c=r.toLowerCase().lastIndexOf(l),d=o+Math.max(0,c),u=d+a.text.length,f=e.slice(d,u),g=u<e.length&&e[u]===" "?u+1:u,h=e.length,y={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:f,kind:a.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:a.metadata,icon:a.icon,icon_svg:a.icon_svg},v=t.length,p=0;for(let b=0;b<t.length;b++){let S=e.indexOf(t[b].text,p);if(S!==-1){if(S>=g){v=b;break}p=S+t[b].text.length}}let m=[...t];return m.splice(v,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 ke(n,e,t){let i=n.slice(0,e),o=n.slice(t),s=(i===""||i.endsWith(" "))&&o.startsWith(" ");return s&&(o=o.slice(1)),{text:i+o,removed:t-e+(s?1:0)}}var _e=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(r=>r.id===e);if(!i)return;let o=0,s=-1;for(let r of t.completedParams){let a=t.text.indexOf(r.text,o);if(a!==-1){if(r.id===e){s=a;break}o=a+r.text.length}}s<0||this.deps.store.set({editingParam:i,editingAnchor:s,editingTail:s+i.text.length,caretOffset:s+i.text.length,activeDropdownIndex:-1,editingIdentified:null})}exit(){this.deps.store.get().editingParam&&this.deps.store.set({editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1})}replaceRange(e){let t=this.deps.store.get(),i=t.editingParam,o=t.editingAnchor,s=t.editingTail;if(!i||o==null||s==null||!t.completedParams.some(l=>l.id===i.id))return!1;let{text:r}=e===""?ke(t.text,o,s):{text:t.text.slice(0,o)+e+t.text.slice(s)},a=o+e.length;return this.deps.store.set(l=>({text:r,completedParams:l.completedParams.filter(c=>c.id!==i.id),editingTail:a,caretOffset:a,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(a),this.promoteIfExact(),!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.promoteIfExact()}caretMove(e){let t=this.deps.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null&&e!=null&&(e<t.editingAnchor||e>t.editingTail)){this.deps.store.set({caretOffset:e,editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1});return}this.deps.store.set({caretOffset:e})}selectOption(e){let t=this.deps.store.get(),i=t.editingParam,o=t.editingAnchor,s=t.editingTail;if(!i||o==null||s==null)return;this.deps.fireTelemetry("option",{raw_query:I(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:i.options.filter(p=>p.text!==e.text).map(p=>p.text)});let r=t.text.slice(0,o),a=t.text.slice(s),l=o===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,d=a.length===0||a[0]!==" "?`${l} `:l,u=r+d+a,f=u.length,g={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:l,kind:e.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg},h=t.completedParams.findIndex(p=>p.id===i.id),y=t.completedParams.filter(p=>p.id!==i.id),v=h>=0?Math.min(h,y.length):y.length;y.splice(v,0,g),this.deps.store.set({text:u,completedParams:y,newParamId:g.id,filterBase:f,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:f,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.deps.startSelectionAnimationTimer(),this.deps.scheduleSetCursor(f),this.deps.fetchNow()}promoteIfExact(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let t=Me({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 Ji=33,Zi=70,eo=120,to=50,J="data-aia-placeholder-leaving",Z=new WeakMap;function Ne(n){n.timer!==null&&(clearTimeout(n.timer),n.timer=null)}function no(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function Ln(n,e,t){e.shown=t,n.dataset.placeholder=e.target.slice(0,t)}function Mn(n,e){if(e.timer=null,!n.isConnected||e.shown>=e.target.length||(Ln(n,e,e.shown+1),e.shown>=e.target.length))return;let t=e.target[e.shown-1],i=t===" "||t==="-"?70:0;e.timer=setTimeout(()=>Mn(n,e),33+i)}function Dn(n,e){Ln(n,e,0),e.timer=setTimeout(()=>Mn(n,e),33)}function kn(n,e){let t=Z.get(n);if(e===""){t&&(Ne(t),Z.delete(n)),n.removeAttribute(J),delete n.dataset.placeholder;return}if(t?.target===e)return;if(no(n)){t&&Ne(t),n.removeAttribute(J),Z.set(n,{target:e,shown:e.length,timer:null}),n.dataset.placeholder=e;return}let i={target:e,shown:0,timer:null},o=t&&t.shown>0?t:null;if(t&&Ne(t),Z.set(n,i),o){n.setAttribute(J,""),i.timer=setTimeout(()=>{i.timer=null,n.removeAttribute(J),n.isConnected&&Dn(n,i)},170);return}n.removeAttribute(J),Dn(n,i)}function _n(n){let e=Z.get(n);e&&(Ne(e),Z.delete(n))}var Nn="https://ai-autocomplete.com";function St(n=Nn){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 xt(n,e){return n?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}var io={selectedIso:null,selectedRange:null,rangeStart:null};function le(n){if(!E(n.activeFormatType))return io;let e=n.editingIdentified;if(e){let{iso:i,isoEnd:o}=e;return{selectedIso:o?null:i,selectedRange:i&&o?te(i,o):null,rangeStart:n.dateRangeStart}}let t=ne(n.editingParam);return{selectedIso:t?null:Je(n.editingParam?.text),selectedRange:t,rangeStart:n.dateRangeStart}}function vt(n){return n.pendingStart?te(n.pendingStart,n.highlightedIso??n.pendingStart):n.selected}function Pt(n,e){if(n==null)return{selected:!1,inRange:!1};let{selectedIso:t,range:i}=e,o=n===t||i!=null&&(n===i.start||n===i.end),s=i!=null&&n>i.start&&n<i.end;return{selected:o,inRange:s}}var Fn="data-aia-key";function H(n,e,t){let i=new Map;for(let r of Array.from(n.children)){let a=r.getAttribute(Fn);a!=null&&i.set(a,r)}let o=new Set,s=[];for(let r=0;r<e.length;r++){let a=e[r],l=t.keyOf(a,r);o.add(l);let c=i.get(l);c||(c=t.create(a,r),c.setAttribute(Fn,l)),t.update?.(c,a,r),n.children[r]!==c&&n.insertBefore(c,n.children[r]??null),s.push(c)}for(let[r,a]of i)o.has(r)||a.remove();return s}function Bn(n,e,t,i,o,s,r){let a=n.querySelector(".magicx-aia-datepicker");if(!o||e.length===0){a?.remove();return}a||(a=so(),n.appendChild(a));let l=a.querySelector(".magicx-aia-datepicker-month");l&&(l.textContent=Ye(o));let c=a.querySelector("[data-aia-date-prev]"),d=a.querySelector("[data-aia-date-next]");c&&(c.onclick=()=>r.onPreviousMonth()),d&&(d.onclick=()=>r.onNextMonth());let u=a.querySelector(".magicx-aia-datepicker-grid");u&&oo(u,e,t,i,s,r)}function oo(n,e,t,i,o,s){let r=D(new Date),a=vt({pendingStart:o.rangeStart,highlightedIso:k(e[t]),selected:o.selectedRange});H(n,e,{keyOf:(l,c)=>k(l)??`pad-${c}`,create:l=>ro(l),update:(l,c,d)=>{let u=k(c),f=Pt(u,{selectedIso:o.selectedIso,range:a}),g=d===t&&c.is_tappable;l.id=`${i}-option-${d}`,l.dataset.aiaIndex=String(d),l.setAttribute("aria-selected",String(g)),l.classList.toggle("magicx-aia-date-cell--past",u!=null&&u<r),l.classList.toggle("magicx-aia-date-cell--highlighted",g),l.classList.toggle("magicx-aia-date-cell--today",u!=null&&u===r),l.classList.toggle("magicx-aia-date-cell--selected",f.selected),l.classList.toggle("magicx-aia-date-cell--in-range",f.inRange),c.is_tappable?(l.onclick=()=>{l.classList.add("magicx-aia-date-cell--pressed"),s.onSelect(c),setTimeout(()=>l.classList.remove("magicx-aia-date-cell--pressed"),170)},l.onmouseenter=()=>{let h=Number.parseInt(l.dataset.aiaIndex??"-1",10);h>=0&&s.onHighlight(h)}):(l.onclick=null,l.onmouseenter=null)}})}function ro(n){let e=document.createElement("div");e.setAttribute("role","option"),e.setAttribute("data-aia-option",""),e.setAttribute("data-aia-date-cell","");let t=Ze(n);if(t==null)return e.className="magicx-aia-date-cell magicx-aia-date-cell--blank",e.setAttribute("aria-hidden","true"),e.tabIndex=-1,e;e.className="magicx-aia-date-cell magicx-aia-date-cell--day",e.tabIndex=0,e.setAttribute("aria-label",n.text);let i=document.createElement("span");return i.className="magicx-aia-date-cell-number",i.textContent=String(t),e.appendChild(i),e}function so(){let n=document.createElement("div");n.className="magicx-aia-datepicker",n.setAttribute("data-aia-datepicker","");let e=document.createElement("div");e.className="magicx-aia-datepicker-header";let t=document.createElement("span");t.className="magicx-aia-datepicker-month",t.setAttribute("data-aia-date-month",""),t.setAttribute("aria-live","polite"),e.append(Hn("prev","Previous month","\u2039"),t,Hn("next","Next month","\u203A"));let i=document.createElement("div");i.className="magicx-aia-datepicker-weekdays",i.setAttribute("aria-hidden","true");for(let s of ue){let r=document.createElement("span");r.className="magicx-aia-datepicker-weekday",r.textContent=s,i.appendChild(r)}let o=document.createElement("div");return o.className="magicx-aia-datepicker-grid",o.setAttribute("data-aia-date-grid",""),n.append(e,i,o),n}function Hn(n,e,t){let i=document.createElement("button");return i.type="button",i.tabIndex=-1,i.className="magicx-aia-datepicker-nav",i.setAttribute(`data-aia-date-${n}`,""),i.setAttribute("aria-label",e),i.textContent=t,i.addEventListener("mousedown",o=>o.preventDefault()),i}var Wn=[125,69];function Gn(n,e){return e?1:n===0?.7:n===1?.4:.2}function Fe(n,e,t,i,o=!1,s=!1,r=!1){let a=n.querySelector(".magicx-aia-pill-list");if(a||(a=document.createElement("span"),a.className="magicx-aia-pill-list",n.appendChild(a)),s&&e.length===0){a.setAttribute("data-aia-pill-list-loading",""),a.innerHTML="";for(let l=0;l<Wn.length;l++){let c=Wn[l],d=document.createElement("span");d.setAttribute("data-aia-pill-skeleton",""),d.className=`magicx-aia-pill magicx-aia-pill--skeleton${o?" magicx-aia-pill--rounded":""}`,d.style.width=`${c}px`,d.style.opacity=String(Gn(l,!1)),a.appendChild(d)}return}s?a.setAttribute("data-aia-pill-list-loading",""):a.removeAttribute("data-aia-pill-list-loading");for(let l of a.querySelectorAll("[data-aia-pill-skeleton]"))l.remove();H(a,e,{keyOf:l=>`${l.type}-${l.text}`,create:l=>{let c=document.createElement("button");return c.type="button",c.tabIndex=-1,c.setAttribute("data-aia-pill",""),c.setAttribute("contenteditable","false"),c.textContent=l.text,c.addEventListener("mousedown",d=>d.preventDefault()),c},update:(l,c,d)=>{let u=l,f=r&&d===t&&!s,g=["magicx-aia-pill"];o&&g.push("magicx-aia-pill--rounded"),s&&g.push("magicx-aia-pill--skeleton"),u.className=g.join(" "),u.style.width="",u.style.opacity=String(Gn(d,f)),s?(u.setAttribute("data-aia-loading",""),u.disabled=!0,u.onclick=null):(u.removeAttribute("data-aia-loading"),u.disabled=!1,u.onclick=()=>i(d))}})}function Et(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var ao=32;function $n(n,e){if(e.ctrlKey)return null;let t=e.deltaY||0,i=e.deltaX||0;if(!t||Math.abs(i)>=Math.abs(t))return null;let o=n.scrollWidth-n.clientWidth;if(o<=1)return null;let s=n.scrollLeft,r=t;return e.deltaMode===1?r*=32:e.deltaMode===2&&(r*=n.clientWidth),Math.max(0,Math.min(o,s+r))}function wt(n){let e=t=>{let i=$n(n,t);i!==null&&(t.preventDefault(),n.scrollLeft=i)};return n.addEventListener("wheel",e,{passive:!1}),()=>n.removeEventListener("wheel",e)}var lo="Products";function qn(n,e,t,i,o,s="row"){let r=n.querySelector(".magicx-aia-products");if(e.length===0){r?.remove();return}if(!r){r=document.createElement("section"),r.className="magicx-aia-products",r.setAttribute("data-aia-products",""),r.setAttribute("role","group"),r.setAttribute("aria-labelledby",`${t}-products-label`);let l=document.createElement("div");l.className="magicx-aia-products-label",l.id=`${t}-products-label`,l.setAttribute("data-aia-products-label",""),l.textContent=lo;let c=document.createElement("div");c.className="magicx-aia-products-row",c.setAttribute("data-aia-products-row",""),wt(c),r.append(l,c),n.appendChild(r)}r.setAttribute("data-aia-products-layout",s);let a=r.querySelector(".magicx-aia-products-row");a&&H(a,e,{keyOf:l=>co(l),create:l=>uo(l,i,o),update:(l,c,d)=>{l.id=`${t}-product-${d}`,l.dataset.aiaIndex=String(d)}})}function Tt(n,e){let t=n.querySelectorAll("[data-aia-product]");for(let i of t)i.tabIndex=e?0:-1}function co(n){return[n.id,n.title,n.url,n.imageUrl,n.price,n.vendor].map(e=>e??"").join("\0")}function uo(n,e,t){let i=document.createElement("a");i.className="magicx-aia-product",i.setAttribute("data-aia-product",""),i.setAttribute("role","option"),i.setAttribute("aria-selected","false"),n.url&&(i.href=n.url),i.tabIndex=0;let o=document.createElement("span");if(o.className="magicx-aia-product-media",n.imageUrl){let a=document.createElement("img");a.className="magicx-aia-product-image",a.src=n.imageUrl,a.alt="",a.loading="lazy",a.decoding="async",o.appendChild(a)}else o.setAttribute("data-aia-product-placeholder","");i.appendChild(o);let s=document.createElement("span");if(s.className="magicx-aia-product-body",n.vendor){let a=document.createElement("span");a.className="magicx-aia-product-vendor",a.textContent=n.vendor,s.appendChild(a)}let r=document.createElement("span");if(r.className="magicx-aia-product-title",r.textContent=n.title,s.appendChild(r),n.price){let a=document.createElement("span");a.className="magicx-aia-product-price",a.textContent=n.price,s.appendChild(a)}return i.appendChild(s),i.addEventListener("click",a=>{a.metaKey||a.ctrlKey||a.shiftKey||a.altKey||a.button!==0||(a.preventDefault(),e(n))}),i.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),e(n))}),i.addEventListener("focus",()=>t(!0)),i.addEventListener("blur",a=>{a.relatedTarget?.closest("[data-aia-dropdown]")||t(!1)}),i}var po=80,mo=150,fo=280,go=16,Ct="--aia-option-enter-delay";function At(n,e,t,i="below"){let o=Math.max(1,Math.floor(e)),s=Math.floor(Math.max(0,n)/o);if(i!=="above")return s*80;let r=Math.max(1,Math.ceil(Math.max(0,t)/o));return Math.max(0,r-1-s)*80}function Ot(n,e){let t=Math.max(1,Math.floor(e));return(Math.max(1,Math.ceil(Math.max(0,n)/t))-1)*80+280}var Vn="http://www.w3.org/2000/svg",ho=new Set(["svg","g","path","circle","ellipse","line","polyline","polygon","rect"]);function bo(n,e){let t=n.toLowerCase();return t.startsWith("on")||t.includes("href")||t==="style"||t==="xml:base"||t==="id"||t==="name"||/^\s*javascript:/i.test(e)||/url\s*\(\s*['"]?\s*[^#'"\s)]/i.test(e)}var yo=["fill","stroke","stroke-width","stroke-linecap","stroke-linejoin","fill-rule","clip-rule","opacity","fill-opacity","stroke-opacity"],So=/^[a-zA-Z0-9#.,%\s()-]+$/;function xo(n){let e=[];for(let t of yo){let i=n.getAttribute(t);i===null||!So.test(i)||/url\s*\(/i.test(i)||e.push(`${t}: ${i.trim()}`)}e.length>0&&n.setAttribute("style",e.join("; "))}function Un(n){for(let e of Array.from(n.attributes))bo(e.name,e.value)&&n.removeAttribute(e.name);xo(n);for(let e of Array.from(n.childNodes))if(e.nodeType===Node.ELEMENT_NODE){let t=e;!ho.has(t.localName)||t.namespaceURI!==Vn?t.remove():Un(t)}else e.remove()}function de(n){if(typeof DOMParser>"u"||typeof XMLSerializer>"u")return null;let e=new DOMParser().parseFromString(n,"image/svg+xml"),t=e.documentElement;return!t||t.localName!=="svg"||t.namespaceURI!==Vn||e.getElementsByTagName("parsererror").length>0?null:(Un(t),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false"),new XMLSerializer().serializeToString(t))}function It(n){return n.text}function vo(n,e,t){let i=yt(),o=!t&>(e,i)?bt(n):null,s=ht(e,i,o?.rowWidths??null,o?.gridWidth??null);return n.style.gridTemplateColumns=s.template,n.style.setProperty("--aia-grid-max-height",s.maxHeight),n.querySelectorAll("[data-aia-option]").forEach((r,a)=>{r.classList.toggle("magicx-aia-option--scroll-hint",!t&&s.scrollHintIndices.includes(a))}),s.cols}function Kn(n,e,t,i,o,s,r,a="",l="below",c=!0){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));let u=d.dataset.aiaGroup!==a;d.dataset.aiaGroup=a,Po(d,e,t,i,o,s,r,c);let f=vo(d,e.length,r);Eo(d,e.length,f,r,l),u&&(d.scrollTop=0)}function Po(n,e,t,i,o,s,r,a){let l=r?"1":"0",c=n.dataset.aiaGroup??"",d=a?u=>u.icon??u.icon_svg??"":()=>"";H(n,e,{keyOf:u=>`${u.text}\0${d(u)}\0${l}\0${c}`,create:(u,f)=>{let g=wo(u,r,a);return r||(g.dataset.aiaEntering=""),g},update:(u,f,g)=>{let h=g===t&&!r;u.id=`${s}-option-${g}`,u.dataset.aiaIndex=String(g),u.setAttribute("aria-selected",String(h)),u.classList.toggle("magicx-aia-option--highlighted",h),!r&&f.is_tappable?(u.onclick=()=>{u.classList.add("magicx-aia-option--pressed"),i(f),setTimeout(()=>u.classList.remove("magicx-aia-option--pressed"),170)},u.onmouseenter=()=>{let y=Number.parseInt(u.dataset.aiaIndex??"-1",10);y>=0&&o(y)}):(u.onclick=null,u.onmouseenter=null)}})}function Eo(n,e,t,i,o){for(let s of n.querySelectorAll("[data-aia-entering]")){if(!i){let r=Number.parseInt(s.dataset.aiaIndex??"-1",10);r>=0&&s.style.setProperty(Ct,`${At(r,t,e,o)}ms`)}delete s.dataset.aiaEntering}}function wo(n,e,t){let i=document.createElement("div");i.setAttribute("role","option"),i.setAttribute("data-aia-option",""),e&&i.setAttribute("data-aia-loading",""),i.tabIndex=e||!n.is_tappable?-1:0;let o=["magicx-aia-option"];n.is_tappable?o.push("magicx-aia-option--tappable"):o.push("magicx-aia-option--non-tappable"),i.className=o.join(" ");let s=document.createElement("span");s.className="magicx-aia-option-content";let r=t&&n.icon_svg?de(n.icon_svg):null;if(r){let l=document.createElement("span");l.className="magicx-aia-option-icon",l.setAttribute("aria-hidden","true"),l.innerHTML=r,s.appendChild(l),n.icon&&(i.dataset.aiaIcon=n.icon)}let a=document.createElement("span");if(a.className="magicx-aia-option-text",a.textContent=It(n),s.appendChild(a),n.tag){let l=document.createElement("span");l.className="magicx-aia-option-tag",l.textContent=n.tag,s.appendChild(l)}return i.appendChild(s),i}var Qn="magicx-aia-scroll-arrow",Yn="data-aia-scroll-arrow",He="data-aia-visible",To=1e3,jn=160,zn="--aia-scroll-arrow-bottom",Xn="Scroll down for more options",Co="[data-aia-products-label]",Ao=4,Oo=8,Io=240;function Ro(n,e,t,i){let o=n.scrollTop,s=t?.requestAnimationFrame,r=n.ownerDocument?.visibilityState==="hidden";if(!s||r||Zn(n)){n.scrollTop=o+e,i();return}let a=t.performance?.now?.()??Date.now(),l=()=>t.performance?.now?.()??Date.now(),c=()=>{let d=Math.min(1,(l()-a)/Io),u=1-(1-d)*(1-d);n.scrollTop=o+e*u,d<1?s.call(t,c):i()};s.call(t,c)}function Do(n=document){let e="http://www.w3.org/2000/svg",t=n.createElementNS(e,"svg");t.setAttribute("viewBox","0 0 16 16"),t.setAttribute("width","18"),t.setAttribute("height","18"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.75"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let i=n.createElementNS(e,"path");return i.setAttribute("d","M4 6.5 8 10.5l4-4"),t.appendChild(i),t}function Jn(n=document){let e=n.createElement("button");return e.type="button",e.tabIndex=-1,e.className=Qn,e.setAttribute(Yn,""),e.setAttribute("aria-label",Xn),e.setAttribute("aria-hidden","true"),e.appendChild(Do(n)),e}function Lo(n){let e=n.style.gridTemplateColumns.trim();return e?Math.max(1,e.split(/\s+/).length):1}function Zn(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function Rt({dropdown:n,grid:e,button:t}){let i=e.ownerDocument?.defaultView??(typeof window<"u"?window:null),o=!1,s=null,r=null,a=null,l=p=>{p?(t.setAttribute(He,""),t.setAttribute("aria-hidden","false")):(t.removeAttribute(He),t.setAttribute("aria-hidden","true"))},c=p=>{let m=0,b=p;for(;b&&b!==n;)m+=b.offsetTop,b=b.offsetParent instanceof HTMLElement?b.offsetParent:null;return m},d=()=>{let p=n.querySelector(Co),m;if(p){let b=c(p)+p.offsetHeight/2;m=n.clientHeight-b-t.offsetHeight/2}else{let b=c(e),S=i&&Number.parseFloat(i.getComputedStyle(e).paddingBottom)||0;m=n.clientHeight-(b+e.offsetHeight)+(S>0?0:Oo)}t.style.setProperty(zn,`${Math.max(0,Math.round(m))}px`)},u=()=>{if(o||r!==null||a!==null)return;let p=e.querySelector("[data-aia-option][data-aia-loading]")!==null,m=e.scrollHeight-e.clientHeight-e.scrollTop;l(!p&&m>Ao)},f=()=>{if(o)return;d();let p=e.getAttribute("data-aia-group")??"";if(p!==s){s=p,l(!1),r!==null&&clearTimeout(r);let m=e.querySelectorAll("[data-aia-option]").length,b=Zn(e)?0:Ot(m,Lo(e));r=setTimeout(()=>{r=null,u()},b);return}u()},g=()=>{o||r!==null||(l(!1),a!==null&&clearTimeout(a),a=setTimeout(()=>{a=null,u()},jn))};e.addEventListener("scroll",g,{passive:!0});let h=p=>p.preventDefault(),y=()=>{let p=i?(Number.parseFloat(i.getComputedStyle(e).paddingTop)||0)+(Number.parseFloat(i.getComputedStyle(e).paddingBottom)||0):0,m=Math.max(1,e.clientHeight-p);Ro(e,m,i,g)};t.addEventListener("mousedown",h),t.addEventListener("click",y);let v=null;return i&&typeof i.ResizeObserver=="function"&&(v=new i.ResizeObserver(()=>{d(),u()}),v.observe(e)),f(),{update:f,destroy(){o||(o=!0,r!==null&&clearTimeout(r),r=null,a!==null&&clearTimeout(a),a=null,e.removeEventListener("scroll",g),t.removeEventListener("mousedown",h),t.removeEventListener("click",y),v?.disconnect(),t.removeAttribute(He),t.setAttribute("aria-hidden","true"))}}}var Mo=[159,119,164];function We(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}var Be=new WeakMap;function ko(n,e){let t=Be.get(n);if(t||(t={button:Jn(n.ownerDocument),grid:null,controller:null},n.appendChild(t.button),Be.set(n,t)),t.grid!==e&&(t.controller?.destroy(),t.controller=null,t.grid=e,e)){t.controller=Rt({dropdown:n,grid:e,button:t.button});return}t.controller?.update()}function Dt(n){let e=Be.get(n);e&&(e.controller?.destroy(),Be.delete(n))}function Ge(n,e){let{filteredOptions:t,activeIndex:i,isOpen:o,isLoading:s,pills:r,showPills:a,isActivePillSelected:l,onSelect:c,onHighlight:d,onPillClick:u,onSkip:f}=e,g=r.length>0,h=a&&g,y=t.length>0,v=e.products.length>0,p=o&&(y||h||s||v);if(p?n.classList.add("magicx-aia-dropdown--visible"):n.classList.remove("magicx-aia-dropdown--visible"),s?n.setAttribute("data-aia-loading",""):n.removeAttribute("data-aia-loading"),!p){Tt(n,!1);return}v?n.setAttribute("data-aia-has-products",""):n.removeAttribute("data-aia-has-products");let m=n.querySelector(".aia-stack");m||(m=document.createElement("div"),m.className="aia-stack",m.style.setProperty("--aia-stack-space","8px"),n.appendChild(m));let b=e.showSkipButton&&g&&!e.isInputEmpty,S=h||s&&a||b,x=m.querySelector(".magicx-aia-pill-bar");if(S){x||(x=document.createElement("div"),x.className="magicx-aia-pill-bar aia-cluster",x.setAttribute("data-nowrap",""),x.setAttribute("data-aia-pillbar",""),m.insertBefore(x,m.firstChild));let P=x.querySelector(".magicx-aia-pill-scroll");P||(P=document.createElement("span"),P.className="magicx-aia-pill-scroll",P.setAttribute("data-aia-pill-scroll",""),x.insertBefore(P,x.firstChild)),Fe(P,a?r:[],0,u,!0,s&&a,l),No(x,b,s||e.skipDisabled,r[0],f)}else x&&x.remove();let w=e.suggestions[0],T=w?`${w.type} ${w.text}`:"",_=E(e.formatType),N=_&&!s;Kn(m,_?[]:t,i,c,d,e.listboxId,s,T,e.optionsPosition??"below",e.showOptionIcons??!0),ko(n,m.querySelector(".aia-grid")),Bn(m,N?t:[],i,e.listboxId,N?e.dateView:null,{selectedIso:e.selectedDateIso,selectedRange:e.selectedDateRange,rangeStart:e.dateRangeStart},{onSelect:c,onHighlight:d,onPreviousMonth:e.onPreviousMonth,onNextMonth:e.onNextMonth});let O=m.querySelector(".magicx-aia-skeleton-bars");if(s&&(!y||_)){if(!O){O=document.createElement("div"),O.className="magicx-aia-skeleton-bars",O.setAttribute("data-aia-skeleton-bars","");for(let P of Mo){let L=document.createElement("span");L.className="magicx-aia-skeleton-bar",L.style.width=`${P}px`,O.appendChild(L)}m.appendChild(O)}}else O&&O.remove();qn(m,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange,e.productsLayout??"row"),Tt(n,!0);let C=m.querySelector(".magicx-aia-footer")??Ho(),Ue=i>=0&&!!t[i]?.is_tappable;Fo(C,xt(Ue,e.isInputEmpty)),C.isConnected||m.appendChild(C),_o(m,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-datepicker",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"])}function _o(n,e){let t=e.map(i=>n.querySelector(`:scope > ${i}`)).filter(i=>i!==null);for(let i=0;i<t.length;i++)n.children[i]!==t[i]&&n.insertBefore(t[i],n.children[i]??null)}function No(n,e,t,i,o){let s=n.querySelector(".magicx-aia-skip");if(!e){s?.remove();return}s||(s=document.createElement("button"),s.type="button",s.tabIndex=-1,s.className="magicx-aia-skip",s.setAttribute("data-aia-skip",""),s.textContent="skip",s.addEventListener("mousedown",r=>r.preventDefault()),n.appendChild(s)),s.setAttribute("aria-label",i?`Skip ${i.text}`:"Skip"),s.disabled=t,s.onclick=t?null:()=>o()}function Fo(n,{key:e,hint:t}){let i=n.querySelector(".magicx-aia-footer-key"),o=n.querySelector(".magicx-aia-footer-hint");!i||!o||(i.textContent!==e&&(i.textContent=e),o.textContent!==t&&(o.textContent=t))}function Ho(){let n=document.createElement("footer");n.className="magicx-aia-footer",n.setAttribute("data-aia-footer","");let e=document.createElement("div");e.className="aia-cluster magicx-aia-footer-row",e.setAttribute("data-align","center"),e.setAttribute("data-justify","between"),e.setAttribute("data-nowrap","");let t=document.createElement("div");t.className="aia-cluster magicx-aia-footer-hint-group",t.setAttribute("data-align","center"),t.style.setProperty("--aia-cluster-gap","5px");let i=document.createElement("kbd");i.className="magicx-aia-footer-key",i.textContent="tab";let o=document.createElement("span");o.className="magicx-aia-footer-hint",o.textContent="to select",t.append(i,o);let s=document.createElement("a");s.className="aia-cluster magicx-aia-footer-brand-link",s.setAttribute("data-align","center"),s.href=St(),s.target="_blank",s.rel="noopener noreferrer",s.style.setProperty("--aia-cluster-gap","2px");let r=document.createElement("span");r.className="magicx-aia-footer-brand",r.textContent="AI";let a=document.createElement("span");return a.className="magicx-aia-footer-badge",a.textContent="Autocomplete",s.append(r,a),e.append(t,s),n.append(e),n}function ei(n,e){let t=We(e.listboxId);return n.appendChild(t),{dropdown:t}}function Lt(n,e,t){let i=le(e);Ge(n.dropdown,{suggestions:e.editingIdentified?[{type:e.editingIdentified.type,text:B(e.editingIdentified.type),required:!0,options:e.filteredOptions}]: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||e.isSearchingOptions,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,showSkipButton:t.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:t.showOptionIcons??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,productsLayout:t.productsLayout??"row",formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:i.selectedIso,selectedDateRange:i.selectedRange,dateRangeStart:i.rangeStart,optionsPosition:t.optionsPosition??"below",onSelect:t.selectOption,onHighlight:o=>t.store.set({activeDropdownIndex:o}),onPillClick:t.setActivePill,onSkip:t.skipActivePill,onPreviousMonth:t.showPreviousMonth,onNextMonth:t.showNextMonth,onProductSelect:t.selectProduct,onProductFocusChange:o=>t.store.set({isFocused:o})})}var Bo=6,Wo=.3;function ti(n){return n<=0?"0px":`${(-Math.min(Wo,2*Bo/n)).toFixed(3)}px`}function Mt(n){let{input:e,segments:t,newParamId:i,editingParamId:o,placeholderText:s,isFocused:r}=n,a=n.showChipIcons??!0,l=t.length===0;e.dataset.aiaEmpty=l?"true":"false",kn(e,l?s:"");let c=t.map(p=>p.type==="completed"?`${p.type}:${p.value}${a?p.param.icon??p.param.icon_svg??"":""}`:`${p.type}:${p.value}`).join("\0"),d=e.dataset.segKey??"",u=e.dataset.newParamId??"",f=e.dataset.editingParamId??"";if(c===d&&(i??"")===u&&(o??"")===f)return;let g=r?M(e):null;e.dataset.segKey=c,e.dataset.newParamId=i??"",e.dataset.editingParamId=o??"";let h=A(e),y=h.createDocumentFragment(),v=0;for(let p of t)if(v+=p.value.length,p.type==="completed"){let m=h.createElement("strong");m.dataset.seg="completed",m.dataset.paramId=p.param.id;let b=p.param.id===i,S=p.param.id===o,x=["magicx-aia-segment","magicx-aia-segment--completed"];b&&x.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),S&&x.push("magicx-aia-segment--editing"),m.className=x.join(" "),m.style.letterSpacing=ti(p.value.length);let w=a&&p.param.icon_svg?de(p.param.icon_svg):null;if(w){let T=h.createElement("span");T.className="magicx-aia-segment-icon",T.setAttribute("contenteditable","false"),T.setAttribute("aria-hidden","true"),T.innerHTML=w,m.appendChild(T),p.param.icon&&(m.dataset.aiaIcon=p.param.icon)}m.appendChild(h.createTextNode(p.value)),y.appendChild(m)}else if(p.type==="identified"){let m=h.createElement("strong");m.dataset.seg="identified",m.dataset.paramId=p.param.id;let b=["magicx-aia-segment","magicx-aia-segment--completed"];p.param.id===o&&b.push("magicx-aia-segment--editing"),m.className=b.join(" "),m.style.letterSpacing=ti(p.value.length),m.textContent=p.value,y.appendChild(m)}else y.appendChild(h.createTextNode(p.value));e.replaceChildren(y),e.dataset.aiaTextLength=String(v),g!=null?R(e,Math.max(0,Math.min(g,v))):r&&En(e)&&R(e,v)}var Go='<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 ni(){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=Go,n}function $o(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function ii(n,e){let t=e.firstElementChild;if(!t){e.removeAttribute("data-aia-pill-wrapped");return}let i=t.getBoundingClientRect(),o=n.getBoundingClientRect();i.top>=o.bottom-2?e.setAttribute("data-aia-pill-wrapped",""):e.removeAttribute("data-aia-pill-wrapped")}function oi(n,e){let{listboxId:t}=e,i=We(t);n.appendChild(i);let o=document.createElement("div");o.className="magicx-aia-input-wrapper",o.setAttribute("data-aia-input-wrapper",""),n.appendChild(o);let s=document.createElement("div");s.className="magicx-aia-editor",s.setAttribute("data-aia-editor",""),o.appendChild(s);let r=document.createElement("div");r.className="magicx-aia-input",r.setAttribute("data-aia-input",""),r.setAttribute("contenteditable",$o()?"plaintext-only":"true"),r.setAttribute("role","combobox"),r.setAttribute("aria-autocomplete","list"),r.setAttribute("aria-haspopup","listbox"),r.setAttribute("aria-controls",t),r.setAttribute("aria-expanded","false"),r.setAttribute("spellcheck","true"),r.setAttribute("enterkeyhint","send"),s.appendChild(r);let a=document.createElement("span");a.className="magicx-aia-pill-list-container",a.setAttribute("data-aia-pill-list-container",""),s.appendChild(a);let l=null,c=null;e.submitButton===void 0?(l=ni(),o.appendChild(l),c=l):e.submitButton!==null&&(c=e.submitButton,c.hasAttribute("data-aia-submit")||c.setAttribute("data-aia-submit",""),c.setAttribute("data-aia-submit-slot",""),o.appendChild(c));let d=new AbortController,{signal:u}=d,f=!1,g=0,h=()=>{let p=Ae(r),b=p.length>0&&p[0]!==p[0].toUpperCase()?p[0].toUpperCase()+p.slice(1):p;e.handleChange(b)},y=()=>{let p=U(r)?.node??null;if(!p||!r.contains(p))return null;let S=(p.nodeType===Node.ELEMENT_NODE?p:p.parentElement)?.closest("strong[data-param-id]")?.dataset.paramId??null;return S&&Pn(r,S)?null:S};if(o.addEventListener("click",p=>{p.target?.closest("[data-aia-pill]")||r.focus()},{signal:u}),r.addEventListener("input",()=>{f||(g=performance.now(),h(),e.handleCaretAfterInput(M(r)))},{signal:u}),A(r).addEventListener("selectionchange",()=>{let p=U(r);if(!p||!r.contains(p.node))return;let m=p.collapsed?y():null,b=e.store.get(),S=b.editingParam?.id??b.editingIdentified?.id??null;if(m&&m!==S){e.startEditingParam(m);return}performance.now()-g<50||e.handleCaretMove(M(r))},{signal:u}),r.addEventListener("compositionstart",()=>{f=!0},{signal:u}),r.addEventListener("compositionend",()=>{f=!1,h()},{signal:u}),r.addEventListener("beforeinput",p=>{let m=p,b=m.inputType;if(b==="insertParagraph"||b==="insertLineBreak"||b==="insertFromDrop"){p.preventDefault();return}if(b.startsWith("insert")||b.startsWith("delete")){let S=b.startsWith("delete")?"":m.data??"";e.replaceEditingRange(S)&&p.preventDefault()}},{signal:u}),r.addEventListener("paste",p=>{p.preventDefault();let m=(p.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!m)return;let b=A(r),S=Pe(r);if(!S||!r.contains(S.startContainer))return;S.deleteContents();let x=b.createTextNode(m);S.insertNode(x),S.setStartAfter(x),se(r,S.startContainer,S.startOffset),h()},{signal:u}),r.addEventListener("keydown",p=>e.handleKeyDown(p),{signal:u}),r.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:u}),r.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:u}),c&&c.addEventListener("click",p=>{let m=e.store.get();if(!(!!m.text||m.completedParams.length>0)||!e.onSubmit)return;p.stopPropagation(),e.onSubmit(K(m.text,m.completedParams,m.skippedParams,{identifiedParams:m.identifiedParams,isReady:m.isReady,customFields:m.customFields}))&&e.afterSubmit?.()},{signal:u}),e.autoFocus!==!1){r.focus();let p=U(r);(!p||!r.contains(p.node))&&se(r,r,0)}if(typeof ResizeObserver<"u"){let p=new ResizeObserver(()=>ii(r,a));p.observe(r),d.signal.addEventListener("abort",()=>p.disconnect(),{once:!0})}return{input:r,inlinePillContainer:a,dropdown:i,submitButton:l,abort:d}}function kt(n,e,t){let{input:i,inlinePillContainer:o,dropdown:s,submitButton:r}=n,{pillPlacement:a,setActivePill:l,selectOption:c,store:d}=t;i.setAttribute("aria-expanded",String(e.isDropdownOpen));let u=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(u?i.setAttribute("aria-activedescendant",u):i.removeAttribute("aria-activedescendant"),r){let p=!!e.text||e.completedParams.length>0;r.disabled=!p}let f=i.dataset.newParamId??"",g=e.newParamId!==null&&e.newParamId!==f;if(Mt({input:i,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused,showChipIcons:t.showChipIcons??!0}),a==="inline"){let p=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;p||e.actionableSuggestions.length>0?Fe(o,e.actionableSuggestions,0,l,!1,p,e.isActivePillSelected):Et(o)}else Et(o);ii(i,o),g?(i.focus(),R(i,e.caretOffset??e.text.length)):e.isFocused&&Ae(i)!==e.text&&R(i,e.text.length);let h=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:e.editingIdentified?{type:e.editingIdentified.type,text:B(e.editingIdentified.type),required:!0,options:[]}:null,y=h??e.actionableSuggestions[0],v=le(e);Ge(s,{suggestions:y?[{...y,options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation||e.isSearchingOptions,listboxId:t.listboxId,pills:h?[h]:e.actionableSuggestions,showPills:a==="dropdown",showSkipButton:t.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:t.showOptionIcons??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,productsLayout:t.productsLayout??"row",formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:v.selectedIso,selectedDateRange:v.selectedRange,dateRangeStart:v.rangeStart,optionsPosition:t.optionsPosition??"below",onSelect:c,onHighlight:p=>d.set({activeDropdownIndex:p}),onPillClick:l,onSkip:t.skipActivePill,onPreviousMonth:t.showPreviousMonth,onNextMonth:t.showNextMonth,onProductSelect:t.selectProduct,onProductFocusChange:p=>d.set({isFocused:p})})}function ri(n,e){let t=n.actionableSuggestions[0];if(!t)return null;let i=n.filterBase,o=n.text.slice(0,i),s=o.length===0&&n.text.length===0,r=o.length===0&&n.text.length>0&&n.placeholderText.length>0&&n.placeholderText.toLowerCase().startsWith(n.text.toLowerCase());(s||r)&&n.placeholderText&&(o=`${n.placeholderText} `);let a=rn(o,e.text);a>0&&(o=o.slice(0,o.length-a));let l=o.length>0&&o[o.length-1]!==" ",c=`${o}${l?" ":""}${e.text} `,d=(s||r)&&c.length>0?c[0].toUpperCase()+c.slice(1):c,u=d.toLowerCase().lastIndexOf(e.text.toLowerCase()),f=u>=0?d.slice(u,u+e.text.length):e.text,g={id:crypto.randomUUID(),placeholder:"",type:t.type,text:f,kind:e.kind,suggestionType:t.type,suggestionPlaceholder:t.text,options:t.options??[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg},h=n.actionableSuggestions.length-1;return{patch:{text:d,filterBase:d.length,completedParams:[...n.completedParams,g],newParamId:g.id,caretOffset:d.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:!0,inSelectionAnimation:!0,pendingSpan:null},telemetry:{selectedOption:e.text,otherOptions:n.filteredOptions.filter(y=>y.text!==e.text).map(y=>y.text)},consumedSuggestion:t,remainingActionable:h}}function _t(n){let e=n,t=new Set,i=[],o=!1;return{get:()=>e,set:s=>{let r=typeof s=="function"?s(e):s,a=e;if(e={...e,...r},i.push([e,a]),!o){o=!0;try{let l=0;for(let c=i.shift();c;c=i.shift()){if(++l>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[d,u]=c;for(let f of t)f(d,u)}}catch(l){throw i.length=0,l}finally{o=!1}}},subscribe:s=>(t.add(s),()=>{t.delete(s)})}}function si(n,e){let t,i,o=s=>(s!==t&&(t=s,i=e(s)),i);return{get:()=>{let s=n.get();return{...s,...o(s)}},set:s=>{typeof s=="function"?n.set(r=>{let a={...r,...o(r)};return s(a)}):n.set(s)},peek:s=>{let r={...n.get(),...s};return{...r,...e(r)}},subscribe:s=>n.subscribe((r,a)=>{let l={...a,...o(a)},c={...r,...o(r)};s(c,l)})}}var Nt=new WeakSet,ai=new WeakMap;function di(n){return n.nodeType===Node.DOCUMENT_NODE}function qo(n){return di(n)?n:n.ownerDocument}function Vo(n){let e=ai.get(n);if(e)return e;let t=n.defaultView?.CSSStyleSheet;if(typeof t!="function")return null;try{let i=new t;return typeof i.replaceSync!="function"?null:(i.replaceSync(ui),ai.set(n,i),i)}catch{return null}}function li(n,e){if(e.querySelector("style[data-magicx-aia]"))return;let t=n.createElement("style");t.setAttribute("data-magicx-aia",""),t.textContent=ui,e.appendChild(t)}function ci(n){if(typeof document>"u")return;let e=n??document;if(Nt.has(e))return;let t=qo(e);if(di(e)){let s=e.head??e.documentElement;if(!s)return;li(t,s),Nt.add(e);return}let i=Vo(t),o=e.adoptedStyleSheets;i&&Array.isArray(o)?o.includes(i)||(e.adoptedStyleSheets=[...o,i]):li(t,e),Nt.add(e)}var ui=`.aia-stack {
|
|
1
|
+
function Ke(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9]+/).filter(Boolean).map(e=>e.toLowerCase())}function B(n){let e=Ke(n);return e.length>0?e.join(" "):n}var Q=["January","February","March","April","May","June","July","August","September","October","November","December"],ue=["S","M","T","W","T","F","S"],Gt=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],$t="aiaDate",qt="aiaDay",Bt=n=>String(n).padStart(2,"0");function D(n){return`${n.getFullYear()}-${Bt(n.getMonth()+1)}-${Bt(n.getDate())}`}function Qe(n){return new Date(n.getFullYear(),n.getMonth(),n.getDate())}function bi(n){let e=Qe(n).getTime()-Qe(new Date).getTime();return Math.round(e/864e5)}function Vt(n){let e=bi(n);return e>=0&&e<7?Gt[n.getDay()]:Y(n)}function Y(n){return n.getFullYear()===new Date().getFullYear()?`${Q[n.getMonth()]} ${n.getDate()}`:`${Q[n.getMonth()]} ${n.getDate()} ${n.getFullYear()}`}function pe(n){if(!n)return null;let e=Gt.findIndex(a=>a.toLowerCase()===n.trim().toLowerCase());if(e>=0){let a=Qe(new Date),l=(e-a.getDay()+7)%7;return new Date(a.getFullYear(),a.getMonth(),a.getDate()+l)}let t=/^\s*([A-Za-z]+)\s+(\d{1,2})(?:\s+(\d{4}))?\s*$/.exec(n);if(!t)return null;let i=Q.findIndex(a=>a.toLowerCase()===t[1].toLowerCase());if(i<0)return null;let o=Number(t[2]),s=t[3]?Number(t[3]):new Date().getFullYear(),r=new Date(s,i,o);return r.getMonth()!==i||r.getDate()!==o?null:r}function Ye(n){return`${Q[n.month]} ${n.year}`}function je(){let n=new Date;return{year:n.getFullYear(),month:n.getMonth()}}function Ut(n){return{year:n.getFullYear(),month:n.getMonth()}}function ze(n,e){let t=new Date(n.year,n.month+e,1);return{year:t.getFullYear(),month:t.getMonth()}}function Wt(){return{text:"",is_tappable:!1,kind:null}}function Xe(n){let e=new Date(n.year,n.month,1).getDay(),t=new Date(n.year,n.month+1,0).getDate(),i=[];for(let o=0;o<e;o++)i.push(Wt());for(let o=1;o<=t;o++){let s=new Date(n.year,n.month,o);i.push({text:Vt(s),is_tappable:!0,kind:null,metadata:{[$t]:D(s),[qt]:o}})}for(;i.length%ue.length!==0;)i.push(Wt());return i}function Je(n){let e=pe(n);return e?D(e):null}function k(n){let e=n?.metadata?.[$t];return typeof e=="string"?e:null}function Ze(n){let e=n?.metadata?.[qt];return typeof e=="number"?e:null}function yi(n){return n.replace(/(\d+)(?:st|nd|rd|th)\b/g,"$1")}function Kt(n){let e=n.toLowerCase().replace(/\.$/,"");return e.length<3?-1:Q.findIndex(t=>t.toLowerCase().startsWith(e))}function Si(n,e,t){let i=new Date(t.getFullYear(),n,e);if(i.getMonth()!==n||i.getDate()!==e)return null;let o=new Date(t.getFullYear(),t.getMonth(),t.getDate());if(i>=o)return i;let s=new Date(t.getFullYear()+1,n,e);return s.getMonth()===n&&s.getDate()===e?s:null}function Qt(n,e,t){let i=new Date(n,e,t);return i.getMonth()===e&&i.getDate()===t?i:null}function W(n,e={}){if(!n)return null;let t=e.today??new Date,i=yi(n.trim().toLowerCase()).replace(/\s+/g," "),o=/^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(i);if(o){let l=Qt(Number(o[1]),Number(o[2])-1,Number(o[3]));return l?D(l):null}let s=/^([a-z]+)\.? (\d{1,2})(?:,? (\d{4}))?$/.exec(i);if(s){let l=Kt(s[1]);if(l>=0)return me(l,Number(s[2]),s[3],t)}let r=/^(\d{1,2}) (?:of )?([a-z]+)\.?(?:,? (\d{4}))?$/.exec(i);if(r){let l=Kt(r[2]);if(l>=0)return me(l,Number(r[1]),r[3],t)}let a=/^(\d{1,2})[/\-.](\d{1,2})(?:[/\-.](\d{2,4}))?$/.exec(i);if(a){let l=Number(a[1]),c=Number(a[2]);return l>12&&c<=12?me(c-1,l,a[3],t):c>12&&l<=12?me(l-1,c,a[3],t):null}return null}function me(n,e,t,i){if(t){if(t.length!==4)return null;let s=Qt(Number(t),n,e);return s?D(s):null}let o=Si(n,e,i);return o?D(o):null}function et(n,e={}){let t=n.isoDate;return typeof t=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t)?t:W(n.text,e)}var jt=" - ",nt="aiaDateRangeStart",it="aiaDateRangeEnd";function te(n,e){return n<=e?{start:n,end:e}:{start:e,end:n}}var tt=/^\d{4}-\d{2}-\d{2}$/;function Yt(n){if(!tt.test(n))return null;let[e,t,i]=n.split("-").map(Number),o=new Date(e,t-1,i);return o.getMonth()===t-1&&o.getDate()===i?o:null}var xi=/\s+(?:to|through|thru|until|til|till)\s+/g,vi=/[-–—]/g;function Pi(n){let e=[];for(let t of[xi,vi]){t.lastIndex=0;let i=t.exec(n);for(;i!==null;)e.push([n.slice(0,i.index),n.slice(i.index+i[0].length)]),i=t.exec(n)}return e}function j(n,e={}){if(!n)return null;let t=new Set,i=null;for(let[o,s]of Pi(n.trim())){let r=W(o.trim(),e);if(!r)continue;let a=W(s.trim(),e);!a||a<r||(t.add(`${r}|${a}`),i={start:r,end:a})}return t.size===1?i:null}function zt(n){let e=Yt(n.start),t=Yt(n.end);return!e||!t?"":n.start===n.end?Y(e):`${Y(e)}${jt}${Y(t)}`}function Xt(n,e){let t=te(n,e);return{text:zt(t),is_tappable:!0,kind:null,metadata:{[nt]:t.start,[it]:t.end}}}function ne(n,e={}){let t=n?.metadata?.[nt],i=n?.metadata?.[it];return typeof t=="string"&&typeof i=="string"&&tt.test(t)&&tt.test(i)?te(t,i):j(n?.text,e)}function E(n){return n==="date"||n==="date-range"}var Ei=new Set(["date","dates"]),wi=new Set(["range","ranges","span","period","window"]),Jt=3;function Ti(n){let e={single:0,range:0};if(!n)return e;for(let t of n)t.is_tappable&&(j(t.text)!==null?e.range+=1:W(t.text)!==null&&(e.single+=1));return e}function G(n){if(!n)return"options";let e=n.formatType;if(e==="date"||e==="options"||e==="date-range")return e;let t=Ti(n.options);if(t.single+t.range>=Jt&&t.range>t.single)return"date-range";let i=Ke(n.type);return i.some(o=>Ei.has(o))?i.some(o=>wi.has(o))?"date-range":"date":t.single>=Jt?"date":"options"}var fe=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 Ci="https://api.ai-autocomplete.com",ge=`${Ci}/api/suggest`,Zt=new WeakMap;function ie(n){return n?.type==="accessToken"}function Ai(n){if(!(!n||ie(n)))return n}function he(n){let e=Zt.get(n.getAccessToken);return e||(e=new fe(n),Zt.set(n.getAccessToken,e)),e}function be(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function ye(n){let e=Ai(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}function oe(n){return n.map(e=>({type:e.type,value:e.text}))}var en="skipped";function re(n,e){if(e.length===0)return n;let t=new Set(n.map(o=>o.type)),i=e.filter(o=>!t.has(o.type)).map(o=>({placeholder:"",type:o.type,text:en,kind:null}));return i.length>0?[...n,...i]:n}var Oi="0.26.2",tn=!1;function Ii(){return crypto.randomUUID()}function Ri(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.value??n.text},kind:n.kind}}function Di(n,e,t,i,o,s,r,a,l){let c=e.find(u=>u.type==="contact"&&u.metadata?.contact_account_count)?.metadata?.contact_account_count,d=typeof c=="number"?c:void 0;return{data:{raw_query:n,completed_params:re(e.map(u=>Ri(u,t)),a??[]),...s&&s.length>0&&{identified_params:oe(s)},...r&&r.length>0&&{recently_suggested:r},...d!=null&&{contact_account_count:d},...l!==void 0&&{additional_context:l}},meta:{request_id:Ii(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:Oi,session_id:i,source:o}}}async function nn(n,e,t,i,o){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:o})}async function on(n,e,t){let i=t.apiConfig,o=!t.maskCompletedText,s=Di(n,e,o,t.sessionId,t.source,t.identifiedParams,t.recentlySuggested,t.skippedParams,t.additionalContext),r=be(i),a=i?.endpoint??ge,l=JSON.stringify(s);if(ie(i)){let u=he(i),f=await u.getToken(),g=await nn(a,r,f,l,t.signal);if(g.status===401){let h=await u.getToken(!0);g=await nn(a,r,h,l,t.signal)}if(!g.ok)throw new Error(`API error: ${g.status} ${g.statusText}`);return g.json()}let c=ye(i);!c&&!tn&&(tn=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),c&&(r.Authorization=c);let d=await fetch(a,{method:"POST",headers:r,body:l,signal:t.signal});if(!d.ok)throw new Error(`API error: ${d.status} ${d.statusText}`);return d.json()}function I(n,e){let t=n,i={},o=[],s=[],r=0;for(let a of e){let l=(i[a.type]??0)+1;i[a.type]=l;let d=`{{${a.type.toUpperCase().replace(/\s+/g,"_")}_${l}}}`,u=g=>{let h=t.indexOf(a.text,g);for(;h!==-1&&s.some(y=>h<y.end&&h+a.text.length>y.start);)h=t.indexOf(a.text,h+1);return h},f=u(r);if(f===-1&&(f=u(0)),f!==-1){t=t.slice(0,f)+d+t.slice(f+a.text.length);let g=d.length-a.text.length;for(let h of s)h.start>=f+a.text.length&&(h.start+=g,h.end+=g);s.push({start:f,end:f+d.length}),r=f>=r?f+d.length:r+g}o.push({...a,placeholder:d})}return{rawQuery:t,completedParams:o}}function F(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function Se(n,e,t){return e===0&&n.length>0&&t.length>0&&t.toLowerCase().startsWith(n.toLowerCase())}function $(n,e,t){let i=n.slice(e);if(t||e===0||n[e-1]===" ")return i;let o=i.indexOf(" ");return o===-1?"":i.slice(o+1)}function rn(n,e){let t=n.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let i=t.split(" "),o=e.toLowerCase();for(let s=0;s<i.length;s++){let r=i.slice(s).join(" ");if(o.startsWith(r.toLowerCase())){let a=t.length-r.length;return n.length-a}}return 0}function q(n,e){if(!n)return[];let t=e.trimStart();if(!t)return n;let i=t.toLowerCase();return n.filter(o=>!o.is_tappable||o.text.toLowerCase().includes(i))}function z(n,e){if(!n)return null;let t=e.trim();if(!t)return null;let i=t.toLowerCase();return n.find(o=>o.is_tappable&&o.text.toLowerCase()===i)??null}function sn(n,e){return e?n.map(t=>e[t.type]?{...t,options:[]}:t):n}function an(n,e){let t=0,i=e;for(let o of n)t+=o.value.length,o.type!=="text"&&(i=Math.max(i,t));return i}function ln(n,e){let t=0;for(let i of n){let o=t+i.value.length;if(i.type==="text"&&o>e&&i.value.slice(Math.max(e-t,0)).trim().length>0)return!1;t=o}return!0}function dn(n,e){let t=[],i=new Set;for(let o of[...n,...e])o.type==="placeholder"||i.has(o.type)||(i.add(o.type),t.push({type:o.type,text:o.text}));return t}function cn(n,e,t){if(n===e)return t;let i=Math.min(n.length,e.length),o=0;for(;o<i&&n[o]===e[o];)o++;if(o>=t)return t;let s=0;for(;s<i-o&&n[n.length-1-s]===e[e.length-1-s];)s++;return n.length-s<=t?t+(e.length-n.length):null}function ot(n,e){let t=[],i=[],o=0;for(let s of e){let r=n.indexOf(s.text,o);if(r===-1){i.push(s);continue}t.push({start:r,end:r+s.text.length,param:s}),o=r+s.text.length}return{located:t,missing:i}}function un(n,e,t){let i=[],o=[],s=0;for(let r of t){let a=n.indexOf(r.text,s);for(;a!==-1&&e.some(l=>a<l.end&&a+r.text.length>l.start);)a=n.indexOf(r.text,a+1);if(a===-1){o.push(r);continue}i.push({start:a,end:a+r.text.length,param:r}),s=a+r.text.length}return{located:i,missing:o}}function pn(n,e,t=[]){let i=ot(n,e).located,o=un(n,i,t).located,s=[...i.map(c=>({start:c.start,end:c.end,segment:{type:"completed",value:c.param.text,param:c.param}})),...o.map(c=>({start:c.start,end:c.end,segment:{type:"identified",value:c.param.text,param:c.param}}))].sort((c,d)=>c.start-d.start),r=[],a=0;for(let c of s)c.start>a&&r.push({type:"text",value:n.slice(a,c.start)}),r.push(c.segment),a=c.end;let l=n.slice(a);return l&&r.push({type:"text",value:l}),r}function mn(n,e){let{located:t,missing:i}=ot(n,e);return{valid:t.map(o=>o.param),invalid:i}}function xe(n,e,t){let i=ot(n,e).located,{located:o,missing:s}=un(n,i,t);return{valid:o.map(r=>r.param),invalid:s}}function Li(n){if(n instanceof Error)return n;try{return new Error(String(n))}catch{return new Error("Unknown error")}}var Mi=100,ki=300,_i=2,ve=class{constructor(e,t,i,o,s,r,a,l,c={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=o;this.getOnError=s;this.getSessionId=r;this.getSource=a;this.getAdditionalContext=l;this.callbacks=c;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null}start(){this.doFetch("",[]);let e=this.store.get().text,t=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(i=>{(i.text!==e||i.completedParams!==t)&&(e=i.text,t=i.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let i=new AbortController;this.abortController=i;let o=++this.fetchVersion,s=this.store.get().text.length;try{this.callbacks.onRequest?.({query:this.store.get().text,signal:i.signal,isCurrent:()=>o===this.fetchVersion})}catch{}try{this.store.set({isLoading:!0,error:null});let r=this.store.get(),a=r.pendingSpan?dn(r.pendingSpan.snapshot,r.actionableSuggestions):void 0,l=await on(e,t,{sessionId:this.getSessionId(),source:this.getSource(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig(),identifiedParams:r.identifiedParams,recentlySuggested:a,skippedParams:r.skippedParams,additionalContext:this.getAdditionalContext()});if(o!==this.fetchVersion)return;let c=(l.data.input??[]).filter(x=>x.source==="identified").map(x=>({id:crypto.randomUUID(),type:x.type,text:x.text})),d=sn(l.data.suggestions??[],this.getOptionOverrides()),u=l.data.input??[],f=u[u.length-1],g=this.store.get().text,h,y;if(f?.state==="in_progress"){y=!0;let x=g.toLowerCase().lastIndexOf(f.text.toLowerCase());h=x!==-1?x:s}else y=!1,h=s;let p=d.filter(x=>x.type!=="placeholder")[0],m=null;if(p&&!E(G(p))){let x=$(g,h,y),w=z(p.options,x);w&&(m={id:crypto.randomUUID(),placeholder:"",type:p.type,text:w.text,value:w.value,kind:w.kind,suggestionType:p.type,suggestionPlaceholder:p.text,options:p.options??[],metadata:w.metadata,icon:w.icon,icon_svg:w.icon_svg},d=d.filter(T=>T!==p),this.callbacks.onAutoMatch?.({active:p,matched:w,rawQuery:e}))}let b=l.data.custom_fields??null,S=this.callbacks.productsForResponse?.(b);this.store.set(x=>{let w=m?[...x.completedParams,m]:x.completedParams,T=xe(x.text,w,c).valid,_=new Set(r.skippedParams.map(C=>C.id)),N=new Set(x.skippedParams.filter(C=>!_.has(C.id)).map(C=>C.type));return{suggestions:N.size>0?d.filter(C=>C.type==="placeholder"||!N.has(C.type)):d,isLoading:!1,isReady:l.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:h,filterInProgress:y,identifiedParams:T,customFields:b,...S!==void 0?{products:S}:{},...m?{completedParams:w}:{}}}),this.callbacks.onResponse?.()}catch(r){let a=Li(r);o===this.fetchVersion&&(this.store.set({error:a,isLoading:!1}),this.getOnError()?.(a))}finally{if(o===this.fetchVersion&&this.store.get().isLoading)try{this.store.set({isLoading:!1})}catch{}}}attemptNow(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}this.attemptFetch(1,!0)}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}this.debounceTimer=setTimeout(()=>{this.attemptFetch(_i)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},Mi),this.slowDebounceTimer=setTimeout(()=>this.attemptFetch(1),ki)}attemptFetch(e,t=!1){let i=this.store.get();if(!i.text&&i.completedParams.length===0)return this.doFetch("",[]),!0;let o=this.callbacks.consumerTick?.(i,e)??"no";if(o==="asked")return!0;if(o==="owns")return!1;let s=i.suggestions.filter(S=>S.type==="placeholder").map(S=>S.text).join(" "),r=F(i.text,i.filterBase,s),a=$(i.text,r,i.filterInProgress),c=i.suggestions.filter(S=>S.type!=="placeholder")[0],d=E(i.activeFormatType),f=(c&&!d?q(c.options,a):[]).filter(S=>S.is_tappable),g=c&&!d?z(c.options,a)!==null:!1,h=a.trim().length>0;if(f.length>0&&!g&&h||Se(i.text,i.completedParams.length,s))return!1;let{rawQuery:y,completedParams:v}=I(i.text,i.completedParams),p=y.length<i.lastRawQuery.length,m=Math.abs(y.length-i.lastRawQuery.length),b=t&&y!==i.lastRawQuery;return p||m>=e||b?(this.doFetch(y,v),!0):!1}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};function Ni(n){return n.nodeType===Node.DOCUMENT_NODE?!0:n.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in n}function V(n){let e=typeof n.getRootNode=="function"?n.getRootNode():null;return e&&Ni(e)?e:n.ownerDocument??n}function A(n){return n.ownerDocument??n}function Fi(n){return n.nodeType===Node.DOCUMENT_FRAGMENT_NODE}function fn(n){let e=V(n);return!Fi(e)||typeof e.getSelection=="function"?null:e}function gn(n){let e=fn(n);if(!e)return null;let t=A(n).getSelection?.();return!t||typeof t.getComposedRanges!="function"?null:e}function hn(n,e){let t=n,i;try{i=t.getComposedRanges({shadowRoots:[e]})}catch{i=t.getComposedRanges(e)}return i.length>0?i[0]:null}function rt(n){let t=V(n).getSelection?.();return t||(A(n).getSelection?.()??null)}function U(n){let e=rt(n);if(!e||e.rangeCount===0)return null;let t=gn(n);if(t){let i=hn(e,t);return i?{node:i.startContainer,offset:i.startOffset,collapsed:i.startContainer===i.endContainer&&i.startOffset===i.endOffset}:null}return e.anchorNode?{node:e.anchorNode,offset:e.anchorOffset,collapsed:e.isCollapsed}:null}function Pe(n){let e=rt(n);if(!e||e.rangeCount===0)return null;let t=gn(n);if(!t)return e.getRangeAt(0);let i=hn(e,t);if(!i)return null;let o=A(n).createRange();return o.setStart(i.startContainer,i.startOffset),o.setEnd(i.endContainer,i.endOffset),o}function se(n,e,t){let i=rt(n);if(!i)return null;if(fn(n))return i.collapse(e,t),i;let o=A(n).createRange();return o.setStart(e,t),o.collapse(!0),i.removeAllRanges(),i.addRange(o),i}function Ee(n,e){let t=n?V(n):typeof document<"u"?document:null;return t?typeof t.getElementById=="function"?t.getElementById(e):typeof document<"u"?document.getElementById(e):null:null}var we=2,Hi="magicx-aia";function bn(n){return n==="auto"||n==="scroll"||n==="hidden"||n==="overlay"}function Bi(n){let e=A(n),t=e.defaultView;if(!t?.getComputedStyle)return null;let i=n;for(;i&&i!==e.body&&i!==e.documentElement;){let o=i.scrollWidth>i.clientWidth,s=i.scrollHeight>i.clientHeight;if(o||s){let r=t.getComputedStyle(i);if(o&&bn(r.overflowX)||s&&bn(r.overflowY))return i}if(i.classList.contains(Hi))return null;i=i.parentElement}return null}function st(n){let e=Pe(n);if(!e||!e.collapsed||!n.contains(e.startContainer))return;let t=Bi(n);if(!t||typeof e.getBoundingClientRect!="function")return;let i=e.getBoundingClientRect();if(i.height===0)return;let o=t.getBoundingClientRect();if(t.scrollWidth>t.clientWidth){let s=o.left+t.clientLeft,r=s+t.clientWidth;i.right>r?t.scrollLeft+=i.right-r+we:i.left<s&&(t.scrollLeft-=s-i.left+we)}if(t.scrollHeight>t.clientHeight){let s=o.top+t.clientTop,r=s+t.clientHeight;i.bottom>r?t.scrollTop+=i.bottom-r+we:i.top<s&&(t.scrollTop-=s-i.top+we)}}var xn='[contenteditable="false"]',Wi="strong[data-param-id]",X;function Gi(){if(X!==void 0)return X;let n=globalThis.Intl.Segmenter;if(!n)return X=null,null;try{X=new n(void 0,{granularity:"grapheme"})}catch{X=null}return X??null}function Te(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(xn))return!0;t=t.parentNode}return!1}function Ce(n){return A(n).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return Te(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function Ae(n){let e=Ce(n),t="",i=e.nextNode();for(;i;)t+=i.data,i=e.nextNode();return t}function at(n){let e=Ce(n),t=0,i=e.nextNode();for(;i;)t+=i.data.length,i=e.nextNode();return t}function M(n){let e=U(n);if(!e)return null;let t=e.node,i=e.offset;if(!n.contains(t))return null;if(t.nodeType===Node.ELEMENT_NODE){let o=t;if(Te(o,n)&&o!==n)return null;let s=0;for(let r=0;r<i&&r<o.childNodes.length;r++)s+=vn(o.childNodes[r],n);return s+yn(o,n)}return t.nodeType!==Node.TEXT_NODE||Te(t,n)?null:yn(t,n)+i}function vn(n,e){if(n.nodeType===Node.TEXT_NODE)return Te(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(xn))return 0;let i=0;for(let o of Array.from(t.childNodes))i+=vn(o,e);return i}function yn(n,e){let t=Ce(e),i=0,o=t.nextNode();for(;o;){if(o===n||n.nodeType===Node.ELEMENT_NODE&&n.contains(o))return i;i+=o.data.length,o=t.nextNode()}return i}function R(n,e){let t=A(n),i=Math.max(0,Math.min(e,at(n))),o=Ce(n),s=0,r=null,a=0,l=o.nextNode(),c=null;for(;l;){let u=l.data.length;if(i<s+u){r=l,a=i-s;break}if(i===s+u){let f=o.nextNode();f?(r=f,a=0):(r=l,a=u);break}s+=u,c=l,l=o.nextNode()}let d=t.createRange();if(r){let u=r.parentElement?.closest('strong[data-seg="completed"]');u&&u!==n&&n.contains(u)?a===0?d.setStartBefore(u):a===r.data.length?d.setStartAfter(u):d.setStart(r,a):d.setStart(r,a)}else c?d.setStart(c,c.data.length):d.setStart(n,0);d.collapse(!0),se(n,d.startContainer,d.startOffset)&&($i(n,d,i),st(n))}function Sn(n,e){if(!n||!e.contains(n))return null;let i=(n.nodeType===Node.ELEMENT_NODE?n:n.parentElement)?.closest(Wi)??null;return i&&e.contains(i)?i:null}function $i(n,e,t){let i=Sn(U(n)?.node??null,n);if(i&&i!==Sn(e.startContainer,n)){n.dataset.aiaCaretEscapedChip=`${t}:${i.dataset.paramId}`;return}delete n.dataset.aiaCaretEscapedChip}function Pn(n,e){let t=n.dataset.aiaCaretEscapedChip;if(!t)return!1;let i=M(n);return i!==null&&t===`${i}:${e}`}function En(n){return V(n).activeElement===n}function lt(n){let e=M(n);return e==null?!1:e>=at(n)}function dt(n,e){if(e<=0)return 0;let t=Gi();if(!t)return e-1;let i=n.slice(0,e),o=0;for(let{index:s}of t.segment(i))s<e&&(o=s);return o}function K(n,e,t=[],i={}){let{rawQuery:o,completedParams:s}=I(n,e);return{query:n.trim(),raw_query:o,completed_params:re(s,t),identified_params:oe(i.identifiedParams??[]),is_ready:i.isReady??!1,...i.customFields?{custom_fields:i.customFields}:{}}}function ct(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")?lt(n):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function ut(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?M(n):null}var Oe=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:o}=this.ctx,s=e.target instanceof Node?e.target:null,r=this.getEffectiveColumns(s),a=o(),l=this.getTappableIndices(r);if((e.shiftKey||e.metaKey||e.ctrlKey||e.altKey)&&(e.key==="ArrowDown"||e.key==="ArrowUp"||e.key==="ArrowLeft"||e.key==="ArrowRight"))return;let c=this.ctx.getOptionsPosition()==="above";switch(e.key){case"ArrowDown":{let d=ct(e.target,t),u=!!t.editingParam;if(!d&&!u&&t.activeDropdownIndex<0)break;if(t.activeDropdownIndex<0){if(c)break;e.preventDefault();let h=E(t.activeFormatType)?this.dateEntryIndex(t,!1):l[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:h});break}if(l.length===0)return;this.store.set({activeDropdownIndex:h});break}if(e.preventDefault(),l.length===0)return;if(E(t.activeFormatType)){this.stepDateWeek(t,7);break}if(t.filteredOptions.length>0){let h=Math.floor((t.filteredOptions.length-1)/r);if(Math.floor(t.activeDropdownIndex/r)===h){this.store.set({activeDropdownIndex:-1});break}}let f=l.indexOf(t.activeDropdownIndex),g=f<l.length-1?f+1:0;this.store.set({activeDropdownIndex:l[g]});break}case"ArrowUp":{if(t.activeDropdownIndex<0){if(!c)break;let f=ct(e.target,t),g=!!t.editingParam;if(!f&&!g)break;e.preventDefault();let h=E(t.activeFormatType)?this.dateEntryIndex(t,!0):this.firstTappableInBottomRow(r)??l[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:h});break}if(l.length===0)return;this.store.set({activeDropdownIndex:h});break}if(l.length===0)break;if(e.preventDefault(),E(t.activeFormatType)){this.stepDateWeek(t,-7);break}if(t.activeDropdownIndex<r){this.store.set({activeDropdownIndex:-1});break}let d=l.indexOf(t.activeDropdownIndex),u=d>0?d-1:l.length-1;this.store.set({activeDropdownIndex:l[u]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),E(t.activeFormatType)){this.stepDateDay(t,1);break}if(t.activeDropdownIndex%r<r-1){let f=t.activeDropdownIndex+1;f<t.filteredOptions.length&&t.filteredOptions[f]?.is_tappable&&this.store.set({activeDropdownIndex:f})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let u=e.target.closest("[data-aia-input]")??e.target,f=t.editingTail;this.ctx.exitEditMode?.(),R(u,f);break}ct(e.target,t)&&t.actionableSuggestions.length>=1&&(e.preventDefault(),this.ctx.skipActivePill());break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),E(t.activeFormatType)){this.stepDateDay(t,-1);break}if(t.activeDropdownIndex%r>0){let d=t.activeDropdownIndex-1;d>=0&&t.filteredOptions[d]?.is_tappable&&this.store.set({activeDropdownIndex:d});break}if(!t.editingParam&&this.ctx.startEditingParamAtCaret){let d=ut(e.target);d!=null&&this.ctx.startEditingParamAtCaret(d)}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let d=e.target.closest("[data-aia-input]")??e.target,u=t.editingAnchor;this.ctx.exitEditMode?.(),R(d,u);break}if(this.ctx.startEditingParamAtCaret){let d=ut(e.target);d!=null&&this.ctx.startEditingParamAtCaret(d)&&e.preventDefault()}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let d=ut(e.target);if(d==null)break;this.ctx.removeParamAtCaret(d)&&e.preventDefault();break}case"Enter":{e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable?this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i,s):a&&a(K(t.text,t.completedParams,t.skippedParams,{identifiedParams:t.identifiedParams,isReady:t.isReady,customFields:t.customFields}))&&this.ctx.afterSubmit?.();break}case"Tab":{let d=t.filteredOptions.map((g,h)=>g.is_tappable?h:-1).filter(g=>g!==-1);if(d.length===0)break;if(!t.isDropdownOpen){if(t.actionableSuggestions.length===0)break;e.preventDefault();let g=e.shiftKey?d[d.length-1]:d[0];this.store.set({pillTapped:!0,activeDropdownIndex:g});break}e.preventDefault();let u=d.indexOf(t.activeDropdownIndex),f;if(u<0)f=e.shiftKey?d.length-1:0;else{let g=e.shiftKey?-1:1;f=(u+g+d.length)%d.length}this.store.set({activeDropdownIndex:d[f]});break}case"Escape":{if(t.dateRangeStart){this.store.set({pendingRangeStart:null});break}if(t.editingIdentified){this.ctx.exitEditingIdentified?.(),this.store.set({activeDropdownIndex:-1});break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){let d=e.target.closest("[data-aia-input]")??e.target,u=t.editingTail;this.ctx.exitEditMode?.(),R(d,u)}this.store.set({activeDropdownIndex:-1});break}}}firstTappableInBottomRow(e){let t=this.store.get();if(t.filteredOptions.length===0)return null;let o=Math.floor((t.filteredOptions.length-1)/e)*e;for(let s=o;s<t.filteredOptions.length;s++)if(t.filteredOptions[s]?.is_tappable)return s;return null}dateEntryIndex(e,t){let i=D(new Date),o=e.filteredOptions.findIndex(r=>k(r)===i);if(o>=0)return o;let s=e.filteredOptions.map((r,a)=>r.is_tappable?a:-1).filter(r=>r!==-1);return(t?s[s.length-1]:s[0])??0}stepDateDay(e,t){for(let i=e.activeDropdownIndex+t;i>=0&&i<e.filteredOptions.length;i+=t)if(e.filteredOptions[i]?.is_tappable){this.store.set({activeDropdownIndex:i});return}}stepDateWeek(e,t){let i=e.activeDropdownIndex+t;this.store.set({activeDropdownIndex:e.filteredOptions[i]?.is_tappable?i:-1})}getTappableIndices(e){let i=this.store.get().filteredOptions.map((s,r)=>s.is_tappable?r:-1).filter(s=>s!==-1),o=Array.from({length:e},()=>[]);for(let s of i)o[s%e].push(s);return o.flat()}getEffectiveColumns(e){let t=Ee(e,this.ctx.listboxId);if(!t)return this.ctx.columns;let o=Ee(e,`${this.ctx.listboxId}-option-0`)?.parentElement??null;for(;o;){let s=getComputedStyle(o).gridTemplateColumns;if(s&&s!=="none"){let r=s.split(" ").filter(Boolean).length;if(r>0)return r}if(o===t)break;o=o.parentElement}return this.ctx.columns}clickOrSelect(e,t,i,o){let s=Ee(o,`${i}-option-${e}`);s?s.click():this.ctx.selectOption(t[e])}};var Ie=class{constructor(e,t,i={}){this.store=e;this.getOverrides=t;this.callbacks=i;this.unsubscribe=null;this.current=null;this.version=0;this.lastMiss=null;this.hasLoggedError=!1}start(){this.unsubscribe=this.store.subscribe(e=>this.sync(e)),this.sync(this.store.get())}dispose(){this.unsubscribe?.(),this.unsubscribe=null,this.cancel(),this.current=null}reset(){this.cancel(),this.current=null,this.lastMiss=null}refresh(){this.reset(),this.sync(this.store.get())}hasOverride(e){return!!this.getOverrides()?.[e]}owns(e,t){return this.hasOverride(e)&&!this.missCovers(e,t)}tick(e,t){let i=this.resolveTarget(e);if(!i||this.missCovers(i.type,i.query))return"no";let o=this.current;if(o&&o.key===i.key){if(o.query===i.query)return"owns";let s=Math.abs(i.query.length-o.query.length),r=i.query.length<o.query.length;if(t>1&&!r&&s<t)return"owns"}return this.ask(i),"asked"}sync(e){let t=this.resolveTarget(e);if(!t){this.current&&(this.cancel(),this.current=null),e.optionSearch&&this.store.set({optionSearch:null});return}this.current&&this.current.key===t.key||this.ask(t)}resolveTarget(e){if(E(e.activeFormatType)||e.editingIdentified)return null;let t=e.editingParam;if(t&&e.editingAnchor!=null)return this.hasOverride(t.suggestionType)?{mode:"edit",key:t.id,type:t.suggestionType,suggestion:{type:t.suggestionType,text:t.suggestionPlaceholder,required:!0,options:t.options},query:e.optionQuery}:null;let i=e.actionableSuggestions[0];return!i||!this.hasOverride(i.type)?null:{mode:"pill",key:i,type:i.type,suggestion:i,query:e.optionQuery}}missCovers(e,t){return this.lastMiss!=null&&this.lastMiss.type===e&&this.lastMiss.query===t}ask(e){this.cancel();let t=this.getOverrides()?.[e.type],i=++this.version;if(!t||this.missCovers(e.type,e.query)){this.current={key:e.key,type:e.type,query:e.query,abort:null},this.setSearch(e,"done");return}let o=new AbortController;this.current={key:e.key,type:e.type,query:e.query,abort:o};let s;try{s=t(e.query,o.signal,e.suggestion)}catch(r){this.logOnce(r),this.commit(e,[],i);return}if(Array.isArray(s)){this.commit(e,s,i);return}this.setSearch(e,"loading"),this.await(e,s,o.signal,i)}async await(e,t,i,o){let s;try{let r=await t;if(i.aborted||o!==this.version)return;s=Array.isArray(r)?r:[]}catch(r){if(i.aborted||o!==this.version||qi(r))return;this.logOnce(r),s=[]}this.commit(e,s,o)}commit(e,t,i){if(i!==this.version)return;let o=this.resolveTarget(this.store.get());if(!o||o.key!==e.key)return;t.length===0?this.lastMiss={type:e.type,query:e.query}:this.lastMiss?.type===e.type&&(this.lastMiss=null);let s={type:e.type,query:e.query,status:"done"};if(e.mode==="edit")this.store.set(r=>({editingParam:r.editingParam&&r.editingParam.id===e.key?{...r.editingParam,options:t}:r.editingParam,optionSearch:s}));else{let r={...e.suggestion,options:t};this.current&&this.current.key===e.key&&(this.current.key=r),this.store.set(a=>({suggestions:a.suggestions.map(l=>l===e.suggestion?r:l),optionSearch:s}))}t.length===0?this.callbacks.onMiss?.(e.mode,e.query):this.callbacks.onAnswer?.(e.mode,e.query)}setSearch(e,t){let i=this.store.get().optionSearch;i&&i.type===e.type&&i.query===e.query&&i.status===t||this.store.set({optionSearch:{type:e.type,query:e.query,status:t}})}cancel(){this.current?.abort?.abort(),this.version++}logOnce(e){this.hasLoggedError||(this.hasLoggedError=!0,console.warn("[AIAutocomplete] an optionOverrides entry threw or rejected \u2014 treated as no options. Later failures on this instance are not logged.",e))}};function qi(n){return n instanceof Error&&n.name==="AbortError"}var Re=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),i=t.suggestions.filter(c=>c.type!=="placeholder");if(e<0||e>=i.length)return;let o=i[e],s=i.filter((c,d)=>d!==e),r=t.suggestions.filter(c=>c.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:c}=I(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:c,selectedPill:o.text,otherPills:s.map(d=>d.text)})}let a=[...r,o,...s],l=this.store.peek({suggestions:a}).filteredOptions.findIndex(c=>c.is_tappable);this.store.set({suggestions:a,pillTapped:!0,activeDropdownIndex:l})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};var Tn="/products/",wn="https://relative.invalid";function Vi(n){if(!n)return;let e;try{e=new URL(n,`${wn}/`)}catch{return}if(!(e.protocol!=="http:"&&e.protocol!=="https:"))return n.startsWith("/")?e.origin===wn?n:void 0:/^https?:\/\//i.test(n)?n:void 0}function Cn(n){let e=Vi(n.item_url)??(n.handle?`${Tn}${encodeURIComponent(n.handle)}`:void 0);return{id:n.source_id,title:n.title,...e&&{url:e},imageUrl:n.image_url||null,...n.price&&{price:n.price},...n.vendor&&{vendor:n.vendor}}}function pt(n){return(n?.items.matched??[]).map(Cn)}var De=class{constructor(e,t,i=()=>!0){this.store=e;this.getConfig=t;this.isEnabled=i;this.hasLoggedError=!1}forResponse(e){if(!this.isEnabled())return[];if(!this.getConfig())return pt(e)}async run(e,t,i){if(!this.isEnabled())return;let o=this.getConfig();if(!o)return;if(e.trim().length===0){this.clear(i);return}let s=()=>t.aborted||!i()||!this.owns(o);try{let r=await o.fetch(e,t);if(s())return;let a=o.transform(r),l=Array.isArray(a)?a:[],c=o.limit!=null?l.slice(0,o.limit):l;if(s())return;this.commit(c)}catch(r){if(t.aborted||Ui(r)||(this.logOnce(r),s()))return;this.clear(i)}}owns(e){return this.isEnabled()&&this.getConfig()===e}resync(){let e=this.forResponse(this.store.get().customFields);this.commit(e??[])}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 Ui(n){return n instanceof Error&&n.name==="AbortError"}var Le="(max-width: 768px)";var Ki="var(--aia-option-row-height, 37px)",Qi="var(--aia-grid-scroll-top, 0px) + var(--aia-grid-scroll-bottom, 0px)";function An(n,e){return e?mt(1,Math.min(n,5)):mt(1,Math.min(n,4))}function mt(n,e){return{cols:n,rows:e,maxHeight:`calc(${e} * ${Ki} + ${Qi})`}}function gt(n,e){return!e&&n>=5}function ht(n,e,t,i){if(!(!e&&n>=5&&Yi(t,i))){let r=An(n,e);return{...r,template:ft(r.cols),scrollHintIndices:!e&&n>r.rows?[r.rows-1]:[]}}let s=6;return{...mt(2,3),template:ft(2),scrollHintIndices:n>s?[s-2,s-1]:[]}}function Yi(n,e){return!n||n.length===0||e==null||e<=0||n.some(i=>i<=0)?!1:Math.ceil(Math.max(...n))*2<=e}function bt(n){if(typeof document>"u")return null;let e=Array.from(n.querySelectorAll("[data-aia-option]"));if(e.length===0)return null;let t=document.createElement("div");t.style.cssText="position:absolute;visibility:hidden;left:-9999px;top:0;";for(let r of e){let a=r.cloneNode(!0);a.removeAttribute("id"),a.removeAttribute("role"),a.removeAttribute("aria-selected"),a.style.whiteSpace="nowrap",a.style.width="max-content",t.appendChild(a)}n.appendChild(t);let i=Array.from(t.children).map(r=>r.offsetWidth);t.remove();let o=getComputedStyle(n),s=n.clientWidth-(Number.parseFloat(o.paddingLeft)||0)-(Number.parseFloat(o.paddingRight)||0)-(Number.parseFloat(o.columnGap)||0);return{rowWidths:i,gridWidth:s}}function ft(n){return Array.from({length:n},()=>"minmax(0,1fr)").join(" ")}function yt(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(Le).matches}function On(n,e){let t=e.dropdownTrigger??"auto",i=e.closeDropdownOnBlur??!0,r=n.filteredOptionsLength>0||n.activePillHasNoOptions||n.hasProducts;if(n.inEditMode){let a=i?n.isFocused:!0;return r&&a}if(t==="auto"){let a=i?n.isFocused:!0,l=n.text.replace(/\s+$/,"").length,c=n.caretOffset==null||n.caretOffset>=l;return(r||n.isLoading)&&a&&c}return t==="manual"?(r||n.isLoading)&&n.pillTapped:!1}function ae(n){if(n.editingIdentified){let{type:t,anchor:i}=n.editingIdentified;return`identified:${t}@${i}`}return n.editingParam!=null&&n.editingAnchor!=null?`edit:${n.editingParam?.id}`:`pill:${n.actionableSuggestions[0]?.type??""}`}function In(n){if(!n)return je();let[e,t]=n.split("-").map(Number);return{year:e,month:t-1}}function ji(n){let e=pe(n);return e?Ut(e):je()}function Rn(n,e){let t=pn(n.text,n.completedParams,n.identifiedParams),i=n.suggestions.filter(P=>P.type!=="placeholder"),o=i[0],s=n.suggestions.filter(P=>P.type==="placeholder").map(P=>P.text).join(" "),r=F(n.text,Math.min(n.filterBase,n.text.length),s),l=r===0&&Se(n.text,n.completedParams.length,s)?"":$(n.text,r,n.filterInProgress),c=o?.options??[],d=n.editingParam!=null&&n.editingAnchor!=null,u,f,g,h;if(d&&n.editingParam&&n.editingAnchor!=null){let P=n.editingParam.id,L=n.completedParams.some(hi=>hi.id===P),ee=n.caretOffset??n.editingAnchor,Ht=L?"":n.text.slice(n.editingAnchor,ee);f=Ht.trim(),g=n.editingParam.options,h=n.editingParam.suggestionType,u=q(n.editingParam.options,Ht)}else f=l.trim(),g=c,h=o?.type,u=q(c,l);let y=n.optionSearch,v=y!=null&&h!=null&&y.type===h;v&&y.status==="done"&&y.query===f&&(u=g);let p=v&&y.status==="loading",m=e.showNonTappableOptions===!1;m&&(u=u.filter(P=>P.is_tappable));let b=n.editingIdentified,S=d?n.editingParam&&{type:n.editingParam.suggestionType,options:n.editingParam.options}:o,x=b?b.format:G(S),w=d&&E(x)?ne(n.editingParam):null;w&&(x="date-range");let T=null,_=null;if(E(x)){let P=ae({...n,actionableSuggestions:i}),L=n.dateViewMonth;T=L&&L.key===P?{year:L.year,month:L.month}:b?In(b.iso):w?In(w.start):ji(n.editingParam?.text),u=Xe(T);let ee=n.pendingRangeStart;x==="date-range"&&ee&&ee.key===P&&(_=ee.iso)}let N=P=>m?P.is_tappable:!0,O;if(d){let P=n.editingParam?.options??[];O=n.editingParam!=null&&P.filter(N).length===0}else O=o!=null&&c.filter(N).length===0;let C=On({inEditMode:d||b!=null,filteredOptionsLength:u.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading||p,pillTapped:n.pillTapped,activePillHasNoOptions:O,hasProducts:n.products.length>0},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),Ue=C&&n.activeDropdownIndex>=0&&!!u[n.activeDropdownIndex]?.is_tappable;return{segments:t,actionableSuggestions:i,filteredOptions:u,activeFormatType:x,dateView:T,dateRangeStart:_,placeholderText:s,optionQuery:f,isSearchingOptions:p,isDropdownOpen:C,isActivePillSelected:Ue}}function Me(n){return n.mode==="fresh"?zi(n):Xi(n)}function zi(n){let{text:e,completedParams:t,suggestions:i,filterBase:o,filterInProgress:s}=n,a=i.filter(S=>S.type!=="placeholder")[0];if(!a?.options)return null;let l=i.filter(S=>S.type==="placeholder").map(S=>S.text).join(" "),c=F(e,o,l),d=$(e,c,s),u=z(a.options,d);if(!u)return null;let f=u.text.toLowerCase(),g=e.toLowerCase().lastIndexOf(f),h=g>=0?g:Math.max(0,e.length-u.text.length),y=h+u.text.length,v=e.slice(h,y),m=y<e.length&&e[y]===" "?y+1:y,b={id:crypto.randomUUID(),placeholder:"",type:a.type,text:v,value:u.value,kind:u.kind,suggestionType:a.type,suggestionPlaceholder:a.text,options:a.options??[],metadata:u.metadata,icon:u.icon,icon_svg:u.icon_svg};return{patch:{text:e,completedParams:[...t,b],suggestions:i.filter(S=>S!==a),filterBase:m,newParamId:b.id,caretOffset:m,activeDropdownIndex:-1},caretPos:m}}function Xi(n){let{text:e,completedParams:t,editingParam:i,editingAnchor:o,editingTail:s}=n;if(t.some(b=>b.id===i.id))return null;let r=e.slice(o,s),a=z(i.options,r);if(!a)return null;let l=a.text.toLowerCase(),c=r.toLowerCase().lastIndexOf(l),d=o+Math.max(0,c),u=d+a.text.length,f=e.slice(d,u),g=u<e.length&&e[u]===" "?u+1:u,h=e.length,y={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:f,value:a.value,kind:a.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:a.metadata,icon:a.icon,icon_svg:a.icon_svg},v=t.length,p=0;for(let b=0;b<t.length;b++){let S=e.indexOf(t[b].text,p);if(S!==-1){if(S>=g){v=b;break}p=S+t[b].text.length}}let m=[...t];return m.splice(v,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 ke(n,e,t){let i=n.slice(0,e),o=n.slice(t),s=(i===""||i.endsWith(" "))&&o.startsWith(" ");return s&&(o=o.slice(1)),{text:i+o,removed:t-e+(s?1:0)}}var _e=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(r=>r.id===e);if(!i)return;let o=0,s=-1;for(let r of t.completedParams){let a=t.text.indexOf(r.text,o);if(a!==-1){if(r.id===e){s=a;break}o=a+r.text.length}}s<0||this.deps.store.set({editingParam:i,editingAnchor:s,editingTail:s+i.text.length,caretOffset:s+i.text.length,activeDropdownIndex:-1,editingIdentified:null})}exit(){this.deps.store.get().editingParam&&this.deps.store.set({editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1})}replaceRange(e){let t=this.deps.store.get(),i=t.editingParam,o=t.editingAnchor,s=t.editingTail;if(!i||o==null||s==null||!t.completedParams.some(l=>l.id===i.id))return!1;let{text:r}=e===""?ke(t.text,o,s):{text:t.text.slice(0,o)+e+t.text.slice(s)},a=o+e.length;return this.deps.store.set(l=>({text:r,completedParams:l.completedParams.filter(c=>c.id!==i.id),editingTail:a,caretOffset:a,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(a),this.promoteIfExact(),!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.promoteIfExact()}caretMove(e){let t=this.deps.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null&&e!=null&&(e<t.editingAnchor||e>t.editingTail)){this.deps.store.set({caretOffset:e,editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1});return}this.deps.store.set({caretOffset:e})}selectOption(e){let t=this.deps.store.get(),i=t.editingParam,o=t.editingAnchor,s=t.editingTail;if(!i||o==null||s==null)return;this.deps.fireTelemetry("option",{raw_query:I(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:i.options.filter(p=>p.text!==e.text).map(p=>p.text)});let r=t.text.slice(0,o),a=t.text.slice(s),l=o===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,d=a.length===0||a[0]!==" "?`${l} `:l,u=r+d+a,f=u.length,g={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:l,value:e.value,kind:e.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg},h=t.completedParams.findIndex(p=>p.id===i.id),y=t.completedParams.filter(p=>p.id!==i.id),v=h>=0?Math.min(h,y.length):y.length;y.splice(v,0,g),this.deps.store.set({text:u,completedParams:y,newParamId:g.id,filterBase:f,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:f,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.deps.startSelectionAnimationTimer(),this.deps.scheduleSetCursor(f),this.deps.fetchNow()}promoteIfExact(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let t=Me({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 Ji=33,Zi=70,eo=120,to=50,J="data-aia-placeholder-leaving",Z=new WeakMap;function Ne(n){n.timer!==null&&(clearTimeout(n.timer),n.timer=null)}function no(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function Ln(n,e,t){e.shown=t,n.dataset.placeholder=e.target.slice(0,t)}function Mn(n,e){if(e.timer=null,!n.isConnected||e.shown>=e.target.length||(Ln(n,e,e.shown+1),e.shown>=e.target.length))return;let t=e.target[e.shown-1],i=t===" "||t==="-"?70:0;e.timer=setTimeout(()=>Mn(n,e),33+i)}function Dn(n,e){Ln(n,e,0),e.timer=setTimeout(()=>Mn(n,e),33)}function kn(n,e){let t=Z.get(n);if(e===""){t&&(Ne(t),Z.delete(n)),n.removeAttribute(J),delete n.dataset.placeholder;return}if(t?.target===e)return;if(no(n)){t&&Ne(t),n.removeAttribute(J),Z.set(n,{target:e,shown:e.length,timer:null}),n.dataset.placeholder=e;return}let i={target:e,shown:0,timer:null},o=t&&t.shown>0?t:null;if(t&&Ne(t),Z.set(n,i),o){n.setAttribute(J,""),i.timer=setTimeout(()=>{i.timer=null,n.removeAttribute(J),n.isConnected&&Dn(n,i)},170);return}n.removeAttribute(J),Dn(n,i)}function _n(n){let e=Z.get(n);e&&(Ne(e),Z.delete(n))}var Nn="https://ai-autocomplete.com";function St(n=Nn){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 xt(n,e){return n?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}var io={selectedIso:null,selectedRange:null,rangeStart:null};function le(n){if(!E(n.activeFormatType))return io;let e=n.editingIdentified;if(e){let{iso:i,isoEnd:o}=e;return{selectedIso:o?null:i,selectedRange:i&&o?te(i,o):null,rangeStart:n.dateRangeStart}}let t=ne(n.editingParam);return{selectedIso:t?null:Je(n.editingParam?.text),selectedRange:t,rangeStart:n.dateRangeStart}}function vt(n){return n.pendingStart?te(n.pendingStart,n.highlightedIso??n.pendingStart):n.selected}function Pt(n,e){if(n==null)return{selected:!1,inRange:!1};let{selectedIso:t,range:i}=e,o=n===t||i!=null&&(n===i.start||n===i.end),s=i!=null&&n>i.start&&n<i.end;return{selected:o,inRange:s}}var Fn="data-aia-key";function H(n,e,t){let i=new Map;for(let r of Array.from(n.children)){let a=r.getAttribute(Fn);a!=null&&i.set(a,r)}let o=new Set,s=[];for(let r=0;r<e.length;r++){let a=e[r],l=t.keyOf(a,r);o.add(l);let c=i.get(l);c||(c=t.create(a,r),c.setAttribute(Fn,l)),t.update?.(c,a,r),n.children[r]!==c&&n.insertBefore(c,n.children[r]??null),s.push(c)}for(let[r,a]of i)o.has(r)||a.remove();return s}function Bn(n,e,t,i,o,s,r){let a=n.querySelector(".magicx-aia-datepicker");if(!o||e.length===0){a?.remove();return}a||(a=so(),n.appendChild(a));let l=a.querySelector(".magicx-aia-datepicker-month");l&&(l.textContent=Ye(o));let c=a.querySelector("[data-aia-date-prev]"),d=a.querySelector("[data-aia-date-next]");c&&(c.onclick=()=>r.onPreviousMonth()),d&&(d.onclick=()=>r.onNextMonth());let u=a.querySelector(".magicx-aia-datepicker-grid");u&&oo(u,e,t,i,s,r)}function oo(n,e,t,i,o,s){let r=D(new Date),a=vt({pendingStart:o.rangeStart,highlightedIso:k(e[t]),selected:o.selectedRange});H(n,e,{keyOf:(l,c)=>k(l)??`pad-${c}`,create:l=>ro(l),update:(l,c,d)=>{let u=k(c),f=Pt(u,{selectedIso:o.selectedIso,range:a}),g=d===t&&c.is_tappable;l.id=`${i}-option-${d}`,l.dataset.aiaIndex=String(d),l.setAttribute("aria-selected",String(g)),l.classList.toggle("magicx-aia-date-cell--past",u!=null&&u<r),l.classList.toggle("magicx-aia-date-cell--highlighted",g),l.classList.toggle("magicx-aia-date-cell--today",u!=null&&u===r),l.classList.toggle("magicx-aia-date-cell--selected",f.selected),l.classList.toggle("magicx-aia-date-cell--in-range",f.inRange),c.is_tappable?(l.onclick=()=>{l.classList.add("magicx-aia-date-cell--pressed"),s.onSelect(c),setTimeout(()=>l.classList.remove("magicx-aia-date-cell--pressed"),170)},l.onmouseenter=()=>{let h=Number.parseInt(l.dataset.aiaIndex??"-1",10);h>=0&&s.onHighlight(h)}):(l.onclick=null,l.onmouseenter=null)}})}function ro(n){let e=document.createElement("div");e.setAttribute("role","option"),e.setAttribute("data-aia-option",""),e.setAttribute("data-aia-date-cell","");let t=Ze(n);if(t==null)return e.className="magicx-aia-date-cell magicx-aia-date-cell--blank",e.setAttribute("aria-hidden","true"),e.tabIndex=-1,e;e.className="magicx-aia-date-cell magicx-aia-date-cell--day",e.tabIndex=0,e.setAttribute("aria-label",n.text);let i=document.createElement("span");return i.className="magicx-aia-date-cell-number",i.textContent=String(t),e.appendChild(i),e}function so(){let n=document.createElement("div");n.className="magicx-aia-datepicker",n.setAttribute("data-aia-datepicker","");let e=document.createElement("div");e.className="magicx-aia-datepicker-header";let t=document.createElement("span");t.className="magicx-aia-datepicker-month",t.setAttribute("data-aia-date-month",""),t.setAttribute("aria-live","polite"),e.append(Hn("prev","Previous month","\u2039"),t,Hn("next","Next month","\u203A"));let i=document.createElement("div");i.className="magicx-aia-datepicker-weekdays",i.setAttribute("aria-hidden","true");for(let s of ue){let r=document.createElement("span");r.className="magicx-aia-datepicker-weekday",r.textContent=s,i.appendChild(r)}let o=document.createElement("div");return o.className="magicx-aia-datepicker-grid",o.setAttribute("data-aia-date-grid",""),n.append(e,i,o),n}function Hn(n,e,t){let i=document.createElement("button");return i.type="button",i.tabIndex=-1,i.className="magicx-aia-datepicker-nav",i.setAttribute(`data-aia-date-${n}`,""),i.setAttribute("aria-label",e),i.textContent=t,i.addEventListener("mousedown",o=>o.preventDefault()),i}var Wn=[125,69];function Gn(n,e){return e?1:n===0?.7:n===1?.4:.2}function Fe(n,e,t,i,o=!1,s=!1,r=!1){let a=n.querySelector(".magicx-aia-pill-list");if(a||(a=document.createElement("span"),a.className="magicx-aia-pill-list",n.appendChild(a)),s&&e.length===0){a.setAttribute("data-aia-pill-list-loading",""),a.innerHTML="";for(let l=0;l<Wn.length;l++){let c=Wn[l],d=document.createElement("span");d.setAttribute("data-aia-pill-skeleton",""),d.className=`magicx-aia-pill magicx-aia-pill--skeleton${o?" magicx-aia-pill--rounded":""}`,d.style.width=`${c}px`,d.style.opacity=String(Gn(l,!1)),a.appendChild(d)}return}s?a.setAttribute("data-aia-pill-list-loading",""):a.removeAttribute("data-aia-pill-list-loading");for(let l of a.querySelectorAll("[data-aia-pill-skeleton]"))l.remove();H(a,e,{keyOf:l=>`${l.type}-${l.text}`,create:l=>{let c=document.createElement("button");return c.type="button",c.tabIndex=-1,c.setAttribute("data-aia-pill",""),c.setAttribute("contenteditable","false"),c.textContent=l.text,c.addEventListener("mousedown",d=>d.preventDefault()),c},update:(l,c,d)=>{let u=l,f=r&&d===t&&!s,g=["magicx-aia-pill"];o&&g.push("magicx-aia-pill--rounded"),s&&g.push("magicx-aia-pill--skeleton"),u.className=g.join(" "),u.style.width="",u.style.opacity=String(Gn(d,f)),s?(u.setAttribute("data-aia-loading",""),u.disabled=!0,u.onclick=null):(u.removeAttribute("data-aia-loading"),u.disabled=!1,u.onclick=()=>i(d))}})}function Et(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var ao=32;function $n(n,e){if(e.ctrlKey)return null;let t=e.deltaY||0,i=e.deltaX||0;if(!t||Math.abs(i)>=Math.abs(t))return null;let o=n.scrollWidth-n.clientWidth;if(o<=1)return null;let s=n.scrollLeft,r=t;return e.deltaMode===1?r*=32:e.deltaMode===2&&(r*=n.clientWidth),Math.max(0,Math.min(o,s+r))}function wt(n){let e=t=>{let i=$n(n,t);i!==null&&(t.preventDefault(),n.scrollLeft=i)};return n.addEventListener("wheel",e,{passive:!1}),()=>n.removeEventListener("wheel",e)}var lo="Products";function qn(n,e,t,i,o,s="row"){let r=n.querySelector(".magicx-aia-products");if(e.length===0){r?.remove();return}if(!r){r=document.createElement("section"),r.className="magicx-aia-products",r.setAttribute("data-aia-products",""),r.setAttribute("role","group"),r.setAttribute("aria-labelledby",`${t}-products-label`);let l=document.createElement("div");l.className="magicx-aia-products-label",l.id=`${t}-products-label`,l.setAttribute("data-aia-products-label",""),l.textContent=lo;let c=document.createElement("div");c.className="magicx-aia-products-row",c.setAttribute("data-aia-products-row",""),wt(c),r.append(l,c),n.appendChild(r)}r.setAttribute("data-aia-products-layout",s);let a=r.querySelector(".magicx-aia-products-row");a&&H(a,e,{keyOf:l=>co(l),create:l=>uo(l,i,o),update:(l,c,d)=>{l.id=`${t}-product-${d}`,l.dataset.aiaIndex=String(d)}})}function Tt(n,e){let t=n.querySelectorAll("[data-aia-product]");for(let i of t)i.tabIndex=e?0:-1}function co(n){return[n.id,n.title,n.url,n.imageUrl,n.price,n.vendor].map(e=>e??"").join("\0")}function uo(n,e,t){let i=document.createElement("a");i.className="magicx-aia-product",i.setAttribute("data-aia-product",""),i.setAttribute("role","option"),i.setAttribute("aria-selected","false"),n.url&&(i.href=n.url),i.tabIndex=0;let o=document.createElement("span");if(o.className="magicx-aia-product-media",n.imageUrl){let a=document.createElement("img");a.className="magicx-aia-product-image",a.src=n.imageUrl,a.alt="",a.loading="lazy",a.decoding="async",o.appendChild(a)}else o.setAttribute("data-aia-product-placeholder","");i.appendChild(o);let s=document.createElement("span");if(s.className="magicx-aia-product-body",n.vendor){let a=document.createElement("span");a.className="magicx-aia-product-vendor",a.textContent=n.vendor,s.appendChild(a)}let r=document.createElement("span");if(r.className="magicx-aia-product-title",r.textContent=n.title,s.appendChild(r),n.price){let a=document.createElement("span");a.className="magicx-aia-product-price",a.textContent=n.price,s.appendChild(a)}return i.appendChild(s),i.addEventListener("click",a=>{a.metaKey||a.ctrlKey||a.shiftKey||a.altKey||a.button!==0||(a.preventDefault(),e(n))}),i.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),e(n))}),i.addEventListener("focus",()=>t(!0)),i.addEventListener("blur",a=>{a.relatedTarget?.closest("[data-aia-dropdown]")||t(!1)}),i}var po=80,mo=150,fo=280,go=16,Ct="--aia-option-enter-delay";function At(n,e,t,i="below"){let o=Math.max(1,Math.floor(e)),s=Math.floor(Math.max(0,n)/o);if(i!=="above")return s*80;let r=Math.max(1,Math.ceil(Math.max(0,t)/o));return Math.max(0,r-1-s)*80}function Ot(n,e){let t=Math.max(1,Math.floor(e));return(Math.max(1,Math.ceil(Math.max(0,n)/t))-1)*80+280}var Vn="http://www.w3.org/2000/svg",ho=new Set(["svg","g","path","circle","ellipse","line","polyline","polygon","rect"]);function bo(n,e){let t=n.toLowerCase();return t.startsWith("on")||t.includes("href")||t==="style"||t==="xml:base"||t==="id"||t==="name"||/^\s*javascript:/i.test(e)||/url\s*\(\s*['"]?\s*[^#'"\s)]/i.test(e)}var yo=["fill","stroke","stroke-width","stroke-linecap","stroke-linejoin","fill-rule","clip-rule","opacity","fill-opacity","stroke-opacity"],So=/^[a-zA-Z0-9#.,%\s()-]+$/;function xo(n){let e=[];for(let t of yo){let i=n.getAttribute(t);i===null||!So.test(i)||/url\s*\(/i.test(i)||e.push(`${t}: ${i.trim()}`)}e.length>0&&n.setAttribute("style",e.join("; "))}function Un(n){for(let e of Array.from(n.attributes))bo(e.name,e.value)&&n.removeAttribute(e.name);xo(n);for(let e of Array.from(n.childNodes))if(e.nodeType===Node.ELEMENT_NODE){let t=e;!ho.has(t.localName)||t.namespaceURI!==Vn?t.remove():Un(t)}else e.remove()}function de(n){if(typeof DOMParser>"u"||typeof XMLSerializer>"u")return null;let e=new DOMParser().parseFromString(n,"image/svg+xml"),t=e.documentElement;return!t||t.localName!=="svg"||t.namespaceURI!==Vn||e.getElementsByTagName("parsererror").length>0?null:(Un(t),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false"),new XMLSerializer().serializeToString(t))}function It(n){return n.text}function vo(n,e,t){let i=yt(),o=!t&>(e,i)?bt(n):null,s=ht(e,i,o?.rowWidths??null,o?.gridWidth??null);return n.style.gridTemplateColumns=s.template,n.style.setProperty("--aia-grid-max-height",s.maxHeight),n.querySelectorAll("[data-aia-option]").forEach((r,a)=>{r.classList.toggle("magicx-aia-option--scroll-hint",!t&&s.scrollHintIndices.includes(a))}),s.cols}function Kn(n,e,t,i,o,s,r,a="",l="below",c=!0){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));let u=d.dataset.aiaGroup!==a;d.dataset.aiaGroup=a,Po(d,e,t,i,o,s,r,c);let f=vo(d,e.length,r);Eo(d,e.length,f,r,l),u&&(d.scrollTop=0)}function Po(n,e,t,i,o,s,r,a){let l=r?"1":"0",c=n.dataset.aiaGroup??"",d=a?u=>u.icon??u.icon_svg??"":()=>"";H(n,e,{keyOf:u=>`${u.text}\0${d(u)}\0${l}\0${c}`,create:(u,f)=>{let g=wo(u,r,a);return r||(g.dataset.aiaEntering=""),g},update:(u,f,g)=>{let h=g===t&&!r;u.id=`${s}-option-${g}`,u.dataset.aiaIndex=String(g),u.setAttribute("aria-selected",String(h)),u.classList.toggle("magicx-aia-option--highlighted",h),!r&&f.is_tappable?(u.onclick=()=>{u.classList.add("magicx-aia-option--pressed"),i(f),setTimeout(()=>u.classList.remove("magicx-aia-option--pressed"),170)},u.onmouseenter=()=>{let y=Number.parseInt(u.dataset.aiaIndex??"-1",10);y>=0&&o(y)}):(u.onclick=null,u.onmouseenter=null)}})}function Eo(n,e,t,i,o){for(let s of n.querySelectorAll("[data-aia-entering]")){if(!i){let r=Number.parseInt(s.dataset.aiaIndex??"-1",10);r>=0&&s.style.setProperty(Ct,`${At(r,t,e,o)}ms`)}delete s.dataset.aiaEntering}}function wo(n,e,t){let i=document.createElement("div");i.setAttribute("role","option"),i.setAttribute("data-aia-option",""),e&&i.setAttribute("data-aia-loading",""),i.tabIndex=e||!n.is_tappable?-1:0;let o=["magicx-aia-option"];n.is_tappable?o.push("magicx-aia-option--tappable"):o.push("magicx-aia-option--non-tappable"),i.className=o.join(" ");let s=document.createElement("span");s.className="magicx-aia-option-content";let r=t&&n.icon_svg?de(n.icon_svg):null;if(r){let l=document.createElement("span");l.className="magicx-aia-option-icon",l.setAttribute("aria-hidden","true"),l.innerHTML=r,s.appendChild(l),n.icon&&(i.dataset.aiaIcon=n.icon)}let a=document.createElement("span");if(a.className="magicx-aia-option-text",a.textContent=It(n),s.appendChild(a),n.tag){let l=document.createElement("span");l.className="magicx-aia-option-tag",l.textContent=n.tag,s.appendChild(l)}return i.appendChild(s),i}var Qn="magicx-aia-scroll-arrow",Yn="data-aia-scroll-arrow",He="data-aia-visible",To=1e3,jn=160,zn="--aia-scroll-arrow-bottom",Xn="Scroll down for more options",Co="[data-aia-products-label]",Ao=4,Oo=8,Io=240;function Ro(n,e,t,i){let o=n.scrollTop,s=t?.requestAnimationFrame,r=n.ownerDocument?.visibilityState==="hidden";if(!s||r||Zn(n)){n.scrollTop=o+e,i();return}let a=t.performance?.now?.()??Date.now(),l=()=>t.performance?.now?.()??Date.now(),c=()=>{let d=Math.min(1,(l()-a)/Io),u=1-(1-d)*(1-d);n.scrollTop=o+e*u,d<1?s.call(t,c):i()};s.call(t,c)}function Do(n=document){let e="http://www.w3.org/2000/svg",t=n.createElementNS(e,"svg");t.setAttribute("viewBox","0 0 16 16"),t.setAttribute("width","18"),t.setAttribute("height","18"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.75"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let i=n.createElementNS(e,"path");return i.setAttribute("d","M4 6.5 8 10.5l4-4"),t.appendChild(i),t}function Jn(n=document){let e=n.createElement("button");return e.type="button",e.tabIndex=-1,e.className=Qn,e.setAttribute(Yn,""),e.setAttribute("aria-label",Xn),e.setAttribute("aria-hidden","true"),e.appendChild(Do(n)),e}function Lo(n){let e=n.style.gridTemplateColumns.trim();return e?Math.max(1,e.split(/\s+/).length):1}function Zn(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function Rt({dropdown:n,grid:e,button:t}){let i=e.ownerDocument?.defaultView??(typeof window<"u"?window:null),o=!1,s=null,r=null,a=null,l=p=>{p?(t.setAttribute(He,""),t.setAttribute("aria-hidden","false")):(t.removeAttribute(He),t.setAttribute("aria-hidden","true"))},c=p=>{let m=0,b=p;for(;b&&b!==n;)m+=b.offsetTop,b=b.offsetParent instanceof HTMLElement?b.offsetParent:null;return m},d=()=>{let p=n.querySelector(Co),m;if(p){let b=c(p)+p.offsetHeight/2;m=n.clientHeight-b-t.offsetHeight/2}else{let b=c(e),S=i&&Number.parseFloat(i.getComputedStyle(e).paddingBottom)||0;m=n.clientHeight-(b+e.offsetHeight)+(S>0?0:Oo)}t.style.setProperty(zn,`${Math.max(0,Math.round(m))}px`)},u=()=>{if(o||r!==null||a!==null)return;let p=e.querySelector("[data-aia-option][data-aia-loading]")!==null,m=e.scrollHeight-e.clientHeight-e.scrollTop;l(!p&&m>Ao)},f=()=>{if(o)return;d();let p=e.getAttribute("data-aia-group")??"";if(p!==s){s=p,l(!1),r!==null&&clearTimeout(r);let m=e.querySelectorAll("[data-aia-option]").length,b=Zn(e)?0:Ot(m,Lo(e));r=setTimeout(()=>{r=null,u()},b);return}u()},g=()=>{o||r!==null||(l(!1),a!==null&&clearTimeout(a),a=setTimeout(()=>{a=null,u()},jn))};e.addEventListener("scroll",g,{passive:!0});let h=p=>p.preventDefault(),y=()=>{let p=i?(Number.parseFloat(i.getComputedStyle(e).paddingTop)||0)+(Number.parseFloat(i.getComputedStyle(e).paddingBottom)||0):0,m=Math.max(1,e.clientHeight-p);Ro(e,m,i,g)};t.addEventListener("mousedown",h),t.addEventListener("click",y);let v=null;return i&&typeof i.ResizeObserver=="function"&&(v=new i.ResizeObserver(()=>{d(),u()}),v.observe(e)),f(),{update:f,destroy(){o||(o=!0,r!==null&&clearTimeout(r),r=null,a!==null&&clearTimeout(a),a=null,e.removeEventListener("scroll",g),t.removeEventListener("mousedown",h),t.removeEventListener("click",y),v?.disconnect(),t.removeAttribute(He),t.setAttribute("aria-hidden","true"))}}}var Mo=[159,119,164];function We(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}var Be=new WeakMap;function ko(n,e){let t=Be.get(n);if(t||(t={button:Jn(n.ownerDocument),grid:null,controller:null},n.appendChild(t.button),Be.set(n,t)),t.grid!==e&&(t.controller?.destroy(),t.controller=null,t.grid=e,e)){t.controller=Rt({dropdown:n,grid:e,button:t.button});return}t.controller?.update()}function Dt(n){let e=Be.get(n);e&&(e.controller?.destroy(),Be.delete(n))}function Ge(n,e){let{filteredOptions:t,activeIndex:i,isOpen:o,isLoading:s,pills:r,showPills:a,isActivePillSelected:l,onSelect:c,onHighlight:d,onPillClick:u,onSkip:f}=e,g=r.length>0,h=a&&g,y=t.length>0,v=e.products.length>0,p=o&&(y||h||s||v);if(p?n.classList.add("magicx-aia-dropdown--visible"):n.classList.remove("magicx-aia-dropdown--visible"),s?n.setAttribute("data-aia-loading",""):n.removeAttribute("data-aia-loading"),!p){Tt(n,!1);return}v?n.setAttribute("data-aia-has-products",""):n.removeAttribute("data-aia-has-products");let m=n.querySelector(".aia-stack");m||(m=document.createElement("div"),m.className="aia-stack",m.style.setProperty("--aia-stack-space","8px"),n.appendChild(m));let b=e.showSkipButton&&g&&!e.isInputEmpty,S=h||s&&a||b,x=m.querySelector(".magicx-aia-pill-bar");if(S){x||(x=document.createElement("div"),x.className="magicx-aia-pill-bar aia-cluster",x.setAttribute("data-nowrap",""),x.setAttribute("data-aia-pillbar",""),m.insertBefore(x,m.firstChild));let P=x.querySelector(".magicx-aia-pill-scroll");P||(P=document.createElement("span"),P.className="magicx-aia-pill-scroll",P.setAttribute("data-aia-pill-scroll",""),x.insertBefore(P,x.firstChild)),Fe(P,a?r:[],0,u,!0,s&&a,l),No(x,b,s||e.skipDisabled,r[0],f)}else x&&x.remove();let w=e.suggestions[0],T=w?`${w.type} ${w.text}`:"",_=E(e.formatType),N=_&&!s;Kn(m,_?[]:t,i,c,d,e.listboxId,s,T,e.optionsPosition??"below",e.showOptionIcons??!0),ko(n,m.querySelector(".aia-grid")),Bn(m,N?t:[],i,e.listboxId,N?e.dateView:null,{selectedIso:e.selectedDateIso,selectedRange:e.selectedDateRange,rangeStart:e.dateRangeStart},{onSelect:c,onHighlight:d,onPreviousMonth:e.onPreviousMonth,onNextMonth:e.onNextMonth});let O=m.querySelector(".magicx-aia-skeleton-bars");if(s&&(!y||_)){if(!O){O=document.createElement("div"),O.className="magicx-aia-skeleton-bars",O.setAttribute("data-aia-skeleton-bars","");for(let P of Mo){let L=document.createElement("span");L.className="magicx-aia-skeleton-bar",L.style.width=`${P}px`,O.appendChild(L)}m.appendChild(O)}}else O&&O.remove();qn(m,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange,e.productsLayout??"row"),Tt(n,!0);let C=m.querySelector(".magicx-aia-footer")??Ho(),Ue=i>=0&&!!t[i]?.is_tappable;Fo(C,xt(Ue,e.isInputEmpty)),C.isConnected||m.appendChild(C),_o(m,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-datepicker",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"])}function _o(n,e){let t=e.map(i=>n.querySelector(`:scope > ${i}`)).filter(i=>i!==null);for(let i=0;i<t.length;i++)n.children[i]!==t[i]&&n.insertBefore(t[i],n.children[i]??null)}function No(n,e,t,i,o){let s=n.querySelector(".magicx-aia-skip");if(!e){s?.remove();return}s||(s=document.createElement("button"),s.type="button",s.tabIndex=-1,s.className="magicx-aia-skip",s.setAttribute("data-aia-skip",""),s.textContent="skip",s.addEventListener("mousedown",r=>r.preventDefault()),n.appendChild(s)),s.setAttribute("aria-label",i?`Skip ${i.text}`:"Skip"),s.disabled=t,s.onclick=t?null:()=>o()}function Fo(n,{key:e,hint:t}){let i=n.querySelector(".magicx-aia-footer-key"),o=n.querySelector(".magicx-aia-footer-hint");!i||!o||(i.textContent!==e&&(i.textContent=e),o.textContent!==t&&(o.textContent=t))}function Ho(){let n=document.createElement("footer");n.className="magicx-aia-footer",n.setAttribute("data-aia-footer","");let e=document.createElement("div");e.className="aia-cluster magicx-aia-footer-row",e.setAttribute("data-align","center"),e.setAttribute("data-justify","between"),e.setAttribute("data-nowrap","");let t=document.createElement("div");t.className="aia-cluster magicx-aia-footer-hint-group",t.setAttribute("data-align","center"),t.style.setProperty("--aia-cluster-gap","5px");let i=document.createElement("kbd");i.className="magicx-aia-footer-key",i.textContent="tab";let o=document.createElement("span");o.className="magicx-aia-footer-hint",o.textContent="to select",t.append(i,o);let s=document.createElement("a");s.className="aia-cluster magicx-aia-footer-brand-link",s.setAttribute("data-align","center"),s.href=St(),s.target="_blank",s.rel="noopener noreferrer",s.style.setProperty("--aia-cluster-gap","2px");let r=document.createElement("span");r.className="magicx-aia-footer-brand",r.textContent="AI";let a=document.createElement("span");return a.className="magicx-aia-footer-badge",a.textContent="Autocomplete",s.append(r,a),e.append(t,s),n.append(e),n}function ei(n,e){let t=We(e.listboxId);return n.appendChild(t),{dropdown:t}}function Lt(n,e,t){let i=le(e);Ge(n.dropdown,{suggestions:e.editingIdentified?[{type:e.editingIdentified.type,text:B(e.editingIdentified.type),required:!0,options:e.filteredOptions}]: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||e.isSearchingOptions,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,showSkipButton:t.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:t.showOptionIcons??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,productsLayout:t.productsLayout??"row",formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:i.selectedIso,selectedDateRange:i.selectedRange,dateRangeStart:i.rangeStart,optionsPosition:t.optionsPosition??"below",onSelect:t.selectOption,onHighlight:o=>t.store.set({activeDropdownIndex:o}),onPillClick:t.setActivePill,onSkip:t.skipActivePill,onPreviousMonth:t.showPreviousMonth,onNextMonth:t.showNextMonth,onProductSelect:t.selectProduct,onProductFocusChange:o=>t.store.set({isFocused:o})})}var Bo=6,Wo=.3;function ti(n){return n<=0?"0px":`${(-Math.min(Wo,2*Bo/n)).toFixed(3)}px`}function Mt(n){let{input:e,segments:t,newParamId:i,editingParamId:o,placeholderText:s,isFocused:r}=n,a=n.showChipIcons??!0,l=t.length===0;e.dataset.aiaEmpty=l?"true":"false",kn(e,l?s:"");let c=t.map(p=>p.type==="completed"?`${p.type}:${p.value}${a?p.param.icon??p.param.icon_svg??"":""}`:`${p.type}:${p.value}`).join("\0"),d=e.dataset.segKey??"",u=e.dataset.newParamId??"",f=e.dataset.editingParamId??"";if(c===d&&(i??"")===u&&(o??"")===f)return;let g=r?M(e):null;e.dataset.segKey=c,e.dataset.newParamId=i??"",e.dataset.editingParamId=o??"";let h=A(e),y=h.createDocumentFragment(),v=0;for(let p of t)if(v+=p.value.length,p.type==="completed"){let m=h.createElement("strong");m.dataset.seg="completed",m.dataset.paramId=p.param.id;let b=p.param.id===i,S=p.param.id===o,x=["magicx-aia-segment","magicx-aia-segment--completed"];b&&x.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),S&&x.push("magicx-aia-segment--editing"),m.className=x.join(" "),m.style.letterSpacing=ti(p.value.length);let w=a&&p.param.icon_svg?de(p.param.icon_svg):null;if(w){let T=h.createElement("span");T.className="magicx-aia-segment-icon",T.setAttribute("contenteditable","false"),T.setAttribute("aria-hidden","true"),T.innerHTML=w,m.appendChild(T),p.param.icon&&(m.dataset.aiaIcon=p.param.icon)}m.appendChild(h.createTextNode(p.value)),y.appendChild(m)}else if(p.type==="identified"){let m=h.createElement("strong");m.dataset.seg="identified",m.dataset.paramId=p.param.id;let b=["magicx-aia-segment","magicx-aia-segment--completed"];p.param.id===o&&b.push("magicx-aia-segment--editing"),m.className=b.join(" "),m.style.letterSpacing=ti(p.value.length),m.textContent=p.value,y.appendChild(m)}else y.appendChild(h.createTextNode(p.value));e.replaceChildren(y),e.dataset.aiaTextLength=String(v),g!=null?R(e,Math.max(0,Math.min(g,v))):r&&En(e)&&R(e,v)}var Go='<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 ni(){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=Go,n}function $o(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function ii(n,e){let t=e.firstElementChild;if(!t){e.removeAttribute("data-aia-pill-wrapped");return}let i=t.getBoundingClientRect(),o=n.getBoundingClientRect();i.top>=o.bottom-2?e.setAttribute("data-aia-pill-wrapped",""):e.removeAttribute("data-aia-pill-wrapped")}function oi(n,e){let{listboxId:t}=e,i=We(t);n.appendChild(i);let o=document.createElement("div");o.className="magicx-aia-input-wrapper",o.setAttribute("data-aia-input-wrapper",""),n.appendChild(o);let s=document.createElement("div");s.className="magicx-aia-editor",s.setAttribute("data-aia-editor",""),o.appendChild(s);let r=document.createElement("div");r.className="magicx-aia-input",r.setAttribute("data-aia-input",""),r.setAttribute("contenteditable",$o()?"plaintext-only":"true"),r.setAttribute("role","combobox"),r.setAttribute("aria-autocomplete","list"),r.setAttribute("aria-haspopup","listbox"),r.setAttribute("aria-controls",t),r.setAttribute("aria-expanded","false"),r.setAttribute("spellcheck","true"),r.setAttribute("enterkeyhint","send"),s.appendChild(r);let a=document.createElement("span");a.className="magicx-aia-pill-list-container",a.setAttribute("data-aia-pill-list-container",""),s.appendChild(a);let l=null,c=null;e.submitButton===void 0?(l=ni(),o.appendChild(l),c=l):e.submitButton!==null&&(c=e.submitButton,c.hasAttribute("data-aia-submit")||c.setAttribute("data-aia-submit",""),c.setAttribute("data-aia-submit-slot",""),o.appendChild(c));let d=new AbortController,{signal:u}=d,f=!1,g=0,h=()=>{let p=Ae(r),b=p.length>0&&p[0]!==p[0].toUpperCase()?p[0].toUpperCase()+p.slice(1):p;e.handleChange(b)},y=()=>{let p=U(r)?.node??null;if(!p||!r.contains(p))return null;let S=(p.nodeType===Node.ELEMENT_NODE?p:p.parentElement)?.closest("strong[data-param-id]")?.dataset.paramId??null;return S&&Pn(r,S)?null:S};if(o.addEventListener("click",p=>{p.target?.closest("[data-aia-pill]")||r.focus()},{signal:u}),r.addEventListener("input",()=>{f||(g=performance.now(),h(),e.handleCaretAfterInput(M(r)))},{signal:u}),A(r).addEventListener("selectionchange",()=>{let p=U(r);if(!p||!r.contains(p.node))return;let m=p.collapsed?y():null,b=e.store.get(),S=b.editingParam?.id??b.editingIdentified?.id??null;if(m&&m!==S){e.startEditingParam(m);return}performance.now()-g<50||e.handleCaretMove(M(r))},{signal:u}),r.addEventListener("compositionstart",()=>{f=!0},{signal:u}),r.addEventListener("compositionend",()=>{f=!1,h()},{signal:u}),r.addEventListener("beforeinput",p=>{let m=p,b=m.inputType;if(b==="insertParagraph"||b==="insertLineBreak"||b==="insertFromDrop"){p.preventDefault();return}if(b.startsWith("insert")||b.startsWith("delete")){let S=b.startsWith("delete")?"":m.data??"";e.replaceEditingRange(S)&&p.preventDefault()}},{signal:u}),r.addEventListener("paste",p=>{p.preventDefault();let m=(p.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!m)return;let b=A(r),S=Pe(r);if(!S||!r.contains(S.startContainer))return;S.deleteContents();let x=b.createTextNode(m);S.insertNode(x),S.setStartAfter(x),se(r,S.startContainer,S.startOffset),h()},{signal:u}),r.addEventListener("keydown",p=>e.handleKeyDown(p),{signal:u}),r.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:u}),r.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:u}),c&&c.addEventListener("click",p=>{let m=e.store.get();if(!(!!m.text||m.completedParams.length>0)||!e.onSubmit)return;p.stopPropagation(),e.onSubmit(K(m.text,m.completedParams,m.skippedParams,{identifiedParams:m.identifiedParams,isReady:m.isReady,customFields:m.customFields}))&&e.afterSubmit?.()},{signal:u}),e.autoFocus!==!1){r.focus();let p=U(r);(!p||!r.contains(p.node))&&se(r,r,0)}if(typeof ResizeObserver<"u"){let p=new ResizeObserver(()=>ii(r,a));p.observe(r),d.signal.addEventListener("abort",()=>p.disconnect(),{once:!0})}return{input:r,inlinePillContainer:a,dropdown:i,submitButton:l,abort:d}}function kt(n,e,t){let{input:i,inlinePillContainer:o,dropdown:s,submitButton:r}=n,{pillPlacement:a,setActivePill:l,selectOption:c,store:d}=t;i.setAttribute("aria-expanded",String(e.isDropdownOpen));let u=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(u?i.setAttribute("aria-activedescendant",u):i.removeAttribute("aria-activedescendant"),r){let p=!!e.text||e.completedParams.length>0;r.disabled=!p}let f=i.dataset.newParamId??"",g=e.newParamId!==null&&e.newParamId!==f;if(Mt({input:i,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused,showChipIcons:t.showChipIcons??!0}),a==="inline"){let p=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;p||e.actionableSuggestions.length>0?Fe(o,e.actionableSuggestions,0,l,!1,p,e.isActivePillSelected):Et(o)}else Et(o);ii(i,o),g?(i.focus(),R(i,e.caretOffset??e.text.length)):e.isFocused&&Ae(i)!==e.text&&R(i,e.text.length);let h=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:e.editingIdentified?{type:e.editingIdentified.type,text:B(e.editingIdentified.type),required:!0,options:[]}:null,y=h??e.actionableSuggestions[0],v=le(e);Ge(s,{suggestions:y?[{...y,options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation||e.isSearchingOptions,listboxId:t.listboxId,pills:h?[h]:e.actionableSuggestions,showPills:a==="dropdown",showSkipButton:t.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:t.showOptionIcons??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,productsLayout:t.productsLayout??"row",formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:v.selectedIso,selectedDateRange:v.selectedRange,dateRangeStart:v.rangeStart,optionsPosition:t.optionsPosition??"below",onSelect:c,onHighlight:p=>d.set({activeDropdownIndex:p}),onPillClick:l,onSkip:t.skipActivePill,onPreviousMonth:t.showPreviousMonth,onNextMonth:t.showNextMonth,onProductSelect:t.selectProduct,onProductFocusChange:p=>d.set({isFocused:p})})}function ri(n,e){let t=n.actionableSuggestions[0];if(!t)return null;let i=n.filterBase,o=n.text.slice(0,i),s=o.length===0&&n.text.length===0,r=o.length===0&&n.text.length>0&&n.placeholderText.length>0&&n.placeholderText.toLowerCase().startsWith(n.text.toLowerCase());(s||r)&&n.placeholderText&&(o=`${n.placeholderText} `);let a=rn(o,e.text);a>0&&(o=o.slice(0,o.length-a));let l=o.length>0&&o[o.length-1]!==" ",c=`${o}${l?" ":""}${e.text} `,d=(s||r)&&c.length>0?c[0].toUpperCase()+c.slice(1):c,u=d.toLowerCase().lastIndexOf(e.text.toLowerCase()),f=u>=0?d.slice(u,u+e.text.length):e.text,g={id:crypto.randomUUID(),placeholder:"",type:t.type,text:f,value:e.value,kind:e.kind,suggestionType:t.type,suggestionPlaceholder:t.text,options:t.options??[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg},h=n.actionableSuggestions.length-1;return{patch:{text:d,filterBase:d.length,completedParams:[...n.completedParams,g],newParamId:g.id,caretOffset:d.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:!0,inSelectionAnimation:!0,pendingSpan:null},telemetry:{selectedOption:e.text,otherOptions:n.filteredOptions.filter(y=>y.text!==e.text).map(y=>y.text)},consumedSuggestion:t,remainingActionable:h}}function _t(n){let e=n,t=new Set,i=[],o=!1;return{get:()=>e,set:s=>{let r=typeof s=="function"?s(e):s,a=e;if(e={...e,...r},i.push([e,a]),!o){o=!0;try{let l=0;for(let c=i.shift();c;c=i.shift()){if(++l>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[d,u]=c;for(let f of t)f(d,u)}}catch(l){throw i.length=0,l}finally{o=!1}}},subscribe:s=>(t.add(s),()=>{t.delete(s)})}}function si(n,e){let t,i,o=s=>(s!==t&&(t=s,i=e(s)),i);return{get:()=>{let s=n.get();return{...s,...o(s)}},set:s=>{typeof s=="function"?n.set(r=>{let a={...r,...o(r)};return s(a)}):n.set(s)},peek:s=>{let r={...n.get(),...s};return{...r,...e(r)}},subscribe:s=>n.subscribe((r,a)=>{let l={...a,...o(a)},c={...r,...o(r)};s(c,l)})}}var Nt=new WeakSet,ai=new WeakMap;function di(n){return n.nodeType===Node.DOCUMENT_NODE}function qo(n){return di(n)?n:n.ownerDocument}function Vo(n){let e=ai.get(n);if(e)return e;let t=n.defaultView?.CSSStyleSheet;if(typeof t!="function")return null;try{let i=new t;return typeof i.replaceSync!="function"?null:(i.replaceSync(ui),ai.set(n,i),i)}catch{return null}}function li(n,e){if(e.querySelector("style[data-magicx-aia]"))return;let t=n.createElement("style");t.setAttribute("data-magicx-aia",""),t.textContent=ui,e.appendChild(t)}function ci(n){if(typeof document>"u")return;let e=n??document;if(Nt.has(e))return;let t=qo(e);if(di(e)){let s=e.head??e.documentElement;if(!s)return;li(t,s),Nt.add(e);return}let i=Vo(t),o=e.adoptedStyleSheets;i&&Array.isArray(o)?o.includes(i)||(e.adoptedStyleSheets=[...o,i]):li(t,e),Nt.add(e)}var ui=`.aia-stack {
|
|
2
2
|
display: flex;
|
|
3
3
|
flex-direction: column;
|
|
4
4
|
gap: var(--aia-stack-space, 0.5rem);
|
|
@@ -1925,5 +1925,5 @@ function Ke(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9
|
|
|
1925
1925
|
background: var(--aia-surface, #ffffff);
|
|
1926
1926
|
}
|
|
1927
1927
|
}
|
|
1928
|
-
`;var $e=class{constructor(){this.reported=new Set}run(e,t){try{return t()}catch(i){this.report(e,i,e);return}}runListener(e,t,i=e){try{return t(),!0}catch(o){return this.report(e,o,i),!1}}report(e,t,i){this.reported.has(i)||(this.reported.add(i),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 qe=class{constructor(e){this.boundary=e;this.listeners={};this.keys=new WeakMap;this.registrationCount=0}on(e,t){let i=`${String(e)}#${++this.registrationCount}`,o=(...r)=>t(...r);this.keys.set(o,i);let s=this.listeners[e];return s||(s=new Set,this.listeners[e]=s),s.add(o),()=>{this.listeners[e]?.delete(o)}}emit(e,...t){let i=this.listeners[e];if(!i)return!0;let o=!0;for(let s of i)this.boundary.runListener(String(e),()=>s(...t),this.keys.get(s)??String(e))||(o=!1);return o}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var Ve=class{constructor(){this.timers=new Map}schedule(e,t,i){this.clear(e);let o=setTimeout(()=>{this.timers.delete(e),t()},i);this.timers.set(e,o)}clear(e){let t=this.timers.get(e);t!==void 0&&(clearTimeout(t),this.timers.delete(e))}clearAll(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};var ce=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 Uo(n){return(n??ge).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function Ko(n){return ie(n)?`Bearer ${await he(n).getToken()}`:ye(n)}async function pi(n){try{let e=Uo(n.apiConfig?.endpoint),t=be(n.apiConfig),i=await Ko(n.apiConfig);i&&(t.Authorization=i);let o=JSON.stringify({source:n.source,session_id:n.sessionId,type:n.type,at:new Date().toISOString(),query_data:n.queryData});await fetch(e,{method:"POST",headers:t,body:o})}catch{}}var Qo="newParam",mi="suggestionRemoval",Yo="selectionAnimation",jo=650,zo=0;function Xo(){return`:ac-${++zo}:`}var fi=170;function gi(){return{text:"",completedParams:[],identifiedParams:[],skippedParams:[],pendingSpan:null,suggestions:[],products:[],customFields:null,optionSearch:null,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,dateViewMonth:null,pendingRangeStart:null,editingIdentified:null}}var Ft=class{constructor(e,t={}){this.inputStore=_t(gi());this._listboxId=Xo();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new Ve;this.boundary=new $e;this.subscriberCount=0;this.emitter=new qe(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=si(this.inputStore,i=>Rn(i,this.opts)),t.onSubmit&&this.emitter.on("submit",t.onSubmit),t.onResult&&this.emitter.on("result",t.onResult),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 Re(this.store,{onPillSelected:({rawQuery:i,selectedPill:o,otherPills:s})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:o,other_pills:s})}}),this.reEdit=new _e({store:this.store,scheduleSetCursor:i=>this.scheduleSetCursor(i),fireTelemetry:(i,o)=>this.fireTelemetry(i,o),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer(),fetchNow:()=>this.fetchNow()}),this.productsController=new De(this.store,()=>this.opts.products,()=>this.opts.showProducts!==!1),this.optionSource=new Ie(this.store,()=>this.opts.optionOverrides,{onAnswer:i=>{i==="edit"?this.reEdit.promoteIfExact():this.maybePromoteExactMatch(this.store.get().text)},onMiss:(i,o)=>{i==="pill"&&o.length>0&&this.fetchController.attemptNow()}}),this.fetchController=new ve(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.emitter.hasListeners("error")?this.emitError:void 0,()=>this.sessionId,()=>this.resolveSource(),()=>this.opts.additionalContext,{onRequest:({query:i,signal:o,isCurrent:s})=>{this.productsController.run(i,o,s).catch(()=>{})},onAutoMatch:({active:i,matched:o,rawQuery:s})=>{this.fireTelemetry("option",{raw_query:s,selected_option:o.text,other_options:(i.options??[]).filter(r=>r.text!==o.text).map(r=>r.text)})},onResponse:()=>{this.emitter.hasListeners("result")&&this.emitter.emit("result",this.buildResult())},productsForResponse:i=>this.productsController.forResponse(i),consumerTick:(i,o)=>this.optionSource.tick(i,o)}),this.keyboardController=new Oe(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),startEditingParamAtCaret:i=>this.startEditingParamAtCaret(i),exitEditMode:()=>this.exitEditMode(),exitEditingIdentified:()=>this.exitEditingIdentified(),skipActivePill:()=>this.skipActivePill()}),this.unsubscribers.push(this.store.subscribe((i,o)=>{i.text!==o.text&&this.emitter.emit("change",i.text),i.completedParams!==o.completedParams&&this.emitter.emit("paramsChange",i.completedParams),i.isFocused!==o.isFocused&&(i.isFocused?this.emitter.emit("focus"):this.emitter.emit("blur")),this.emitter.emit("stateChange",i)})),this.unsubscribers.push(this.store.subscribe(()=>this.maybeExitReEditOnNoMatch())),this.unsubscribers.push(this.store.subscribe((i,o)=>{if(i.text===o.text&&i.completedParams===o.completedParams||i.identifiedParams.length===0)return;let{valid:s,invalid:r}=xe(i.text,i.completedParams,i.identifiedParams);r.length>0&&this.store.set({identifiedParams:s})})),this.unsubscribers.push(this.store.subscribe((i,o)=>{if(i.identifiedParams===o.identifiedParams)return;let s=i.editingIdentified;if(!s||i.identifiedParams.some(l=>l.id===s.id))return;let r=0,a;for(let l of i.segments){if(l.type==="identified"&&r===s.anchor&&l.value===s.text){a=l.param;break}r+=l.value.length}if(a){this.store.set({editingIdentified:{...s,id:a.id}});return}this.store.set({editingIdentified:null,activeDropdownIndex:-1})})),this.unsubscribers.push(this.store.subscribe(i=>{let o=i.pendingRangeStart;!o||o.key===ae(i)||this.store.set({pendingRangeStart:null})})),this.unsubscribers.push(this.store.subscribe((i,o)=>{let s=i.pendingSpan;if(!s||i.text===o.text&&i.completedParams===o.completedParams&&i.identifiedParams===o.identifiedParams)return;let r=s.anchor;if(i.text!==o.text){let l=cn(o.text,i.text,r);if(l===null){this.store.set({pendingSpan:null});return}r=l}i.text.slice(r).trim().length===0||ln(i.segments,r)?this.store.set({pendingSpan:null}):r!==s.anchor&&this.store.set({pendingSpan:{anchor:r,snapshot:s.snapshot}})})),this.renderMode!=="headless"&&(ci(this.opts.styleRoot??V(this.container)),this.setupContainer()),this.renderMode==="full"?this.buildAndRenderFull():this.renderMode==="dropdown"&&this.buildAndRenderDropdown(),this.optionSource.start(),this.fetchController.start()}focus(){this.domRefs?.input.focus()}blur(){this.domRefs?.input.blur()}reset(){let e=this.store.get().isFocused;this.optionSource.reset(),this.store.set({...gi(),isFocused:e,skipNextFetch:!0}),this.sessionId=crypto.randomUUID(),this.fetchController.doFetch("",[])}destroy(){this.fetchController.dispose(),this.optionSource.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&&(_n(this.domRefs.input),Dt(this.domRefs.dropdown)),this.dropdownRefs&&Dt(this.dropdownRefs.dropdown),this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}setValue(e){let t=this.store.get();if(t.editingIdentified&&e!==t.text){this.store.set({text:e,editingIdentified:null,activeDropdownIndex:-1});return}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 i of this.store.get().segments){let o=t;if(t+=i.value.length,i.type!=="text"&&e>o&&e<=t)return{kind:i.type,param:i.param,start:o,end:t}}return null}withoutChip(e,t){return t.kind==="completed"?{completedParams:e.completedParams.filter(i=>i.id!==t.param.id)}:{identifiedParams:e.identifiedParams.filter(i=>i.id!==t.param.id)}}removeParamAtCaret(e){let t=this.findChipSpanAt(e);if(!t)return!1;let{text:i}=this.store.get(),{start:o,end:s}=t;if(e===s){let{text:l,removed:c}=ke(i,o,s);return this.store.set(d=>({text:l,filterBase:Math.min(d.filterBase>o?Math.max(o,d.filterBase-c):d.filterBase,l.length),...this.withoutChip(d,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(o),!0}let r=dt(i,e),a=i.slice(0,r)+i.slice(e);return this.store.set(l=>({text:a,filterBase:Math.min(l.filterBase,a.length),...this.withoutChip(l,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(r),!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(),R(t.input,e);else{let i=this.opts.setCursor;i&&this.boundary.runListener("setCursor",()=>i(e))}})}clearNewParamId(){this.store.set({newParamId:null})}startEditingIdentified(e){let t=this.store.get();if(t.editingIdentified?.id===e)return!0;let i=t.identifiedParams.find(d=>d.id===e);if(!i)return!1;let o=G(i);if(!E(o))return!1;let s=j(i.text),r=o==="date-range"||s?"date-range":"date",a=0,l=-1;for(let d of t.segments){if(d.type!=="text"&&d.param.id===e){l=a;break}a+=d.value.length}if(l<0)return!1;let c=l+i.text.length;return this.store.set({editingIdentified:{id:e,type:i.type,anchor:l,tail:c,text:i.text,iso:s?s.start:et(i),isoEnd:s?s.end:null,format:r},editingParam:null,editingAnchor:null,editingTail:null,caretOffset:c,activeDropdownIndex:-1,pillTapped:!0}),!0}exitEditingIdentified(){this.store.get().editingIdentified&&this.store.set({editingIdentified:null,activeDropdownIndex:-1})}startEditingParam(e){this.reEdit.start(e),this.store.get().editingParam?.id!==e&&this.startEditingIdentified(e)}replaceEditingRange(e){return this.reEdit.replaceRange(e)}exitEditMode(){this.reEdit.exit()}handleCaretAfterInput(e){this.reEdit.caretAfterInput(e)}handleCaretMove(e){let t=this.store.get().editingIdentified;t&&e!=null&&(e<t.anchor||e>t.tail)&&this.store.set({editingIdentified:null,activeDropdownIndex:-1}),this.reEdit.caretMove(e)}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}selectProduct(e){this.emitter.emit("productSelect",e)}handleTextChange(e){this.store.get().editingIdentified&&this.store.set({editingIdentified:null,activeDropdownIndex:-1}),this.handleChange(e)}showPreviousMonth(){this.pageDateView(-1)}showNextMonth(){this.pageDateView(1)}pageDateView(e){let t=this.store.get();if(!E(t.activeFormatType)||!t.dateView)return;let i=ze(t.dateView,e);this.store.set({dateViewMonth:{...i,key:ae(t)},activeDropdownIndex:-1})}skipActivePill(){let e=this.store.get();if(e.editingParam||e.inSelectionAnimation)return;let t=e.suggestions.filter(a=>a.type==="placeholder"),i=e.suggestions.filter(a=>a.type!=="placeholder");if(i.length===0)return;let o=i[0],s=i.slice(1),r=e.skippedParams.some(a=>a.type===o.type);this.store.set({suggestions:[...t,...s],pillTapped:s.length>0,activeDropdownIndex:-1,...r?{}:{skippedParams:[...e.skippedParams,{id:crypto.randomUUID(),type:o.type,suggestionPlaceholder:o.text}]}}),s.length===0&&this.fetchNow()}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(i=>{this.boundary.runListener("subscribe",()=>e(i),t)})}getState(){return this.store.get()}getResult(){return this.buildResult()}buildResult(){let e=this.store.get();return K(e.text,e.completedParams,e.skippedParams,{identifiedParams:e.identifiedParams,isReady:e.isReady,customFields:e.customFields})}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,i=this.opts.showProducts,o=this.opts.optionOverrides;Object.assign(this.opts,e),"optionOverrides"in e&&e.optionOverrides!==o&&this.optionSource.refresh(),("products"in e&&e.products!==t||"showProducts"in e&&e.showProducts!==i)&&this.productsController.resync(),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||e.showSkipButton!==void 0||e.showOptionIcons!==void 0||e.productsLayout!==void 0||e.showChipIcons!==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.activeFormatType==="date-range"){let o=k(e);if(o){let s=t.dateRangeStart;if(!s){this.store.set({pendingRangeStart:{iso:o,key:ae(t)}});return}this.store.set({pendingRangeStart:null}),this.selectOption(Xt(s,o));return}}if(t.editingIdentified){this.commitIdentifiedDate(e);return}if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null){this.reEdit.selectOption(e);return}let i=ri(t,e);if(i){if(this.fireTelemetry("option",{raw_query:I(t.text,t.completedParams).rawQuery,selected_option:i.telemetry.selectedOption,other_options:E(t.activeFormatType)?[]:i.telemetry.otherOptions}),this.store.set(i.patch),this.startSelectionAnimationTimer(),this.timers.clear(mi),i.remainingActionable>0){let o=i.consumedSuggestion;this.timers.schedule(mi,()=>{this.store.get().suggestions.includes(o)&&this.store.set(s=>({suggestions:s.suggestions.filter(r=>r!==o)}))},fi)}this.fetchNow()}}startSelectionAnimationTimer(){this.timers.schedule(Yo,()=>this.store.set({inSelectionAnimation:!1}),fi)}resolveSource(){return this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk")}fireTelemetry(e,t){let i=this.resolveSource();pi({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 ce(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 showSkipButton(){return e.opts.showSkipButton??!0},get showOptionIcons(){return e.opts.showOptionIcons??!0},get productsLayout(){return e.opts.productsLayout??"row"},get showChipIcons(){return e.opts.showChipIcons??!0},get optionsPosition(){return e.opts.optionsPosition??"below"},get onSubmit(){return e.emitter.hasListeners("submit")?e.emitSubmit:void 0},afterSubmit:()=>e.reset(),submitButton:this.opts.submitButton,autoFocus:this.opts.autoFocus??!0,selectOption:o=>this.selectOption(o),setActivePill:o=>this.pillsController.setActivePill(o),skipActivePill:()=>this.skipActivePill(),selectProduct:o=>this.selectProduct(o),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth(),handleKeyDown:o=>this.keyboardController.handleKeyDown(o),handleChange:o=>this.handleChange(o),startEditingParam:o=>this.startEditingParam(o),handleCaretAfterInput:o=>this.handleCaretAfterInput(o),handleCaretMove:o=>this.handleCaretMove(o),replaceEditingRange:o=>this.replaceEditingRange(o)};this.domRefs=oi(this.container,t);let i=()=>{this.domRefs&&kt(this.domRefs,this.store.get(),t)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),kt(this.domRefs,this.store.get(),t),this.subscribeNewParamTimer()}buildAndRenderDropdown(){let e=this,t={store:this.store,listboxId:this.listboxId,get showSkipButton(){return e.opts.showSkipButton??!0},get showOptionIcons(){return e.opts.showOptionIcons??!0},get productsLayout(){return e.opts.productsLayout??"row"},get optionsPosition(){return e.opts.optionsPosition??"below"},selectOption:o=>this.selectOption(o),setActivePill:o=>this.pillsController.setActivePill(o),skipActivePill:()=>this.skipActivePill(),selectProduct:o=>this.selectProduct(o),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth()};this.dropdownRefs=ei(this.container,t);let i=()=>{this.dropdownRefs&&Lt(this.dropdownRefs,this.store.get(),t)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),Lt(this.dropdownRefs,this.store.get(),t),this.subscribeNewParamTimer()}subscribeViewportBreakpoint(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;let t=window.matchMedia(Le),i=()=>e();t.addEventListener("change",i),this.unsubscribers.push(()=>t.removeEventListener("change",i))}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(Qo,()=>this.store.set({newParamId:null}),jo)}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:o}=mn(e,t.completedParams);o.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=F(e.text,Math.min(e.filterBase,e.text.length),e.placeholderText),i=an(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(s=>s.id===e.editingParam?.id)||this.optionSource.owns(e.editingParam.suggestionType,e.optionQuery))return;let t=e.caretOffset??e.editingAnchor,i=e.text.slice(e.editingAnchor,t);q(e.editingParam.options,i).some(s=>s.is_tappable)||(this.reEdit.exit(),this.fetchNow())}fetchNow(){let e=this.store.get(),{rawQuery:t,completedParams:i}=I(e.text,e.completedParams);this.fetchController.doFetch(t,i)}commitIdentifiedDate(e){let t=this.store.get(),i=t.editingIdentified;if(!i)return;if(t.text.slice(i.anchor,i.tail)!==i.text){this.store.set({editingIdentified:null,activeDropdownIndex:-1});return}let o=t.text.slice(0,i.anchor),s=t.text.slice(i.tail),r=i.anchor===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,l=s.length===0||s[0]!==" "?`${r} `:r,c=o+l+s,d=c.length,u={id:crypto.randomUUID(),placeholder:"",type:i.type,text:r,kind:e.kind,suggestionType:i.type,suggestionPlaceholder:B(i.type),options:[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg};this.fireTelemetry("option",{raw_query:I(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:[]}),this.store.set({text:c,completedParams:[...t.completedParams,u],identifiedParams:t.identifiedParams.filter(f=>f.id!==i.id),newParamId:u.id,filterBase:d,caretOffset:d,editingIdentified:null,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.startSelectionAnimationTimer(),this.scheduleSetCursor(d),this.fetchNow()}maybePromoteExactMatch(e){let t=this.store.get();if(E(t.activeFormatType))return;let i=Me({mode:"fresh",text:e,completedParams:t.completedParams,suggestions:t.suggestions,filterBase:t.filterBase,filterInProgress:t.filterInProgress});i&&this.store.set(i.patch)}};export{Ft as AIAutocomplete,Nn as ATTRIBUTION_URL,it as DATE_RANGE_META_END,nt as DATE_RANGE_META_START,ce as ModeController,Le as OPTIONS_GRID_MOBILE_QUERY,Ct as OPTION_ENTER_DELAY_VAR,mo as OPTION_ENTER_FADE_MS,fo as OPTION_ENTER_RISE_MS,go as OPTION_ENTER_RISE_PX,po as OPTION_ENTER_STAGGER_MS,eo as PLACEHOLDER_FADE_OUT_MS,J as PLACEHOLDER_LEAVING_ATTR,to as PLACEHOLDER_SWAP_GAP_MS,Ji as PLACEHOLDER_TYPE_MS,Zi as PLACEHOLDER_WORD_PAUSE_MS,Tn as PRODUCT_PATH_PREFIX,ao as PRODUCT_ROW_PX_PER_LINE,jt as RANGE_SEPARATOR,Yn as SCROLL_ARROW_ATTR,zn as SCROLL_ARROW_BOTTOM_VAR,Qn as SCROLL_ARROW_CLASS,To as SCROLL_ARROW_FADE_MS,Xn as SCROLL_ARROW_LABEL,jn as SCROLL_ARROW_SCROLL_IDLE_MS,He as SCROLL_ARROW_VISIBLE_ATTR,en as SKIPPED_PARAM_TEXT,ue as WEEKDAY_LABELS,ze as addMonths,wt as attachProductRowWheel,Rt as attachScrollArrow,St as buildAttributionUrl,Xe as buildDateOptions,I as buildQuery,K as buildSubmitResult,Ze as cellDay,k as cellIso,An as computeOptionsGridLayout,_t as createStore,lt as cursorIsAtEnd,Pt as dateCellMarks,le as dateSelectionFor,Ae as extractPlainText,Y as formatAbsoluteDate,Vt as formatDate,zt as formatDateRange,M as getCursorOffset,xt as getFooterHint,B as identifiedParamLabel,E as isCalendarFormat,yt as isOptionsGridMobileViewport,D as isoDate,bt as measureOptionsGrid,Ye as monthLabel,gt as needsOptionsGridMeasurement,At as optionEnterDelayMs,It as optionLabel,Ot as optionsEntranceDurationMs,ft as optionsGridTemplateColumns,pe as parseDate,W as parseLooseDate,j as parseLooseDateRange,at as plainTextLength,ht as planOptionsGrid,dt as previousGraphemeBoundary,Cn as productFromMatchedItem,$n as productRowWheelTarget,pt as productsFromCustomFields,Mt as renderEditableContent,G as resolveFormatType,et as resolveIdentifiedDate,de as sanitizeOptionIconSvg,st as scrollCaretIntoView,Je as selectedIsoFromText,ne as selectedRangeFor,R as setCursorOffset,oe as toWireIdentifiedParams,vt as visibleDateRange,re as withSkippedParams};
|
|
1928
|
+
`;var $e=class{constructor(){this.reported=new Set}run(e,t){try{return t()}catch(i){this.report(e,i,e);return}}runListener(e,t,i=e){try{return t(),!0}catch(o){return this.report(e,o,i),!1}}report(e,t,i){this.reported.has(i)||(this.reported.add(i),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 qe=class{constructor(e){this.boundary=e;this.listeners={};this.keys=new WeakMap;this.registrationCount=0}on(e,t){let i=`${String(e)}#${++this.registrationCount}`,o=(...r)=>t(...r);this.keys.set(o,i);let s=this.listeners[e];return s||(s=new Set,this.listeners[e]=s),s.add(o),()=>{this.listeners[e]?.delete(o)}}emit(e,...t){let i=this.listeners[e];if(!i)return!0;let o=!0;for(let s of i)this.boundary.runListener(String(e),()=>s(...t),this.keys.get(s)??String(e))||(o=!1);return o}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var Ve=class{constructor(){this.timers=new Map}schedule(e,t,i){this.clear(e);let o=setTimeout(()=>{this.timers.delete(e),t()},i);this.timers.set(e,o)}clear(e){let t=this.timers.get(e);t!==void 0&&(clearTimeout(t),this.timers.delete(e))}clearAll(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};var ce=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 Uo(n){return(n??ge).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function Ko(n){return ie(n)?`Bearer ${await he(n).getToken()}`:ye(n)}async function pi(n){try{let e=Uo(n.apiConfig?.endpoint),t=be(n.apiConfig),i=await Ko(n.apiConfig);i&&(t.Authorization=i);let o=JSON.stringify({source:n.source,session_id:n.sessionId,type:n.type,at:new Date().toISOString(),query_data:n.queryData});await fetch(e,{method:"POST",headers:t,body:o})}catch{}}var Qo="newParam",mi="suggestionRemoval",Yo="selectionAnimation",jo=650,zo=0;function Xo(){return`:ac-${++zo}:`}var fi=170;function gi(){return{text:"",completedParams:[],identifiedParams:[],skippedParams:[],pendingSpan:null,suggestions:[],products:[],customFields:null,optionSearch:null,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,dateViewMonth:null,pendingRangeStart:null,editingIdentified:null}}var Ft=class{constructor(e,t={}){this.inputStore=_t(gi());this._listboxId=Xo();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new Ve;this.boundary=new $e;this.subscriberCount=0;this.emitter=new qe(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=si(this.inputStore,i=>Rn(i,this.opts)),t.onSubmit&&this.emitter.on("submit",t.onSubmit),t.onResult&&this.emitter.on("result",t.onResult),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 Re(this.store,{onPillSelected:({rawQuery:i,selectedPill:o,otherPills:s})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:o,other_pills:s})}}),this.reEdit=new _e({store:this.store,scheduleSetCursor:i=>this.scheduleSetCursor(i),fireTelemetry:(i,o)=>this.fireTelemetry(i,o),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer(),fetchNow:()=>this.fetchNow()}),this.productsController=new De(this.store,()=>this.opts.products,()=>this.opts.showProducts!==!1),this.optionSource=new Ie(this.store,()=>this.opts.optionOverrides,{onAnswer:i=>{i==="edit"?this.reEdit.promoteIfExact():this.maybePromoteExactMatch(this.store.get().text)},onMiss:(i,o)=>{i==="pill"&&o.length>0&&this.fetchController.attemptNow()}}),this.fetchController=new ve(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.emitter.hasListeners("error")?this.emitError:void 0,()=>this.sessionId,()=>this.resolveSource(),()=>this.opts.additionalContext,{onRequest:({query:i,signal:o,isCurrent:s})=>{this.productsController.run(i,o,s).catch(()=>{})},onAutoMatch:({active:i,matched:o,rawQuery:s})=>{this.fireTelemetry("option",{raw_query:s,selected_option:o.text,other_options:(i.options??[]).filter(r=>r.text!==o.text).map(r=>r.text)})},onResponse:()=>{this.emitter.hasListeners("result")&&this.emitter.emit("result",this.buildResult())},productsForResponse:i=>this.productsController.forResponse(i),consumerTick:(i,o)=>this.optionSource.tick(i,o)}),this.keyboardController=new Oe(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),startEditingParamAtCaret:i=>this.startEditingParamAtCaret(i),exitEditMode:()=>this.exitEditMode(),exitEditingIdentified:()=>this.exitEditingIdentified(),skipActivePill:()=>this.skipActivePill()}),this.unsubscribers.push(this.store.subscribe((i,o)=>{i.text!==o.text&&this.emitter.emit("change",i.text),i.completedParams!==o.completedParams&&this.emitter.emit("paramsChange",i.completedParams),i.isFocused!==o.isFocused&&(i.isFocused?this.emitter.emit("focus"):this.emitter.emit("blur")),this.emitter.emit("stateChange",i)})),this.unsubscribers.push(this.store.subscribe(()=>this.maybeExitReEditOnNoMatch())),this.unsubscribers.push(this.store.subscribe((i,o)=>{if(i.text===o.text&&i.completedParams===o.completedParams||i.identifiedParams.length===0)return;let{valid:s,invalid:r}=xe(i.text,i.completedParams,i.identifiedParams);r.length>0&&this.store.set({identifiedParams:s})})),this.unsubscribers.push(this.store.subscribe((i,o)=>{if(i.identifiedParams===o.identifiedParams)return;let s=i.editingIdentified;if(!s||i.identifiedParams.some(l=>l.id===s.id))return;let r=0,a;for(let l of i.segments){if(l.type==="identified"&&r===s.anchor&&l.value===s.text){a=l.param;break}r+=l.value.length}if(a){this.store.set({editingIdentified:{...s,id:a.id}});return}this.store.set({editingIdentified:null,activeDropdownIndex:-1})})),this.unsubscribers.push(this.store.subscribe(i=>{let o=i.pendingRangeStart;!o||o.key===ae(i)||this.store.set({pendingRangeStart:null})})),this.unsubscribers.push(this.store.subscribe((i,o)=>{let s=i.pendingSpan;if(!s||i.text===o.text&&i.completedParams===o.completedParams&&i.identifiedParams===o.identifiedParams)return;let r=s.anchor;if(i.text!==o.text){let l=cn(o.text,i.text,r);if(l===null){this.store.set({pendingSpan:null});return}r=l}i.text.slice(r).trim().length===0||ln(i.segments,r)?this.store.set({pendingSpan:null}):r!==s.anchor&&this.store.set({pendingSpan:{anchor:r,snapshot:s.snapshot}})})),this.renderMode!=="headless"&&(ci(this.opts.styleRoot??V(this.container)),this.setupContainer()),this.renderMode==="full"?this.buildAndRenderFull():this.renderMode==="dropdown"&&this.buildAndRenderDropdown(),this.optionSource.start(),this.fetchController.start()}focus(){this.domRefs?.input.focus()}blur(){this.domRefs?.input.blur()}reset(){let e=this.store.get().isFocused;this.optionSource.reset(),this.store.set({...gi(),isFocused:e,skipNextFetch:!0}),this.sessionId=crypto.randomUUID(),this.fetchController.doFetch("",[])}destroy(){this.fetchController.dispose(),this.optionSource.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&&(_n(this.domRefs.input),Dt(this.domRefs.dropdown)),this.dropdownRefs&&Dt(this.dropdownRefs.dropdown),this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}setValue(e){let t=this.store.get();if(t.editingIdentified&&e!==t.text){this.store.set({text:e,editingIdentified:null,activeDropdownIndex:-1});return}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 i of this.store.get().segments){let o=t;if(t+=i.value.length,i.type!=="text"&&e>o&&e<=t)return{kind:i.type,param:i.param,start:o,end:t}}return null}withoutChip(e,t){return t.kind==="completed"?{completedParams:e.completedParams.filter(i=>i.id!==t.param.id)}:{identifiedParams:e.identifiedParams.filter(i=>i.id!==t.param.id)}}removeParamAtCaret(e){let t=this.findChipSpanAt(e);if(!t)return!1;let{text:i}=this.store.get(),{start:o,end:s}=t;if(e===s){let{text:l,removed:c}=ke(i,o,s);return this.store.set(d=>({text:l,filterBase:Math.min(d.filterBase>o?Math.max(o,d.filterBase-c):d.filterBase,l.length),...this.withoutChip(d,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(o),!0}let r=dt(i,e),a=i.slice(0,r)+i.slice(e);return this.store.set(l=>({text:a,filterBase:Math.min(l.filterBase,a.length),...this.withoutChip(l,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(r),!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(),R(t.input,e);else{let i=this.opts.setCursor;i&&this.boundary.runListener("setCursor",()=>i(e))}})}clearNewParamId(){this.store.set({newParamId:null})}startEditingIdentified(e){let t=this.store.get();if(t.editingIdentified?.id===e)return!0;let i=t.identifiedParams.find(d=>d.id===e);if(!i)return!1;let o=G(i);if(!E(o))return!1;let s=j(i.text),r=o==="date-range"||s?"date-range":"date",a=0,l=-1;for(let d of t.segments){if(d.type!=="text"&&d.param.id===e){l=a;break}a+=d.value.length}if(l<0)return!1;let c=l+i.text.length;return this.store.set({editingIdentified:{id:e,type:i.type,anchor:l,tail:c,text:i.text,iso:s?s.start:et(i),isoEnd:s?s.end:null,format:r},editingParam:null,editingAnchor:null,editingTail:null,caretOffset:c,activeDropdownIndex:-1,pillTapped:!0}),!0}exitEditingIdentified(){this.store.get().editingIdentified&&this.store.set({editingIdentified:null,activeDropdownIndex:-1})}startEditingParam(e){this.reEdit.start(e),this.store.get().editingParam?.id!==e&&this.startEditingIdentified(e)}replaceEditingRange(e){return this.reEdit.replaceRange(e)}exitEditMode(){this.reEdit.exit()}handleCaretAfterInput(e){this.reEdit.caretAfterInput(e)}handleCaretMove(e){let t=this.store.get().editingIdentified;t&&e!=null&&(e<t.anchor||e>t.tail)&&this.store.set({editingIdentified:null,activeDropdownIndex:-1}),this.reEdit.caretMove(e)}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}selectProduct(e){this.emitter.emit("productSelect",e)}handleTextChange(e){this.store.get().editingIdentified&&this.store.set({editingIdentified:null,activeDropdownIndex:-1}),this.handleChange(e)}showPreviousMonth(){this.pageDateView(-1)}showNextMonth(){this.pageDateView(1)}pageDateView(e){let t=this.store.get();if(!E(t.activeFormatType)||!t.dateView)return;let i=ze(t.dateView,e);this.store.set({dateViewMonth:{...i,key:ae(t)},activeDropdownIndex:-1})}skipActivePill(){let e=this.store.get();if(e.editingParam||e.inSelectionAnimation)return;let t=e.suggestions.filter(a=>a.type==="placeholder"),i=e.suggestions.filter(a=>a.type!=="placeholder");if(i.length===0)return;let o=i[0],s=i.slice(1),r=e.skippedParams.some(a=>a.type===o.type);this.store.set({suggestions:[...t,...s],pillTapped:s.length>0,activeDropdownIndex:-1,...r?{}:{skippedParams:[...e.skippedParams,{id:crypto.randomUUID(),type:o.type,suggestionPlaceholder:o.text}]}}),s.length===0&&this.fetchNow()}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(i=>{this.boundary.runListener("subscribe",()=>e(i),t)})}getState(){return this.store.get()}getResult(){return this.buildResult()}buildResult(){let e=this.store.get();return K(e.text,e.completedParams,e.skippedParams,{identifiedParams:e.identifiedParams,isReady:e.isReady,customFields:e.customFields})}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,i=this.opts.showProducts,o=this.opts.optionOverrides;Object.assign(this.opts,e),"optionOverrides"in e&&e.optionOverrides!==o&&this.optionSource.refresh(),("products"in e&&e.products!==t||"showProducts"in e&&e.showProducts!==i)&&this.productsController.resync(),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||e.showSkipButton!==void 0||e.showOptionIcons!==void 0||e.productsLayout!==void 0||e.showChipIcons!==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.activeFormatType==="date-range"){let o=k(e);if(o){let s=t.dateRangeStart;if(!s){this.store.set({pendingRangeStart:{iso:o,key:ae(t)}});return}this.store.set({pendingRangeStart:null}),this.selectOption(Xt(s,o));return}}if(t.editingIdentified){this.commitIdentifiedDate(e);return}if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null){this.reEdit.selectOption(e);return}let i=ri(t,e);if(i){if(this.fireTelemetry("option",{raw_query:I(t.text,t.completedParams).rawQuery,selected_option:i.telemetry.selectedOption,other_options:E(t.activeFormatType)?[]:i.telemetry.otherOptions}),this.store.set(i.patch),this.startSelectionAnimationTimer(),this.timers.clear(mi),i.remainingActionable>0){let o=i.consumedSuggestion;this.timers.schedule(mi,()=>{this.store.get().suggestions.includes(o)&&this.store.set(s=>({suggestions:s.suggestions.filter(r=>r!==o)}))},fi)}this.fetchNow()}}startSelectionAnimationTimer(){this.timers.schedule(Yo,()=>this.store.set({inSelectionAnimation:!1}),fi)}resolveSource(){return this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk")}fireTelemetry(e,t){let i=this.resolveSource();pi({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 ce(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 showSkipButton(){return e.opts.showSkipButton??!0},get showOptionIcons(){return e.opts.showOptionIcons??!0},get productsLayout(){return e.opts.productsLayout??"row"},get showChipIcons(){return e.opts.showChipIcons??!0},get optionsPosition(){return e.opts.optionsPosition??"below"},get onSubmit(){return e.emitter.hasListeners("submit")?e.emitSubmit:void 0},afterSubmit:()=>e.reset(),submitButton:this.opts.submitButton,autoFocus:this.opts.autoFocus??!0,selectOption:o=>this.selectOption(o),setActivePill:o=>this.pillsController.setActivePill(o),skipActivePill:()=>this.skipActivePill(),selectProduct:o=>this.selectProduct(o),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth(),handleKeyDown:o=>this.keyboardController.handleKeyDown(o),handleChange:o=>this.handleChange(o),startEditingParam:o=>this.startEditingParam(o),handleCaretAfterInput:o=>this.handleCaretAfterInput(o),handleCaretMove:o=>this.handleCaretMove(o),replaceEditingRange:o=>this.replaceEditingRange(o)};this.domRefs=oi(this.container,t);let i=()=>{this.domRefs&&kt(this.domRefs,this.store.get(),t)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),kt(this.domRefs,this.store.get(),t),this.subscribeNewParamTimer()}buildAndRenderDropdown(){let e=this,t={store:this.store,listboxId:this.listboxId,get showSkipButton(){return e.opts.showSkipButton??!0},get showOptionIcons(){return e.opts.showOptionIcons??!0},get productsLayout(){return e.opts.productsLayout??"row"},get optionsPosition(){return e.opts.optionsPosition??"below"},selectOption:o=>this.selectOption(o),setActivePill:o=>this.pillsController.setActivePill(o),skipActivePill:()=>this.skipActivePill(),selectProduct:o=>this.selectProduct(o),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth()};this.dropdownRefs=ei(this.container,t);let i=()=>{this.dropdownRefs&&Lt(this.dropdownRefs,this.store.get(),t)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),Lt(this.dropdownRefs,this.store.get(),t),this.subscribeNewParamTimer()}subscribeViewportBreakpoint(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;let t=window.matchMedia(Le),i=()=>e();t.addEventListener("change",i),this.unsubscribers.push(()=>t.removeEventListener("change",i))}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(Qo,()=>this.store.set({newParamId:null}),jo)}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:o}=mn(e,t.completedParams);o.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=F(e.text,Math.min(e.filterBase,e.text.length),e.placeholderText),i=an(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(s=>s.id===e.editingParam?.id)||this.optionSource.owns(e.editingParam.suggestionType,e.optionQuery))return;let t=e.caretOffset??e.editingAnchor,i=e.text.slice(e.editingAnchor,t);q(e.editingParam.options,i).some(s=>s.is_tappable)||(this.reEdit.exit(),this.fetchNow())}fetchNow(){let e=this.store.get(),{rawQuery:t,completedParams:i}=I(e.text,e.completedParams);this.fetchController.doFetch(t,i)}commitIdentifiedDate(e){let t=this.store.get(),i=t.editingIdentified;if(!i)return;if(t.text.slice(i.anchor,i.tail)!==i.text){this.store.set({editingIdentified:null,activeDropdownIndex:-1});return}let o=t.text.slice(0,i.anchor),s=t.text.slice(i.tail),r=i.anchor===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,l=s.length===0||s[0]!==" "?`${r} `:r,c=o+l+s,d=c.length,u={id:crypto.randomUUID(),placeholder:"",type:i.type,text:r,value:e.value,kind:e.kind,suggestionType:i.type,suggestionPlaceholder:B(i.type),options:[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg};this.fireTelemetry("option",{raw_query:I(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:[]}),this.store.set({text:c,completedParams:[...t.completedParams,u],identifiedParams:t.identifiedParams.filter(f=>f.id!==i.id),newParamId:u.id,filterBase:d,caretOffset:d,editingIdentified:null,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.startSelectionAnimationTimer(),this.scheduleSetCursor(d),this.fetchNow()}maybePromoteExactMatch(e){let t=this.store.get();if(E(t.activeFormatType))return;let i=Me({mode:"fresh",text:e,completedParams:t.completedParams,suggestions:t.suggestions,filterBase:t.filterBase,filterInProgress:t.filterInProgress});i&&this.store.set(i.patch)}};export{Ft as AIAutocomplete,Nn as ATTRIBUTION_URL,it as DATE_RANGE_META_END,nt as DATE_RANGE_META_START,ce as ModeController,Le as OPTIONS_GRID_MOBILE_QUERY,Ct as OPTION_ENTER_DELAY_VAR,mo as OPTION_ENTER_FADE_MS,fo as OPTION_ENTER_RISE_MS,go as OPTION_ENTER_RISE_PX,po as OPTION_ENTER_STAGGER_MS,eo as PLACEHOLDER_FADE_OUT_MS,J as PLACEHOLDER_LEAVING_ATTR,to as PLACEHOLDER_SWAP_GAP_MS,Ji as PLACEHOLDER_TYPE_MS,Zi as PLACEHOLDER_WORD_PAUSE_MS,Tn as PRODUCT_PATH_PREFIX,ao as PRODUCT_ROW_PX_PER_LINE,jt as RANGE_SEPARATOR,Yn as SCROLL_ARROW_ATTR,zn as SCROLL_ARROW_BOTTOM_VAR,Qn as SCROLL_ARROW_CLASS,To as SCROLL_ARROW_FADE_MS,Xn as SCROLL_ARROW_LABEL,jn as SCROLL_ARROW_SCROLL_IDLE_MS,He as SCROLL_ARROW_VISIBLE_ATTR,en as SKIPPED_PARAM_TEXT,ue as WEEKDAY_LABELS,ze as addMonths,wt as attachProductRowWheel,Rt as attachScrollArrow,St as buildAttributionUrl,Xe as buildDateOptions,I as buildQuery,K as buildSubmitResult,Ze as cellDay,k as cellIso,An as computeOptionsGridLayout,_t as createStore,lt as cursorIsAtEnd,Pt as dateCellMarks,le as dateSelectionFor,Ae as extractPlainText,Y as formatAbsoluteDate,Vt as formatDate,zt as formatDateRange,M as getCursorOffset,xt as getFooterHint,B as identifiedParamLabel,E as isCalendarFormat,yt as isOptionsGridMobileViewport,D as isoDate,bt as measureOptionsGrid,Ye as monthLabel,gt as needsOptionsGridMeasurement,At as optionEnterDelayMs,It as optionLabel,Ot as optionsEntranceDurationMs,ft as optionsGridTemplateColumns,pe as parseDate,W as parseLooseDate,j as parseLooseDateRange,at as plainTextLength,ht as planOptionsGrid,dt as previousGraphemeBoundary,Cn as productFromMatchedItem,$n as productRowWheelTarget,pt as productsFromCustomFields,Mt as renderEditableContent,G as resolveFormatType,et as resolveIdentifiedDate,de as sanitizeOptionIconSvg,st as scrollCaretIntoView,Je as selectedIsoFromText,ne as selectedRangeFor,R as setCursorOffset,oe as toWireIdentifiedParams,vt as visibleDateRange,re as withSkippedParams};
|
|
1929
1929
|
//# sourceMappingURL=index.mjs.map
|