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