@magicx-eng/ai-autocomplete-vanilla 0.27.0 → 0.28.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/index.d.mts +10 -6
- package/dist/index.d.ts +10 -6
- package/dist/index.js +50 -32
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +50 -32
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
function Ye(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9]+/).filter(Boolean).map(e=>e.toLowerCase())}function W(n){let e=Ye(n);return e.length>0?e.join(" "):n}var Y=["January","February","March","April","May","June","July","August","September","October","November","December"],me=["S","M","T","W","T","F","S"],qt=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],Ut="aiaDate",Vt="aiaDay",$t=n=>String(n).padStart(2,"0");function M(n){return`${n.getFullYear()}-${$t(n.getMonth()+1)}-${$t(n.getDate())}`}function je(n){return new Date(n.getFullYear(),n.getMonth(),n.getDate())}function xi(n){let e=je(n).getTime()-je(new Date).getTime();return Math.round(e/864e5)}function Kt(n){let e=xi(n);return e>=0&&e<7?qt[n.getDay()]:j(n)}function j(n){return n.getFullYear()===new Date().getFullYear()?`${Y[n.getMonth()]} ${n.getDate()}`:`${Y[n.getMonth()]} ${n.getDate()} ${n.getFullYear()}`}function fe(n){if(!n)return null;let e=qt.findIndex(a=>a.toLowerCase()===n.trim().toLowerCase());if(e>=0){let a=je(new Date),l=(e-a.getDay()+7)%7;return new Date(a.getFullYear(),a.getMonth(),a.getDate()+l)}let t=/^\s*([A-Za-z]+)\s+(\d{1,2})(?:\s+(\d{4}))?\s*$/.exec(n);if(!t)return null;let i=Y.findIndex(a=>a.toLowerCase()===t[1].toLowerCase());if(i<0)return null;let o=Number(t[2]),r=t[3]?Number(t[3]):new Date().getFullYear(),s=new Date(r,i,o);return s.getMonth()!==i||s.getDate()!==o?null:s}function ze(n){return`${Y[n.month]} ${n.year}`}function Xe(){let n=new Date;return{year:n.getFullYear(),month:n.getMonth()}}function Qt(n){return{year:n.getFullYear(),month:n.getMonth()}}function Je(n,e){let t=new Date(n.year,n.month+e,1);return{year:t.getFullYear(),month:t.getMonth()}}function Gt(){return{text:"",is_tappable:!1,kind:null}}function Ze(n){let e=new Date(n.year,n.month,1).getDay(),t=new Date(n.year,n.month+1,0).getDate(),i=[];for(let o=0;o<e;o++)i.push(Gt());for(let o=1;o<=t;o++){let r=new Date(n.year,n.month,o);i.push({text:Kt(r),is_tappable:!0,kind:null,metadata:{[Ut]:M(r),[Vt]:o}})}for(;i.length%me.length!==0;)i.push(Gt());return i}function et(n){let e=fe(n);return e?M(e):null}function N(n){let e=n?.metadata?.[Ut];return typeof e=="string"?e:null}function tt(n){let e=n?.metadata?.[Vt];return typeof e=="number"?e:null}function vi(n){return n.replace(/(\d+)(?:st|nd|rd|th)\b/g,"$1")}function Yt(n){let e=n.toLowerCase().replace(/\.$/,"");return e.length<3?-1:Y.findIndex(t=>t.toLowerCase().startsWith(e))}function wi(n,e,t){let i=new Date(t.getFullYear(),n,e);if(i.getMonth()!==n||i.getDate()!==e)return null;let o=new Date(t.getFullYear(),t.getMonth(),t.getDate());if(i>=o)return i;let r=new Date(t.getFullYear()+1,n,e);return r.getMonth()===n&&r.getDate()===e?r:null}function jt(n,e,t){let i=new Date(n,e,t);return i.getMonth()===e&&i.getDate()===t?i:null}function $(n,e={}){if(!n)return null;let t=e.today??new Date,i=vi(n.trim().toLowerCase()).replace(/\s+/g," "),o=/^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(i);if(o){let l=jt(Number(o[1]),Number(o[2])-1,Number(o[3]));return l?M(l):null}let r=/^([a-z]+)\.? (\d{1,2})(?:,? (\d{4}))?$/.exec(i);if(r){let l=Yt(r[1]);if(l>=0)return ge(l,Number(r[2]),r[3],t)}let s=/^(\d{1,2}) (?:of )?([a-z]+)\.?(?:,? (\d{4}))?$/.exec(i);if(s){let l=Yt(s[2]);if(l>=0)return ge(l,Number(s[1]),s[3],t)}let a=/^(\d{1,2})[/\-.](\d{1,2})(?:[/\-.](\d{2,4}))?$/.exec(i);if(a){let l=Number(a[1]),c=Number(a[2]);return l>12&&c<=12?ge(c-1,l,a[3],t):c>12&&l<=12?ge(l-1,c,a[3],t):null}return null}function ge(n,e,t,i){if(t){if(t.length!==4)return null;let r=jt(Number(t),n,e);return r?M(r):null}let o=wi(n,e,i);return o?M(o):null}function nt(n,e={}){let t=n.isoDate;return typeof t=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t)?t:$(n.text,e)}var Xt=" - ",ot="aiaDateRangeStart",rt="aiaDateRangeEnd";function ne(n,e){return n<=e?{start:n,end:e}:{start:e,end:n}}var it=/^\d{4}-\d{2}-\d{2}$/;function zt(n){if(!it.test(n))return null;let[e,t,i]=n.split("-").map(Number),o=new Date(e,t-1,i);return o.getMonth()===t-1&&o.getDate()===i?o:null}var Pi=/\s+(?:to|through|thru|until|til|till)\s+/g,Ei=/[-–—]/g;function Ti(n){let e=[];for(let t of[Pi,Ei]){t.lastIndex=0;let i=t.exec(n);for(;i!==null;)e.push([n.slice(0,i.index),n.slice(i.index+i[0].length)]),i=t.exec(n)}return e}function z(n,e={}){if(!n)return null;let t=new Set,i=null;for(let[o,r]of Ti(n.trim())){let s=$(o.trim(),e);if(!s)continue;let a=$(r.trim(),e);!a||a<s||(t.add(`${s}|${a}`),i={start:s,end:a})}return t.size===1?i:null}function Jt(n){let e=zt(n.start),t=zt(n.end);return!e||!t?"":n.start===n.end?j(e):`${j(e)}${Xt}${j(t)}`}function Zt(n,e){let t=ne(n,e);return{text:Jt(t),is_tappable:!0,kind:null,metadata:{[ot]:t.start,[rt]:t.end}}}function ie(n,e={}){let t=n?.metadata?.[ot],i=n?.metadata?.[rt];return typeof t=="string"&&typeof i=="string"&&it.test(t)&&it.test(i)?ne(t,i):z(n?.text,e)}function P(n){return n==="date"||n==="date-range"}var Ci=new Set(["date","dates"]),Oi=new Set(["range","ranges","span","period","window"]),en=3;function Ai(n){let e={single:0,range:0};if(!n)return e;for(let t of n)t.is_tappable&&(z(t.text)!==null?e.range+=1:$(t.text)!==null&&(e.single+=1));return e}function G(n){if(!n)return"options";let e=n.formatType;if(e==="date"||e==="options"||e==="date-range")return e;let t=Ai(n.options);if(t.single+t.range>=en&&t.range>t.single)return"date-range";let i=Ye(n.type);return i.some(o=>Ci.has(o))?i.some(o=>Oi.has(o))?"date-range":"date":t.single>=en?"date":"options"}var he=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 Ii="https://api.ai-autocomplete.com",be=`${Ii}/api/suggest`,tn=new WeakMap;function oe(n){return n?.type==="accessToken"}function Ri(n){if(!(!n||oe(n)))return n}function ye(n){let e=tn.get(n.getAccessToken);return e||(e=new he(n),tn.set(n.getAccessToken,e)),e}function Se(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function xe(n){let e=Ri(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}function re(n){return n.map(e=>({type:e.type,value:e.text}))}var nn="skipped";function se(n,e){if(e.length===0)return n;let t=new Set(n.map(o=>o.type)),i=e.filter(o=>!t.has(o.type)).map(o=>({placeholder:"",type:o.type,text:nn,kind:null}));return i.length>0?[...n,...i]:n}var Di="0.27.0",on=!1;function Li(){return crypto.randomUUID()}function Mi(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.value??n.text},kind:n.kind}}function _i(n,e,t,i,o,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:se(e.map(u=>Mi(u,t)),a??[]),...r&&r.length>0&&{identified_params:re(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:Di,session_id:i,source:o}}}async function rn(n,e,t,i,o){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:o})}async function sn(n,e,t){let i=t.apiConfig,o=!t.maskCompletedText,r=_i(n,e,o,t.sessionId,t.source,t.identifiedParams,t.recentlySuggested,t.skippedParams,t.additionalContext),s=Se(i),a=i?.endpoint??be,l=JSON.stringify(r);if(oe(i)){let u=ye(i),p=await u.getToken(),g=await rn(a,s,p,l,t.signal);if(g.status===401){let b=await u.getToken(!0);g=await rn(a,s,b,l,t.signal)}if(!g.ok)throw new Error(`API error: ${g.status} ${g.statusText}`);return g.json()}let c=xe(i);!c&&!on&&(on=!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,i={},o=[],r=[],s=0;for(let a of e){let l=(i[a.type]??0)+1;i[a.type]=l;let d=`{{${a.type.toUpperCase().replace(/\s+/g,"_")}_${l}}}`,u=g=>{let b=t.indexOf(a.text,g);for(;b!==-1&&r.some(y=>b<y.end&&b+a.text.length>y.start);)b=t.indexOf(a.text,b+1);return b},p=u(s);if(p===-1&&(p=u(0)),p!==-1){t=t.slice(0,p)+d+t.slice(p+a.text.length);let g=d.length-a.text.length;for(let b of r)b.start>=p+a.text.length&&(b.start+=g,b.end+=g);r.push({start:p,end:p+d.length}),s=p>=s?p+d.length:s+g}o.push({...a,placeholder:d})}return{rawQuery:t,completedParams:o}}function F(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function ve(n,e,t){return e===0&&n.length>0&&t.length>0&&t.toLowerCase().startsWith(n.toLowerCase())}function q(n,e,t){let i=n.slice(e);if(t||e===0||n[e-1]===" ")return i;let o=i.indexOf(" ");return o===-1?"":i.slice(o+1)}function an(n,e){let t=n.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let i=t.split(" "),o=e.toLowerCase();for(let r=0;r<i.length;r++){let s=i.slice(r).join(" ");if(o.startsWith(s.toLowerCase())){let a=t.length-s.length;return n.length-a}}return 0}function U(n,e){if(!n)return[];let t=e.trimStart();if(!t)return n;let i=t.toLowerCase();return n.filter(o=>!o.is_tappable||o.text.toLowerCase().includes(i))}function X(n,e){if(!n)return null;let t=e.trim();if(!t)return null;let i=t.toLowerCase();return n.find(o=>o.is_tappable&&o.text.toLowerCase()===i)??null}function ln(n,e){return e?n.map(t=>e[t.type]?{...t,options:[]}:t):n}function dn(n,e){let t=0,i=e;for(let o of n)t+=o.value.length,o.type!=="text"&&(i=Math.max(i,t));return i}function cn(n,e){let t=0;for(let i of n){let o=t+i.value.length;if(i.type==="text"&&o>e&&i.value.slice(Math.max(e-t,0)).trim().length>0)return!1;t=o}return!0}function un(n,e){let t=[],i=new Set;for(let o of[...n,...e])o.type==="placeholder"||i.has(o.type)||(i.add(o.type),t.push({type:o.type,text:o.text}));return t}function pn(n,e,t){if(n===e)return t;let i=Math.min(n.length,e.length),o=0;for(;o<i&&n[o]===e[o];)o++;if(o>=t)return t;let r=0;for(;r<i-o&&n[n.length-1-r]===e[e.length-1-r];)r++;return n.length-r<=t?t+(e.length-n.length):null}function st(n,e){let t=[],i=[],o=0;for(let r of e){let s=n.indexOf(r.text,o);if(s===-1){i.push(r);continue}t.push({start:s,end:s+r.text.length,param:r}),o=s+r.text.length}return{located:t,missing:i}}function mn(n,e,t){let i=[],o=[],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){o.push(s);continue}i.push({start:a,end:a+s.text.length,param:s}),r=a+s.text.length}return{located:i,missing:o}}function fn(n,e,t=[]){let i=st(n,e).located,o=mn(n,i,t).located,r=[...i.map(c=>({start:c.start,end:c.end,segment:{type:"completed",value:c.param.text,param:c.param}})),...o.map(c=>({start:c.start,end:c.end,segment:{type:"identified",value:c.param.text,param:c.param}}))].sort((c,d)=>c.start-d.start),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 gn(n,e){let{located:t,missing:i}=st(n,e);return{valid:t.map(o=>o.param),invalid:i}}function we(n,e,t){let i=st(n,e).located,{located:o,missing:r}=mn(n,i,t);return{valid:o.map(s=>s.param),invalid:r}}function ki(n){if(n instanceof Error)return n;try{return new Error(String(n))}catch{return new Error("Unknown error")}}var Ni=100,Fi=300,Hi=2,Pe=class{constructor(e,t,i,o,r,s,a,l,c={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=o;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(i=>{(i.text!==e||i.completedParams!==t)&&(e=i.text,t=i.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let i=new AbortController;this.abortController=i;let o=++this.fetchVersion,r=this.store.get().text.length;try{this.callbacks.onRequest?.({query:this.store.get().text,signal:i.signal,isCurrent:()=>o===this.fetchVersion})}catch{}try{this.store.set({isLoading:!0,error:null});let s=this.store.get(),a=s.pendingSpan?un(s.pendingSpan.snapshot,s.actionableSuggestions):void 0,l=await sn(e,t,{sessionId:this.getSessionId(),source:this.getSource(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig(),identifiedParams:s.identifiedParams,recentlySuggested:a,skippedParams:s.skippedParams,additionalContext:this.getAdditionalContext()});if(o!==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=ln(l.data.suggestions??[],this.getOptionOverrides()),u=l.data.input??[],p=u[u.length-1],g=this.store.get().text,b,y;if(p?.state==="in_progress"){y=!0;let v=g.toLowerCase().lastIndexOf(p.text.toLowerCase());b=v!==-1?v:r}else y=!1,b=r;let f=d.filter(v=>v.type!=="placeholder")[0],m=null;if(f&&!P(G(f))){let v=q(g,b,y),E=X(f.options,v);E&&(m={id:crypto.randomUUID(),placeholder:"",type:f.type,text:E.text,value:E.value,kind:E.kind,suggestionType:f.type,suggestionPlaceholder:f.text,options:f.options??[],metadata:E.metadata,icon:E.icon,icon_svg:E.icon_svg,image_url:E.image_url},d=d.filter(A=>A!==f),this.callbacks.onAutoMatch?.({active:f,matched:E,rawQuery:e}))}let h=l.data.custom_fields??null,x=this.callbacks.productsForResponse?.(h);this.store.set(v=>{let E=m?[...v.completedParams,m]:v.completedParams,A=we(v.text,E,c).valid,L=new Set(s.skippedParams.map(C=>C.id)),T=new Set(v.skippedParams.filter(C=>!L.has(C.id)).map(C=>C.type));return{suggestions:T.size>0?d.filter(C=>C.type==="placeholder"||!T.has(C.type)):d,isLoading:!1,isReady:l.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:b,filterInProgress:y,identifiedParams:A,customFields:h,...x!==void 0?{products:x}:{},...m?{completedParams:E}:{}}}),this.callbacks.onResponse?.()}catch(s){let a=ki(s);o===this.fetchVersion&&(this.store.set({error:a,isLoading:!1}),this.getOnError()?.(a))}finally{if(o===this.fetchVersion&&this.store.get().isLoading)try{this.store.set({isLoading:!1})}catch{}}}attemptNow(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}this.attemptFetch(1,!0)}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}this.debounceTimer=setTimeout(()=>{this.attemptFetch(Hi)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},Ni),this.slowDebounceTimer=setTimeout(()=>this.attemptFetch(1),Fi)}attemptFetch(e,t=!1){let i=this.store.get();if(!i.text&&i.completedParams.length===0)return this.doFetch("",[]),!0;let o=this.callbacks.consumerTick?.(i,e)??"no";if(o==="asked")return!0;if(o==="owns")return!1;let r=i.suggestions.filter(x=>x.type==="placeholder").map(x=>x.text).join(" "),s=F(i.text,i.filterBase,r),a=q(i.text,s,i.filterInProgress),c=i.suggestions.filter(x=>x.type!=="placeholder")[0],d=P(i.activeFormatType),p=(c&&!d?U(c.options,a):[]).filter(x=>x.is_tappable),g=c&&!d?X(c.options,a)!==null:!1,b=a.trim().length>0;if(p.length>0&&!g&&b||ve(i.text,i.completedParams.length,r))return!1;let{rawQuery:y,completedParams:S}=R(i.text,i.completedParams),f=y.length<i.lastRawQuery.length,m=Math.abs(y.length-i.lastRawQuery.length),h=t&&y!==i.lastRawQuery;return f||m>=e||h?(this.doFetch(y,S),!0):!1}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};function Bi(n){return n.nodeType===Node.DOCUMENT_NODE?!0:n.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in n}function V(n){let e=typeof n.getRootNode=="function"?n.getRootNode():null;return e&&Bi(e)?e:n.ownerDocument??n}function O(n){return n.ownerDocument??n}function Wi(n){return n.nodeType===Node.DOCUMENT_FRAGMENT_NODE}function hn(n){let e=V(n);return!Wi(e)||typeof e.getSelection=="function"?null:e}function bn(n){let e=hn(n);if(!e)return null;let t=O(n).getSelection?.();return!t||typeof t.getComposedRanges!="function"?null:e}function yn(n,e){let t=n,i;try{i=t.getComposedRanges({shadowRoots:[e]})}catch{i=t.getComposedRanges(e)}return i.length>0?i[0]:null}function at(n){let t=V(n).getSelection?.();return t||(O(n).getSelection?.()??null)}function K(n){let e=at(n);if(!e||e.rangeCount===0)return null;let t=bn(n);if(t){let i=yn(e,t);return i?{node:i.startContainer,offset:i.startOffset,collapsed:i.startContainer===i.endContainer&&i.startOffset===i.endOffset}:null}return e.anchorNode?{node:e.anchorNode,offset:e.anchorOffset,collapsed:e.isCollapsed}:null}function Ee(n){let e=at(n);if(!e||e.rangeCount===0)return null;let t=bn(n);if(!t)return e.getRangeAt(0);let i=yn(e,t);if(!i)return null;let o=O(n).createRange();return o.setStart(i.startContainer,i.startOffset),o.setEnd(i.endContainer,i.endOffset),o}function ae(n,e,t){let i=at(n);if(!i)return null;if(hn(n))return i.collapse(e,t),i;let o=O(n).createRange();return o.setStart(e,t),o.collapse(!0),i.removeAllRanges(),i.addRange(o),i}function Te(n,e){let t=n?V(n):typeof document<"u"?document:null;return t?typeof t.getElementById=="function"?t.getElementById(e):typeof document<"u"?document.getElementById(e):null:null}var Ce=2,$i="magicx-aia";function Sn(n){return n==="auto"||n==="scroll"||n==="hidden"||n==="overlay"}function Gi(n){let e=O(n),t=e.defaultView;if(!t?.getComputedStyle)return null;let i=n;for(;i&&i!==e.body&&i!==e.documentElement;){let o=i.scrollWidth>i.clientWidth,r=i.scrollHeight>i.clientHeight;if(o||r){let s=t.getComputedStyle(i);if(o&&Sn(s.overflowX)||r&&Sn(s.overflowY))return i}if(i.classList.contains($i))return null;i=i.parentElement}return null}function lt(n){let e=Ee(n);if(!e||!e.collapsed||!n.contains(e.startContainer))return;let t=Gi(n);if(!t||typeof e.getBoundingClientRect!="function")return;let i=e.getBoundingClientRect();if(i.height===0)return;let o=t.getBoundingClientRect();if(t.scrollWidth>t.clientWidth){let r=o.left+t.clientLeft,s=r+t.clientWidth;i.right>s?t.scrollLeft+=i.right-s+Ce:i.left<r&&(t.scrollLeft-=r-i.left+Ce)}if(t.scrollHeight>t.clientHeight){let r=o.top+t.clientTop,s=r+t.clientHeight;i.bottom>s?t.scrollTop+=i.bottom-s+Ce:i.top<r&&(t.scrollTop-=r-i.top+Ce)}}var wn='[contenteditable="false"]',qi="strong[data-param-id]",J;function Ui(){if(J!==void 0)return J;let n=globalThis.Intl.Segmenter;if(!n)return J=null,null;try{J=new n(void 0,{granularity:"grapheme"})}catch{J=null}return J??null}function Oe(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(wn))return!0;t=t.parentNode}return!1}function Ae(n){return O(n).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return Oe(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function Ie(n){let e=Ae(n),t="",i=e.nextNode();for(;i;)t+=i.data,i=e.nextNode();return t}function dt(n){let e=Ae(n),t=0,i=e.nextNode();for(;i;)t+=i.data.length,i=e.nextNode();return t}function k(n){let e=K(n);if(!e)return null;let t=e.node,i=e.offset;if(!n.contains(t))return null;if(t.nodeType===Node.ELEMENT_NODE){let o=t;if(Oe(o,n)&&o!==n)return null;let r=0;for(let s=0;s<i&&s<o.childNodes.length;s++)r+=Pn(o.childNodes[s],n);return r+xn(o,n)}return t.nodeType!==Node.TEXT_NODE||Oe(t,n)?null:xn(t,n)+i}function Pn(n,e){if(n.nodeType===Node.TEXT_NODE)return Oe(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(wn))return 0;let i=0;for(let o of Array.from(t.childNodes))i+=Pn(o,e);return i}function xn(n,e){let t=Ae(e),i=0,o=t.nextNode();for(;o;){if(o===n||n.nodeType===Node.ELEMENT_NODE&&n.contains(o))return i;i+=o.data.length,o=t.nextNode()}return i}function D(n,e){let t=O(n),i=Math.max(0,Math.min(e,dt(n))),o=Ae(n),r=0,s=null,a=0,l=o.nextNode(),c=null;for(;l;){let u=l.data.length;if(i<r+u){s=l,a=i-r;break}if(i===r+u){let p=o.nextNode();p?(s=p,a=0):(s=l,a=u);break}r+=u,c=l,l=o.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),ae(n,d.startContainer,d.startOffset)&&(Vi(n,d,i),lt(n))}function vn(n,e){if(!n||!e.contains(n))return null;let i=(n.nodeType===Node.ELEMENT_NODE?n:n.parentElement)?.closest(qi)??null;return i&&e.contains(i)?i:null}function Vi(n,e,t){let i=vn(K(n)?.node??null,n);if(i&&i!==vn(e.startContainer,n)){n.dataset.aiaCaretEscapedChip=`${t}:${i.dataset.paramId}`;return}delete n.dataset.aiaCaretEscapedChip}function En(n,e){let t=n.dataset.aiaCaretEscapedChip;if(!t)return!1;let i=k(n);return i!==null&&t===`${i}:${e}`}function Tn(n){return V(n).activeElement===n}function ct(n){let e=k(n);return e==null?!1:e>=dt(n)}function ut(n,e){if(e<=0)return 0;let t=Ui();if(!t)return e-1;let i=n.slice(0,e),o=0;for(let{index:r}of t.segment(i))r<e&&(o=r);return o}function Q(n,e,t=[],i={}){let{rawQuery:o,completedParams:r}=R(n,e);return{query:n.trim(),raw_query:o,completed_params:se(r,t),identified_params:re(i.identifiedParams??[]),is_ready:i.isReady??!1,...i.customFields?{custom_fields:i.customFields}:{}}}function pt(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")?ct(n):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function mt(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?k(n):null}var Re=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:o}=this.ctx,r=e.target instanceof Node?e.target:null,s=this.getEffectiveColumns(r),a=o(),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=pt(e.target,t),u=!!t.editingParam;if(!d&&!u&&t.activeDropdownIndex<0)break;if(t.activeDropdownIndex<0){if(c)break;e.preventDefault();let b=P(t.activeFormatType)?this.dateEntryIndex(t,!1):l[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:b});break}if(l.length===0)return;this.store.set({activeDropdownIndex:b});break}if(e.preventDefault(),l.length===0)return;if(P(t.activeFormatType)){this.stepDateWeek(t,7);break}if(t.filteredOptions.length>0){let b=Math.floor((t.filteredOptions.length-1)/s);if(Math.floor(t.activeDropdownIndex/s)===b){this.store.set({activeDropdownIndex:-1});break}}let p=l.indexOf(t.activeDropdownIndex),g=p<l.length-1?p+1:0;this.store.set({activeDropdownIndex:l[g]});break}case"ArrowUp":{if(t.activeDropdownIndex<0){if(!c)break;let p=pt(e.target,t),g=!!t.editingParam;if(!p&&!g)break;e.preventDefault();let b=P(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:b});break}if(l.length===0)return;this.store.set({activeDropdownIndex:b});break}if(l.length===0)break;if(e.preventDefault(),P(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(),P(t.activeFormatType)){this.stepDateDay(t,1);break}if(t.activeDropdownIndex%s<s-1){let p=t.activeDropdownIndex+1;p<t.filteredOptions.length&&t.filteredOptions[p]?.is_tappable&&this.store.set({activeDropdownIndex:p})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let u=e.target.closest("[data-aia-input]")??e.target,p=t.editingTail;this.ctx.exitEditMode?.(),D(u,p);break}pt(e.target,t)&&t.actionableSuggestions.length>=1&&(e.preventDefault(),this.ctx.skipActivePill());break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),P(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=mt(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?.(),D(d,u);break}if(this.ctx.startEditingParamAtCaret){let d=mt(e.target);d!=null&&this.ctx.startEditingParamAtCaret(d)&&e.preventDefault()}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let d=mt(e.target);if(d==null)break;this.ctx.removeParamAtCaret(d)&&e.preventDefault();break}case"Enter":{e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable?this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i,r):a&&a(Q(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,b)=>g.is_tappable?b:-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),p;if(u<0)p=e.shiftKey?d.length-1:0;else{let g=e.shiftKey?-1:1;p=(u+g+d.length)%d.length}this.store.set({activeDropdownIndex:d[p]});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?.(),D(d,u)}this.store.set({activeDropdownIndex:-1});break}}}firstTappableInBottomRow(e){let t=this.store.get();if(t.filteredOptions.length===0)return null;let o=Math.floor((t.filteredOptions.length-1)/e)*e;for(let r=o;r<t.filteredOptions.length;r++)if(t.filteredOptions[r]?.is_tappable)return r;return null}dateEntryIndex(e,t){let i=M(new Date),o=e.filteredOptions.findIndex(s=>N(s)===i);if(o>=0)return o;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 i=e.activeDropdownIndex+t;i>=0&&i<e.filteredOptions.length;i+=t)if(e.filteredOptions[i]?.is_tappable){this.store.set({activeDropdownIndex:i});return}}stepDateWeek(e,t){let i=e.activeDropdownIndex+t;this.store.set({activeDropdownIndex:e.filteredOptions[i]?.is_tappable?i:-1})}getTappableIndices(e){let i=this.store.get().filteredOptions.map((r,s)=>r.is_tappable?s:-1).filter(r=>r!==-1),o=Array.from({length:e},()=>[]);for(let r of i)o[r%e].push(r);return o.flat()}getEffectiveColumns(e){let t=Te(e,this.ctx.listboxId);if(!t)return this.ctx.columns;let o=Te(e,`${this.ctx.listboxId}-option-0`)?.parentElement??null;for(;o;){let r=getComputedStyle(o).gridTemplateColumns;if(r&&r!=="none"){let s=r.split(" ").filter(Boolean).length;if(s>0)return s}if(o===t)break;o=o.parentElement}return this.ctx.columns}clickOrSelect(e,t,i,o){let r=Te(o,`${i}-option-${e}`);r?r.click():this.ctx.selectOption(t[e])}};var De=class{constructor(e,t,i={}){this.store=e;this.getOverrides=t;this.callbacks=i;this.unsubscribe=null;this.current=null;this.version=0;this.lastMiss=null;this.hasLoggedError=!1}start(){this.unsubscribe=this.store.subscribe(e=>this.sync(e)),this.sync(this.store.get())}dispose(){this.unsubscribe?.(),this.unsubscribe=null,this.cancel(),this.current=null}reset(){this.cancel(),this.current=null,this.lastMiss=null}refresh(){this.reset(),this.sync(this.store.get())}hasOverride(e){return!!this.getOverrides()?.[e]}owns(e,t){return this.hasOverride(e)&&!this.missCovers(e,t)}tick(e,t){let i=this.resolveTarget(e);if(!i||this.missCovers(i.type,i.query))return"no";let o=this.current;if(o&&o.key===i.key){if(o.query===i.query)return"owns";let r=Math.abs(i.query.length-o.query.length),s=i.query.length<o.query.length;if(t>1&&!s&&r<t)return"owns"}return this.ask(i),"asked"}sync(e){let t=this.resolveTarget(e);if(!t){this.current&&(this.cancel(),this.current=null),e.optionSearch&&this.store.set({optionSearch:null});return}this.current&&this.current.key===t.key||this.ask(t)}resolveTarget(e){if(P(e.activeFormatType)||e.editingIdentified)return null;let t=e.editingParam;if(t&&e.editingAnchor!=null)return this.hasOverride(t.suggestionType)?{mode:"edit",key:t.id,type:t.suggestionType,suggestion:{type:t.suggestionType,text:t.suggestionPlaceholder,required:!0,options:t.options},query:e.optionQuery}:null;let i=e.actionableSuggestions[0];return!i||!this.hasOverride(i.type)?null:{mode:"pill",key:i,type:i.type,suggestion:i,query:e.optionQuery}}missCovers(e,t){return this.lastMiss!=null&&this.lastMiss.type===e&&this.lastMiss.query===t}ask(e){this.cancel();let t=this.getOverrides()?.[e.type],i=++this.version;if(!t||this.missCovers(e.type,e.query)){this.current={key:e.key,type:e.type,query:e.query,abort:null},this.setSearch(e,"done");return}let o=new AbortController;this.current={key:e.key,type:e.type,query:e.query,abort:o};let r;try{r=t(e.query,o.signal,e.suggestion)}catch(s){this.logOnce(s),this.commit(e,[],i);return}if(Array.isArray(r)){this.commit(e,r,i);return}this.setSearch(e,"loading"),this.await(e,r,o.signal,i)}async await(e,t,i,o){let r;try{let s=await t;if(i.aborted||o!==this.version)return;r=Array.isArray(s)?s:[]}catch(s){if(i.aborted||o!==this.version||Ki(s))return;this.logOnce(s),r=[]}this.commit(e,r,o)}commit(e,t,i){if(i!==this.version)return;let o=this.resolveTarget(this.store.get());if(!o||o.key!==e.key)return;t.length===0?this.lastMiss={type:e.type,query:e.query}:this.lastMiss?.type===e.type&&(this.lastMiss=null);let 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 i=this.store.get().optionSearch;i&&i.type===e.type&&i.query===e.query&&i.status===t||this.store.set({optionSearch:{type:e.type,query:e.query,status:t}})}cancel(){this.current?.abort?.abort(),this.version++}logOnce(e){this.hasLoggedError||(this.hasLoggedError=!0,console.warn("[AIAutocomplete] an optionOverrides entry threw or rejected \u2014 treated as no options. Later failures on this instance are not logged.",e))}};function Ki(n){return n instanceof Error&&n.name==="AbortError"}var Le=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),i=t.suggestions.filter(c=>c.type!=="placeholder");if(e<0||e>=i.length)return;let o=i[e],r=i.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:o.text,otherPills:r.map(d=>d.text)})}let a=[...s,o,...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 On="/products/",Cn="https://relative.invalid";function Qi(n){if(!n)return;let e;try{e=new URL(n,`${Cn}/`)}catch{return}if(!(e.protocol!=="http:"&&e.protocol!=="https:"))return n.startsWith("/")?e.origin===Cn?n:void 0:/^https?:\/\//i.test(n)?n:void 0}function An(n){let e=Qi(n.item_url)??(n.handle?`${On}${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 ft(n){return(n?.items.matched??[]).map(An)}var Me=class{constructor(e,t,i=()=>!0){this.store=e;this.getConfig=t;this.isEnabled=i;this.hasLoggedError=!1}forResponse(e){if(!this.isEnabled())return[];if(!this.getConfig())return ft(e)}async run(e,t,i){if(!this.isEnabled())return;let o=this.getConfig();if(!o)return;if(e.trim().length===0){this.clear(i);return}let r=()=>t.aborted||!i()||!this.owns(o);try{let s=await o.fetch(e,t);if(r())return;let a=o.transform(s),l=Array.isArray(a)?a:[],c=o.limit!=null?l.slice(0,o.limit):l;if(r())return;this.commit(c)}catch(s){if(t.aborted||Yi(s)||(this.logOnce(s),r()))return;this.clear(i)}}owns(e){return this.isEnabled()&&this.getConfig()===e}resync(){let e=this.forResponse(this.store.get().customFields);this.commit(e??[])}clear(e){e()&&this.commit([])}commit(e){e.length===0&&this.store.get().products.length===0||this.store.set({products:e})}logOnce(e){this.hasLoggedError||(this.hasLoggedError=!0,console.warn("[AIAutocomplete] products.fetch/transform failed \u2014 the product strip is hidden. Later failures on this instance are not logged.",e))}};function Yi(n){return n instanceof Error&&n.name==="AbortError"}var _e="(max-width: 768px)";var ji="var(--aia-option-row-height, 37px)",zi="var(--aia-grid-scroll-top, 0px) + var(--aia-grid-scroll-bottom, 0px)";function In(n,e){return e?gt(1,Math.min(n,5)):gt(1,Math.min(n,4))}function gt(n,e){return{cols:n,rows:e,maxHeight:`calc(${e} * ${ji} + ${zi})`}}function bt(n,e){return!e&&n>=5}function yt(n,e,t,i){if(!(!e&&n>=5&&Xi(t,i))){let s=In(n,e);return{...s,template:ht(s.cols),scrollHintIndices:!e&&n>s.rows?[s.rows-1]:[]}}let r=6;return{...gt(2,3),template:ht(2),scrollHintIndices:n>r?[r-2,r-1]:[]}}function Xi(n,e){return!n||n.length===0||e==null||e<=0||n.some(i=>i<=0)?!1:Math.ceil(Math.max(...n))*2<=e}function St(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 i=Array.from(t.children).map(s=>s.offsetWidth);t.remove();let o=getComputedStyle(n),r=n.clientWidth-(Number.parseFloat(o.paddingLeft)||0)-(Number.parseFloat(o.paddingRight)||0)-(Number.parseFloat(o.columnGap)||0);return{rowWidths:i,gridWidth:r}}function ht(n){return Array.from({length:n},()=>"minmax(0,1fr)").join(" ")}function xt(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(_e).matches}function Rn(n,e){let t=e.dropdownTrigger??"auto",i=e.closeDropdownOnBlur??!0,s=n.filteredOptionsLength>0||n.activePillHasNoOptions||n.hasProducts;if(n.inEditMode){let a=i?n.isFocused:!0;return s&&a}if(t==="auto"){let a=i?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 le(n){if(n.editingIdentified){let{type:t,anchor:i}=n.editingIdentified;return`identified:${t}@${i}`}return n.editingParam!=null&&n.editingAnchor!=null?`edit:${n.editingParam?.id}`:`pill:${n.actionableSuggestions[0]?.type??""}`}function Dn(n){if(!n)return Xe();let[e,t]=n.split("-").map(Number);return{year:e,month:t-1}}function Ji(n){let e=fe(n);return e?Qt(e):Xe()}function Ln(n,e){let t=fn(n.text,n.completedParams,n.identifiedParams),i=n.suggestions.filter(w=>w.type!=="placeholder"),o=i[0],r=n.suggestions.filter(w=>w.type==="placeholder").map(w=>w.text).join(" "),s=F(n.text,Math.min(n.filterBase,n.text.length),r),l=s===0&&ve(n.text,n.completedParams.length,r)?"":q(n.text,s,n.filterInProgress),c=o?.options??[],d=n.editingParam!=null&&n.editingAnchor!=null,u,p,g,b;if(d&&n.editingParam&&n.editingAnchor!=null){let w=n.editingParam.id,_=n.completedParams.some(Si=>Si.id===w),te=n.caretOffset??n.editingAnchor,Wt=_?"":n.text.slice(n.editingAnchor,te);p=Wt.trim(),g=n.editingParam.options,b=n.editingParam.suggestionType,u=U(n.editingParam.options,Wt)}else p=l.trim(),g=c,b=o?.type,u=U(c,l);let y=n.optionSearch,S=y!=null&&b!=null&&y.type===b;S&&y.status==="done"&&y.query===p&&(u=g);let f=S&&y.status==="loading",m=e.showNonTappableOptions===!1;m&&(u=u.filter(w=>w.is_tappable));let h=n.editingIdentified,x=d?n.editingParam&&{type:n.editingParam.suggestionType,options:n.editingParam.options}:o,v=h?h.format:G(x),E=d&&P(v)?ie(n.editingParam):null;E&&(v="date-range");let A=null,L=null;if(P(v)){let w=le({...n,actionableSuggestions:i}),_=n.dateViewMonth;A=_&&_.key===w?{year:_.year,month:_.month}:h?Dn(h.iso):E?Dn(E.start):Ji(n.editingParam?.text),u=Ze(A);let te=n.pendingRangeStart;v==="date-range"&&te&&te.key===w&&(L=te.iso)}let T=w=>m?w.is_tappable:!0,I;if(d){let w=n.editingParam?.options??[];I=n.editingParam!=null&&w.filter(T).length===0}else I=o!=null&&c.filter(T).length===0;let C=Rn({inEditMode:d||h!=null,filteredOptionsLength:u.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading||f,pillTapped:n.pillTapped,activePillHasNoOptions:I,hasProducts:n.products.length>0},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),Qe=C&&n.activeDropdownIndex>=0&&!!u[n.activeDropdownIndex]?.is_tappable;return{segments:t,actionableSuggestions:i,filteredOptions:u,activeFormatType:v,dateView:A,dateRangeStart:L,placeholderText:r,optionQuery:p,isSearchingOptions:f,isDropdownOpen:C,isActivePillSelected:Qe}}function ke(n){return n.mode==="fresh"?Zi(n):eo(n)}function Zi(n){let{text:e,completedParams:t,suggestions:i,filterBase:o,filterInProgress:r}=n,a=i.filter(x=>x.type!=="placeholder")[0];if(!a?.options)return null;let l=i.filter(x=>x.type==="placeholder").map(x=>x.text).join(" "),c=F(e,o,l),d=q(e,c,r),u=X(a.options,d);if(!u)return null;let p=u.text.toLowerCase(),g=e.toLowerCase().lastIndexOf(p),b=g>=0?g:Math.max(0,e.length-u.text.length),y=b+u.text.length,S=e.slice(b,y),m=y<e.length&&e[y]===" "?y+1:y,h={id:crypto.randomUUID(),placeholder:"",type:a.type,text:S,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,h],suggestions:i.filter(x=>x!==a),filterBase:m,newParamId:h.id,caretOffset:m,activeDropdownIndex:-1},caretPos:m}}function eo(n){let{text:e,completedParams:t,editingParam:i,editingAnchor:o,editingTail:r}=n;if(t.some(h=>h.id===i.id))return null;let s=e.slice(o,r),a=X(i.options,s);if(!a)return null;let l=a.text.toLowerCase(),c=s.toLowerCase().lastIndexOf(l),d=o+Math.max(0,c),u=d+a.text.length,p=e.slice(d,u),g=u<e.length&&e[u]===" "?u+1:u,b=e.length,y={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:p,value:a.value,kind:a.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:a.metadata,icon:a.icon,icon_svg:a.icon_svg,image_url:a.image_url},S=t.length,f=0;for(let h=0;h<t.length;h++){let x=e.indexOf(t[h].text,f);if(x!==-1){if(x>=g){S=h;break}f=x+t[h].text.length}}let m=[...t];return m.splice(S,0,y),{patch:{text:e,completedParams:m,newParamId:y.id,filterBase:b,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:b,activeDropdownIndex:-1},caretPos:b}}function Ne(n,e,t){let i=n.slice(0,e),o=n.slice(t),r=(i===""||i.endsWith(" "))&&o.startsWith(" ");return r&&(o=o.slice(1)),{text:i+o,removed:t-e+(r?1:0)}}var Fe=class{constructor(e){this.deps=e}start(e){let t=this.deps.store.get();if(t.editingParam?.id===e)return;let i=t.completedParams.find(s=>s.id===e);if(!i)return;let o=0,r=-1;for(let s of t.completedParams){let a=t.text.indexOf(s.text,o);if(a!==-1){if(s.id===e){r=a;break}o=a+s.text.length}}r<0||this.deps.store.set({editingParam:i,editingAnchor:r,editingTail:r+i.text.length,caretOffset:r+i.text.length,activeDropdownIndex:-1,editingIdentified:null})}exit(){this.deps.store.get().editingParam&&this.deps.store.set({editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1})}replaceRange(e){let t=this.deps.store.get(),i=t.editingParam,o=t.editingAnchor,r=t.editingTail;if(!i||o==null||r==null||!t.completedParams.some(l=>l.id===i.id))return!1;let{text:s}=e===""?Ne(t.text,o,r):{text:t.text.slice(0,o)+e+t.text.slice(r)},a=o+e.length;return this.deps.store.set(l=>({text:s,completedParams:l.completedParams.filter(c=>c.id!==i.id),editingTail:a,caretOffset:a,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(a),this.promoteIfExact(),!0}caretAfterInput(e){let t=this.deps.store.get(),i={caretOffset:e};t.editingParam&&t.editingAnchor!=null&&e!=null&&(e<t.editingAnchor?(i.editingParam=null,i.editingAnchor=null,i.editingTail=null,i.activeDropdownIndex=-1):t.editingTail!=null&&(i.editingTail=Math.max(t.editingTail,e))),this.deps.store.set(i),this.promoteIfExact()}caretMove(e){let t=this.deps.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null&&e!=null&&(e<t.editingAnchor||e>t.editingTail)){this.deps.store.set({caretOffset:e,editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1});return}this.deps.store.set({caretOffset:e})}selectOption(e){let t=this.deps.store.get(),i=t.editingParam,o=t.editingAnchor,r=t.editingTail;if(!i||o==null||r==null)return;this.deps.fireTelemetry("option",{raw_query:R(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:i.options.filter(f=>f.text!==e.text).map(f=>f.text)});let s=t.text.slice(0,o),a=t.text.slice(r),l=o===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,d=a.length===0||a[0]!==" "?`${l} `:l,u=s+d+a,p=u.length,g={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:l,value:e.value,kind:e.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url},b=t.completedParams.findIndex(f=>f.id===i.id),y=t.completedParams.filter(f=>f.id!==i.id),S=b>=0?Math.min(b,y.length):y.length;y.splice(S,0,g),this.deps.store.set({text:u,completedParams:y,newParamId:g.id,filterBase:p,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:p,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.deps.startSelectionAnimationTimer(),this.deps.scheduleSetCursor(p),this.deps.fetchNow()}promoteIfExact(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let t=ke({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 to=33,no=70,io=120,oo=50,Z="data-aia-placeholder-leaving",ee=new WeakMap;function He(n){n.timer!==null&&(clearTimeout(n.timer),n.timer=null)}function ro(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function _n(n,e,t){e.shown=t,n.dataset.placeholder=e.target.slice(0,t)}function kn(n,e){if(e.timer=null,!n.isConnected||e.shown>=e.target.length||(_n(n,e,e.shown+1),e.shown>=e.target.length))return;let t=e.target[e.shown-1],i=t===" "||t==="-"?70:0;e.timer=setTimeout(()=>kn(n,e),33+i)}function Mn(n,e){_n(n,e,0),e.timer=setTimeout(()=>kn(n,e),33)}function Nn(n,e){let t=ee.get(n);if(e===""){t&&(He(t),ee.delete(n)),n.removeAttribute(Z),delete n.dataset.placeholder;return}if(t?.target===e)return;if(ro(n)){t&&He(t),n.removeAttribute(Z),ee.set(n,{target:e,shown:e.length,timer:null}),n.dataset.placeholder=e;return}let i={target:e,shown:0,timer:null},o=t&&t.shown>0?t:null;if(t&&He(t),ee.set(n,i),o){n.setAttribute(Z,""),i.timer=setTimeout(()=>{i.timer=null,n.removeAttribute(Z),n.isConnected&&Mn(n,i)},170);return}n.removeAttribute(Z),Mn(n,i)}function Fn(n){let e=ee.get(n);e&&(He(e),ee.delete(n))}var Hn="https://ai-autocomplete.com";function vt(n=Hn){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 wt(n,e){return n?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}var so={selectedIso:null,selectedRange:null,rangeStart:null};function de(n){if(!P(n.activeFormatType))return so;let e=n.editingIdentified;if(e){let{iso:i,isoEnd:o}=e;return{selectedIso:o?null:i,selectedRange:i&&o?ne(i,o):null,rangeStart:n.dateRangeStart}}let t=ie(n.editingParam);return{selectedIso:t?null:et(n.editingParam?.text),selectedRange:t,rangeStart:n.dateRangeStart}}function Pt(n){return n.pendingStart?ne(n.pendingStart,n.highlightedIso??n.pendingStart):n.selected}function Et(n,e){if(n==null)return{selected:!1,inRange:!1};let{selectedIso:t,range:i}=e,o=n===t||i!=null&&(n===i.start||n===i.end),r=i!=null&&n>i.start&&n<i.end;return{selected:o,inRange:r}}var Bn="data-aia-key";function H(n,e,t){let i=new Map;for(let s of Array.from(n.children)){let a=s.getAttribute(Bn);a!=null&&i.set(a,s)}let o=new Set,r=[];for(let s=0;s<e.length;s++){let a=e[s],l=t.keyOf(a,s);o.add(l);let c=i.get(l);c||(c=t.create(a,s),c.setAttribute(Bn,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 i)o.has(s)||a.remove();return r}function $n(n,e,t,i,o,r,s){let a=n.querySelector(".magicx-aia-datepicker");if(!o||e.length===0){a?.remove();return}a||(a=co(),n.appendChild(a));let l=a.querySelector(".magicx-aia-datepicker-month");l&&(l.textContent=ze(o));let c=a.querySelector("[data-aia-date-prev]"),d=a.querySelector("[data-aia-date-next]");c&&(c.onclick=()=>s.onPreviousMonth()),d&&(d.onclick=()=>s.onNextMonth());let u=a.querySelector(".magicx-aia-datepicker-grid");u&&ao(u,e,t,i,r,s)}function ao(n,e,t,i,o,r){let s=M(new Date),a=Pt({pendingStart:o.rangeStart,highlightedIso:N(e[t]),selected:o.selectedRange});H(n,e,{keyOf:(l,c)=>N(l)??`pad-${c}`,create:l=>lo(l),update:(l,c,d)=>{let u=N(c),p=Et(u,{selectedIso:o.selectedIso,range:a}),g=d===t&&c.is_tappable;l.id=`${i}-option-${d}`,l.dataset.aiaIndex=String(d),l.setAttribute("aria-selected",String(g)),l.classList.toggle("magicx-aia-date-cell--past",u!=null&&u<s),l.classList.toggle("magicx-aia-date-cell--highlighted",g),l.classList.toggle("magicx-aia-date-cell--today",u!=null&&u===s),l.classList.toggle("magicx-aia-date-cell--selected",p.selected),l.classList.toggle("magicx-aia-date-cell--in-range",p.inRange),c.is_tappable?(l.onclick=()=>{l.classList.add("magicx-aia-date-cell--pressed"),r.onSelect(c),setTimeout(()=>l.classList.remove("magicx-aia-date-cell--pressed"),170)},l.onmouseenter=()=>{let b=Number.parseInt(l.dataset.aiaIndex??"-1",10);b>=0&&r.onHighlight(b)}):(l.onclick=null,l.onmouseenter=null)}})}function lo(n){let e=document.createElement("div");e.setAttribute("role","option"),e.setAttribute("data-aia-option",""),e.setAttribute("data-aia-date-cell","");let t=tt(n);if(t==null)return e.className="magicx-aia-date-cell magicx-aia-date-cell--blank",e.setAttribute("aria-hidden","true"),e.tabIndex=-1,e;e.className="magicx-aia-date-cell magicx-aia-date-cell--day",e.tabIndex=0,e.setAttribute("aria-label",n.text);let i=document.createElement("span");return i.className="magicx-aia-date-cell-number",i.textContent=String(t),e.appendChild(i),e}function co(){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(Wn("prev","Previous month","\u2039"),t,Wn("next","Next month","\u203A"));let i=document.createElement("div");i.className="magicx-aia-datepicker-weekdays",i.setAttribute("aria-hidden","true");for(let r of me){let s=document.createElement("span");s.className="magicx-aia-datepicker-weekday",s.textContent=r,i.appendChild(s)}let o=document.createElement("div");return o.className="magicx-aia-datepicker-grid",o.setAttribute("data-aia-date-grid",""),n.append(e,i,o),n}function Wn(n,e,t){let i=document.createElement("button");return i.type="button",i.tabIndex=-1,i.className="magicx-aia-datepicker-nav",i.setAttribute(`data-aia-date-${n}`,""),i.setAttribute("aria-label",e),i.textContent=t,i.addEventListener("mousedown",o=>o.preventDefault()),i}var Gn=[125,69];function qn(n,e){return e?1:n===0?.7:n===1?.4:.2}function Be(n,e,t,i,o=!1,r=!1,s=!1){let a=n.querySelector(".magicx-aia-pill-list");if(a||(a=document.createElement("span"),a.className="magicx-aia-pill-list",n.appendChild(a)),r&&e.length===0){a.setAttribute("data-aia-pill-list-loading",""),a.innerHTML="";for(let l=0;l<Gn.length;l++){let c=Gn[l],d=document.createElement("span");d.setAttribute("data-aia-pill-skeleton",""),d.className=`magicx-aia-pill magicx-aia-pill--skeleton${o?" magicx-aia-pill--rounded":""}`,d.style.width=`${c}px`,d.style.opacity=String(qn(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();H(a,e,{keyOf:l=>`${l.type}-${l.text}`,create:l=>{let c=document.createElement("button");return c.type="button",c.tabIndex=-1,c.setAttribute("data-aia-pill",""),c.setAttribute("contenteditable","false"),c.textContent=l.text,c.addEventListener("mousedown",d=>d.preventDefault()),c},update:(l,c,d)=>{let u=l,p=s&&d===t&&!r,g=["magicx-aia-pill"];o&&g.push("magicx-aia-pill--rounded"),r&&g.push("magicx-aia-pill--skeleton"),u.className=g.join(" "),u.style.width="",u.style.opacity=String(qn(d,p)),r?(u.setAttribute("data-aia-loading",""),u.disabled=!0,u.onclick=null):(u.removeAttribute("data-aia-loading"),u.disabled=!1,u.onclick=()=>i(d))}})}function Tt(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var uo=32;function Un(n,e){if(e.ctrlKey)return null;let t=e.deltaY||0,i=e.deltaX||0;if(!t||Math.abs(i)>=Math.abs(t))return null;let o=n.scrollWidth-n.clientWidth;if(o<=1)return null;let r=n.scrollLeft,s=t;return e.deltaMode===1?s*=32:e.deltaMode===2&&(s*=n.clientWidth),Math.max(0,Math.min(o,r+s))}function Ct(n){let e=t=>{let i=Un(n,t);i!==null&&(t.preventDefault(),n.scrollLeft=i)};return n.addEventListener("wheel",e,{passive:!1}),()=>n.removeEventListener("wheel",e)}var po="Products";function Vn(n,e,t,i,o,r="row"){let s=n.querySelector(".magicx-aia-products");if(e.length===0){s?.remove();return}if(!s){s=document.createElement("section"),s.className="magicx-aia-products",s.setAttribute("data-aia-products",""),s.setAttribute("role","group"),s.setAttribute("aria-labelledby",`${t}-products-label`);let l=document.createElement("div");l.className="magicx-aia-products-label",l.id=`${t}-products-label`,l.setAttribute("data-aia-products-label",""),l.textContent=po;let c=document.createElement("div");c.className="magicx-aia-products-row",c.setAttribute("data-aia-products-row",""),Ct(c),s.append(l,c),n.appendChild(s)}s.setAttribute("data-aia-products-layout",r);let a=s.querySelector(".magicx-aia-products-row");a&&H(a,e,{keyOf:l=>mo(l),create:l=>fo(l,i,o),update:(l,c,d)=>{l.id=`${t}-product-${d}`,l.dataset.aiaIndex=String(d)}})}function Ot(n,e){let t=n.querySelectorAll("[data-aia-product]");for(let i of t)i.tabIndex=e?0:-1}function mo(n){return[n.id,n.title,n.url,n.imageUrl,n.price,n.vendor].map(e=>e??"").join("\0")}function fo(n,e,t){let i=document.createElement("a");i.className="magicx-aia-product",i.setAttribute("data-aia-product",""),i.setAttribute("role","option"),i.setAttribute("aria-selected","false"),n.url&&(i.href=n.url),i.tabIndex=0;let o=document.createElement("span");if(o.className="magicx-aia-product-media",n.imageUrl){let a=document.createElement("img");a.className="magicx-aia-product-image",a.src=n.imageUrl,a.alt="",a.loading="lazy",a.decoding="async",o.appendChild(a)}else o.setAttribute("data-aia-product-placeholder","");i.appendChild(o);let r=document.createElement("span");if(r.className="magicx-aia-product-body",n.vendor){let a=document.createElement("span");a.className="magicx-aia-product-vendor",a.textContent=n.vendor,r.appendChild(a)}let s=document.createElement("span");if(s.className="magicx-aia-product-title",s.textContent=n.title,r.appendChild(s),n.price){let a=document.createElement("span");a.className="magicx-aia-product-price",a.textContent=n.price,r.appendChild(a)}return i.appendChild(r),i.addEventListener("click",a=>{a.metaKey||a.ctrlKey||a.shiftKey||a.altKey||a.button!==0||(a.preventDefault(),e(n))}),i.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),e(n))}),i.addEventListener("focus",()=>t(!0)),i.addEventListener("blur",a=>{a.relatedTarget?.closest("[data-aia-dropdown]")||t(!1)}),i}var go=80,ho=150,bo=280,yo=16,At="--aia-option-enter-delay";function It(n,e,t,i="below"){let o=Math.max(1,Math.floor(e)),r=Math.floor(Math.max(0,n)/o);if(i!=="above")return r*80;let s=Math.max(1,Math.ceil(Math.max(0,t)/o));return Math.max(0,s-1-r)*80}function Rt(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 B(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 ce(n){return n===void 0||!Number.isInteger(n)||n<0?null:n.toLocaleString()}var Kn={one:"item",other:"items"};function So(n,e=Kn){let t=ce(n);if(t===null)return null;let i=typeof e=="string"?e:n===1?e.one:e.other;return i===""?t:`${t} ${i}`}function xo(n){return B(n.image_url)!==null}var Qn="http://www.w3.org/2000/svg",vo=new Set(["svg","g","path","circle","ellipse","line","polyline","polygon","rect"]);function wo(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 Po=["fill","stroke","stroke-width","stroke-linecap","stroke-linejoin","fill-rule","clip-rule","opacity","fill-opacity","stroke-opacity"],Eo=/^[a-zA-Z0-9#.,%\s()-]+$/;function To(n){let e=[];for(let t of Po){let i=n.getAttribute(t);i===null||!Eo.test(i)||/url\s*\(/i.test(i)||e.push(`${t}: ${i.trim()}`)}e.length>0&&n.setAttribute("style",e.join("; "))}function Yn(n){for(let e of Array.from(n.attributes))wo(e.name,e.value)&&n.removeAttribute(e.name);To(n);for(let e of Array.from(n.childNodes))if(e.nodeType===Node.ELEMENT_NODE){let t=e;!vo.has(t.localName)||t.namespaceURI!==Qn?t.remove():Yn(t)}else e.remove()}function ue(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!==Qn||e.getElementsByTagName("parsererror").length>0?null:(Yn(t),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false"),new XMLSerializer().serializeToString(t))}function Dt(n){return n.text}function Co(n,e,t){let i=xt(),o=!t&&bt(e,i)?St(n):null,r=yt(e,i,o?.rowWidths??null,o?.gridWidth??null);return n.style.gridTemplateColumns=r.template,n.style.setProperty("--aia-grid-max-height",r.maxHeight),n.querySelectorAll("[data-aia-option]").forEach((s,a)=>{s.classList.toggle("magicx-aia-option--scroll-hint",!t&&r.scrollHintIndices.includes(a))}),r.cols}function jn(n,e,t,i,o,r,s,a="",l="below",c=!0,d=!0,u=!0){let p=n.querySelector(".aia-grid");if(e.length===0){p?.remove();return}p||(p=document.createElement("div"),p.className="aia-grid magicx-aia-grid",p.setAttribute("data-scroll",""),p.style.setProperty("--aia-grid-min","250px"),p.style.setProperty("--aia-grid-max","1fr"),p.style.setProperty("--aia-grid-gap","0"),n.appendChild(p));let g=p.dataset.aiaGroup!==a;p.dataset.aiaGroup=a,Oo(p,e,t,i,o,r,s,{showIcons:c,showImages:d,showCounts:u});let b=Co(p,e.length,s);Ao(p,e.length,b,s,l),g&&(p.scrollTop=0)}function Oo(n,e,t,i,o,r,s,a){let l=s?"1":"0",c=n.dataset.aiaGroup??"",{showIcons:d,showImages:u,showCounts:p}=a,g=d?S=>S.icon??S.icon_svg??"":()=>"",b=u?S=>B(S.image_url)??"":()=>"",y=p?S=>ce(S.item_count)??"":()=>"";H(n,e,{keyOf:S=>`${S.text}\0${g(S)}\0${b(S)}\0${y(S)}\0${l}\0${c}`,create:(S,f)=>{let m=Io(S,s,a);return s||(m.dataset.aiaEntering=""),m},update:(S,f,m)=>{let h=m===t&&!s;S.id=`${r}-option-${m}`,S.dataset.aiaIndex=String(m),S.setAttribute("aria-selected",String(h)),S.classList.toggle("magicx-aia-option--highlighted",h),!s&&f.is_tappable?(S.onclick=()=>{S.classList.add("magicx-aia-option--pressed"),i(f),setTimeout(()=>S.classList.remove("magicx-aia-option--pressed"),170)},S.onmouseenter=()=>{let x=Number.parseInt(S.dataset.aiaIndex??"-1",10);x>=0&&o(x)}):(S.onclick=null,S.onmouseenter=null)}})}function Ao(n,e,t,i,o){for(let r of n.querySelectorAll("[data-aia-entering]")){if(!i){let s=Number.parseInt(r.dataset.aiaIndex??"-1",10);s>=0&&r.style.setProperty(At,`${It(s,t,e,o)}ms`)}delete r.dataset.aiaEntering}}function Io(n,e,{showIcons:t,showImages:i,showCounts:o}){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=i?B(n.image_url):null;if(l){let p=document.createElement("span");p.className="magicx-aia-option-image",p.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,p.appendChild(g),a.appendChild(p),r.dataset.aiaImage=""}let c=!l&&t&&n.icon_svg?ue(n.icon_svg):null;if(c){let p=document.createElement("span");p.className="magicx-aia-option-icon",p.setAttribute("aria-hidden","true"),p.innerHTML=c,a.appendChild(p),n.icon&&(r.dataset.aiaIcon=n.icon)}let d=document.createElement("span");if(d.className="magicx-aia-option-text",d.textContent=Dt(n),a.appendChild(d),n.tag){let p=document.createElement("span");p.className="magicx-aia-option-tag",p.textContent=n.tag,a.appendChild(p)}let u=o?ce(n.item_count):null;if(u!==null){let p=document.createElement("span");p.className="magicx-aia-option-count",p.textContent=u,a.appendChild(p),r.dataset.aiaItemCount=String(n.item_count)}return r.appendChild(a),r}var zn="magicx-aia-scroll-arrow",Xn="data-aia-scroll-arrow",We="data-aia-visible",Ro=1e3,Jn=160,Zn="--aia-scroll-arrow-bottom",ei="Scroll down for more options",Do="[data-aia-products-label]",Lo=4,Mo=8,_o=240;function ko(n,e,t,i){let o=n.scrollTop,r=t?.requestAnimationFrame,s=n.ownerDocument?.visibilityState==="hidden";if(!r||s||ni(n)){n.scrollTop=o+e,i();return}let a=t.performance?.now?.()??Date.now(),l=()=>t.performance?.now?.()??Date.now(),c=()=>{let d=Math.min(1,(l()-a)/_o),u=1-(1-d)*(1-d);n.scrollTop=o+e*u,d<1?r.call(t,c):i()};r.call(t,c)}function No(n=document){let e="http://www.w3.org/2000/svg",t=n.createElementNS(e,"svg");t.setAttribute("viewBox","0 0 16 16"),t.setAttribute("width","18"),t.setAttribute("height","18"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.75"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let i=n.createElementNS(e,"path");return i.setAttribute("d","M4 6.5 8 10.5l4-4"),t.appendChild(i),t}function ti(n=document){let e=n.createElement("button");return e.type="button",e.tabIndex=-1,e.className=zn,e.setAttribute(Xn,""),e.setAttribute("aria-label",ei),e.setAttribute("aria-hidden","true"),e.appendChild(No(n)),e}function Fo(n){let e=n.style.gridTemplateColumns.trim();return e?Math.max(1,e.split(/\s+/).length):1}function ni(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function Lt({dropdown:n,grid:e,button:t}){let i=e.ownerDocument?.defaultView??(typeof window<"u"?window:null),o=!1,r=null,s=null,a=null,l=f=>{f?(t.setAttribute(We,""),t.setAttribute("aria-hidden","false")):(t.removeAttribute(We),t.setAttribute("aria-hidden","true"))},c=f=>{let m=0,h=f;for(;h&&h!==n;)m+=h.offsetTop,h=h.offsetParent instanceof HTMLElement?h.offsetParent:null;return m},d=()=>{let f=n.querySelector(Do),m;if(f){let h=c(f)+f.offsetHeight/2;m=n.clientHeight-h-t.offsetHeight/2}else{let h=c(e),x=i&&Number.parseFloat(i.getComputedStyle(e).paddingBottom)||0;m=n.clientHeight-(h+e.offsetHeight)+(x>0?0:Mo)}t.style.setProperty(Zn,`${Math.max(0,Math.round(m))}px`)},u=()=>{if(o||s!==null||a!==null)return;let f=e.querySelector("[data-aia-option][data-aia-loading]")!==null,m=e.scrollHeight-e.clientHeight-e.scrollTop;l(!f&&m>Lo)},p=()=>{if(o)return;d();let f=e.getAttribute("data-aia-group")??"";if(f!==r){r=f,l(!1),s!==null&&clearTimeout(s);let m=e.querySelectorAll("[data-aia-option]").length,h=ni(e)?0:Rt(m,Fo(e));s=setTimeout(()=>{s=null,u()},h);return}u()},g=()=>{o||s!==null||(l(!1),a!==null&&clearTimeout(a),a=setTimeout(()=>{a=null,u()},Jn))};e.addEventListener("scroll",g,{passive:!0});let b=f=>f.preventDefault(),y=()=>{let f=i?(Number.parseFloat(i.getComputedStyle(e).paddingTop)||0)+(Number.parseFloat(i.getComputedStyle(e).paddingBottom)||0):0,m=Math.max(1,e.clientHeight-f);ko(e,m,i,g)};t.addEventListener("mousedown",b),t.addEventListener("click",y);let S=null;return i&&typeof i.ResizeObserver=="function"&&(S=new i.ResizeObserver(()=>{d(),u()}),S.observe(e)),p(),{update:p,destroy(){o||(o=!0,s!==null&&clearTimeout(s),s=null,a!==null&&clearTimeout(a),a=null,e.removeEventListener("scroll",g),t.removeEventListener("mousedown",b),t.removeEventListener("click",y),S?.disconnect(),t.removeAttribute(We),t.setAttribute("aria-hidden","true"))}}}var Ho=[159,119,164];function Ge(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 $e=new WeakMap;function Bo(n,e){let t=$e.get(n);if(t||(t={button:ti(n.ownerDocument),grid:null,controller:null},n.appendChild(t.button),$e.set(n,t)),t.grid!==e&&(t.controller?.destroy(),t.controller=null,t.grid=e,e)){t.controller=Lt({dropdown:n,grid:e,button:t.button});return}t.controller?.update()}function Mt(n){let e=$e.get(n);e&&(e.controller?.destroy(),$e.delete(n))}function qe(n,e){let{filteredOptions:t,activeIndex:i,isOpen:o,isLoading:r,pills:s,showPills:a,isActivePillSelected:l,onSelect:c,onHighlight:d,onPillClick:u,onSkip:p}=e,g=s.length>0,b=a&&g,y=t.length>0,S=e.products.length>0,f=o&&(y||b||r||S);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){Ot(n,!1);return}S?n.setAttribute("data-aia-has-products",""):n.removeAttribute("data-aia-has-products");let m=n.querySelector(".aia-stack");m||(m=document.createElement("div"),m.className="aia-stack",m.style.setProperty("--aia-stack-space","8px"),n.appendChild(m));let h=e.showSkipButton&&g&&!e.isInputEmpty,x=b||r&&a||h,v=m.querySelector(".magicx-aia-pill-bar");if(x){v||(v=document.createElement("div"),v.className="magicx-aia-pill-bar aia-cluster",v.setAttribute("data-nowrap",""),v.setAttribute("data-aia-pillbar",""),m.insertBefore(v,m.firstChild));let w=v.querySelector(".magicx-aia-pill-scroll");w||(w=document.createElement("span"),w.className="magicx-aia-pill-scroll",w.setAttribute("data-aia-pill-scroll",""),v.insertBefore(w,v.firstChild)),Be(w,a?s:[],0,u,!0,r&&a,l),$o(v,h,r||e.skipDisabled,s[0],p)}else v&&v.remove();let E=e.suggestions[0],A=E?`${E.type} ${E.text}`:"",L=P(e.formatType),T=L&&!r;jn(m,L?[]:t,i,c,d,e.listboxId,r,A,e.optionsPosition??"below",e.showOptionIcons??!0,e.showOptionImages??!0,e.showOptionCounts??!0),Bo(n,m.querySelector(".aia-grid")),$n(m,T?t:[],i,e.listboxId,T?e.dateView:null,{selectedIso:e.selectedDateIso,selectedRange:e.selectedDateRange,rangeStart:e.dateRangeStart},{onSelect:c,onHighlight:d,onPreviousMonth:e.onPreviousMonth,onNextMonth:e.onNextMonth});let I=m.querySelector(".magicx-aia-skeleton-bars");if(r&&(!y||L)){if(!I){I=document.createElement("div"),I.className="magicx-aia-skeleton-bars",I.setAttribute("data-aia-skeleton-bars","");for(let w of Ho){let _=document.createElement("span");_.className="magicx-aia-skeleton-bar",_.style.width=`${w}px`,I.appendChild(_)}m.appendChild(I)}}else I&&I.remove();Vn(m,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange,e.productsLayout??"row"),Ot(n,!0);let C=m.querySelector(".magicx-aia-footer")??qo(),Qe=i>=0&&!!t[i]?.is_tappable;Go(C,wt(Qe,e.isInputEmpty)),C.isConnected||m.appendChild(C),Wo(m,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-datepicker",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"])}function Wo(n,e){let t=e.map(i=>n.querySelector(`:scope > ${i}`)).filter(i=>i!==null);for(let i=0;i<t.length;i++)n.children[i]!==t[i]&&n.insertBefore(t[i],n.children[i]??null)}function $o(n,e,t,i,o){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.addEventListener("mousedown",s=>s.preventDefault()),n.appendChild(r)),r.setAttribute("aria-label",i?`Skip ${i.text}`:"Skip"),r.disabled=t,r.onclick=t?null:()=>o()}function Go(n,{key:e,hint:t}){let i=n.querySelector(".magicx-aia-footer-key"),o=n.querySelector(".magicx-aia-footer-hint");!i||!o||(i.textContent!==e&&(i.textContent=e),o.textContent!==t&&(o.textContent=t))}function qo(){let n=document.createElement("footer");n.className="magicx-aia-footer",n.setAttribute("data-aia-footer","");let e=document.createElement("div");e.className="aia-cluster magicx-aia-footer-row",e.setAttribute("data-align","center"),e.setAttribute("data-justify","between"),e.setAttribute("data-nowrap","");let t=document.createElement("div");t.className="aia-cluster magicx-aia-footer-hint-group",t.setAttribute("data-align","center"),t.style.setProperty("--aia-cluster-gap","5px");let i=document.createElement("kbd");i.className="magicx-aia-footer-key",i.textContent="tab";let o=document.createElement("span");o.className="magicx-aia-footer-hint",o.textContent="to select",t.append(i,o);let r=document.createElement("a");r.className="aia-cluster magicx-aia-footer-brand-link",r.setAttribute("data-align","center"),r.href=vt(),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 ii(n,e){let t=Ge(e.listboxId);return n.appendChild(t),{dropdown:t}}function _t(n,e,t){let i=de(e);qe(n.dropdown,{suggestions:e.editingIdentified?[{type:e.editingIdentified.type,text:W(e.editingIdentified.type),required:!0,options:e.filteredOptions}]:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation||e.isSearchingOptions,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,showSkipButton:t.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:t.showOptionIcons??!0,showOptionImages:t.showOptionImages??!0,showOptionCounts:t.showOptionCounts??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,productsLayout:t.productsLayout??"row",formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:i.selectedIso,selectedDateRange:i.selectedRange,dateRangeStart:i.rangeStart,optionsPosition:t.optionsPosition??"below",onSelect:t.selectOption,onHighlight:o=>t.store.set({activeDropdownIndex:o}),onPillClick:t.setActivePill,onSkip:t.skipActivePill,onPreviousMonth:t.showPreviousMonth,onNextMonth:t.showNextMonth,onProductSelect:t.selectProduct,onProductFocusChange:o=>t.store.set({isFocused:o})})}var Uo=6,Vo=.3;function oi(n){return n<=0?"0px":`${(-Math.min(Vo,2*Uo/n)).toFixed(3)}px`}function kt(n){let{input:e,segments:t,newParamId:i,editingParamId:o,placeholderText:r,isFocused:s}=n,a=n.showChipIcons??!0,l=n.showChipImages??!0,c=t.length===0;e.dataset.aiaEmpty=c?"true":"false",Nn(e,c?r:"");let d=t.map(m=>m.type==="completed"?`${m.type}:${m.value}${a?m.param.icon??m.param.icon_svg??"":""}${l?B(m.param.image_url)??"":""}`:`${m.type}:${m.value}`).join("\0"),u=e.dataset.segKey??"",p=e.dataset.newParamId??"",g=e.dataset.editingParamId??"";if(d===u&&(i??"")===p&&(o??"")===g)return;let b=s?k(e):null;e.dataset.segKey=d,e.dataset.newParamId=i??"",e.dataset.editingParamId=o??"";let y=O(e),S=y.createDocumentFragment(),f=0;for(let m of t)if(f+=m.value.length,m.type==="completed"){let h=y.createElement("strong");h.dataset.seg="completed",h.dataset.paramId=m.param.id;let x=m.param.id===i,v=m.param.id===o,E=["magicx-aia-segment","magicx-aia-segment--completed"];x&&E.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),v&&E.push("magicx-aia-segment--editing"),h.className=E.join(" "),h.style.letterSpacing=oi(m.value.length);let A=l?B(m.param.image_url):null;if(A){let T=y.createElement("span");T.className="magicx-aia-segment-image",T.setAttribute("contenteditable","false"),T.setAttribute("aria-hidden","true"),T.style.setProperty("--aia-chip-image",`url("${A}")`),h.appendChild(T),h.dataset.aiaImage=""}let L=!A&&a&&m.param.icon_svg?ue(m.param.icon_svg):null;if(L){let T=y.createElement("span");T.className="magicx-aia-segment-icon",T.setAttribute("contenteditable","false"),T.setAttribute("aria-hidden","true"),T.innerHTML=L,h.appendChild(T),m.param.icon&&(h.dataset.aiaIcon=m.param.icon)}h.appendChild(y.createTextNode(m.value)),S.appendChild(h)}else if(m.type==="identified"){let h=y.createElement("strong");h.dataset.seg="identified",h.dataset.paramId=m.param.id;let x=["magicx-aia-segment","magicx-aia-segment--completed"];m.param.id===o&&x.push("magicx-aia-segment--editing"),h.className=x.join(" "),h.style.letterSpacing=oi(m.value.length),h.textContent=m.value,S.appendChild(h)}else S.appendChild(y.createTextNode(m.value));e.replaceChildren(S),e.dataset.aiaTextLength=String(f),b!=null?D(e,Math.max(0,Math.min(b,f))):s&&Tn(e)&&D(e,f)}var Ko='<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 ri(){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=Ko,n}function Qo(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function si(n,e){let t=e.firstElementChild;if(!t){e.removeAttribute("data-aia-pill-wrapped");return}let i=t.getBoundingClientRect(),o=n.getBoundingClientRect();i.top>=o.bottom-2?e.setAttribute("data-aia-pill-wrapped",""):e.removeAttribute("data-aia-pill-wrapped")}function ai(n,e){let{listboxId:t}=e,i=Ge(t);n.appendChild(i);let o=document.createElement("div");o.className="magicx-aia-input-wrapper",o.setAttribute("data-aia-input-wrapper",""),n.appendChild(o);let r=document.createElement("div");r.className="magicx-aia-editor",r.setAttribute("data-aia-editor",""),o.appendChild(r);let s=document.createElement("div");s.className="magicx-aia-input",s.setAttribute("data-aia-input",""),s.setAttribute("contenteditable",Qo()?"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=ri(),o.appendChild(l),c=l):e.submitButton!==null&&(c=e.submitButton,c.hasAttribute("data-aia-submit")||c.setAttribute("data-aia-submit",""),c.setAttribute("data-aia-submit-slot",""),o.appendChild(c));let d=new AbortController,{signal:u}=d,p=!1,g=0,b=()=>{let f=Ie(s),h=f.length>0&&f[0]!==f[0].toUpperCase()?f[0].toUpperCase()+f.slice(1):f;e.handleChange(h)},y=()=>{let f=K(s)?.node??null;if(!f||!s.contains(f))return null;let x=(f.nodeType===Node.ELEMENT_NODE?f:f.parentElement)?.closest("strong[data-param-id]")?.dataset.paramId??null;return x&&En(s,x)?null:x};if(o.addEventListener("click",f=>{f.target?.closest("[data-aia-pill]")||s.focus()},{signal:u}),s.addEventListener("input",()=>{p||(g=performance.now(),b(),e.handleCaretAfterInput(k(s)))},{signal:u}),O(s).addEventListener("selectionchange",()=>{let f=K(s);if(!f||!s.contains(f.node))return;let m=f.collapsed?y():null,h=e.store.get(),x=h.editingParam?.id??h.editingIdentified?.id??null;if(m&&m!==x){e.startEditingParam(m);return}performance.now()-g<50||e.handleCaretMove(k(s))},{signal:u}),s.addEventListener("compositionstart",()=>{p=!0},{signal:u}),s.addEventListener("compositionend",()=>{p=!1,b()},{signal:u}),s.addEventListener("beforeinput",f=>{let m=f,h=m.inputType;if(h==="insertParagraph"||h==="insertLineBreak"||h==="insertFromDrop"){f.preventDefault();return}if(h.startsWith("insert")||h.startsWith("delete")){let x=h.startsWith("delete")?"":m.data??"";e.replaceEditingRange(x)&&f.preventDefault()}},{signal:u}),s.addEventListener("paste",f=>{f.preventDefault();let m=(f.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!m)return;let h=O(s),x=Ee(s);if(!x||!s.contains(x.startContainer))return;x.deleteContents();let v=h.createTextNode(m);x.insertNode(v),x.setStartAfter(v),ae(s,x.startContainer,x.startOffset),b()},{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 m=e.store.get();if(!(!!m.text||m.completedParams.length>0)||!e.onSubmit)return;f.stopPropagation(),e.onSubmit(Q(m.text,m.completedParams,m.skippedParams,{identifiedParams:m.identifiedParams,isReady:m.isReady,customFields:m.customFields}))&&e.afterSubmit?.()},{signal:u}),e.autoFocus!==!1){s.focus();let f=K(s);(!f||!s.contains(f.node))&&ae(s,s,0)}if(typeof ResizeObserver<"u"){let f=new ResizeObserver(()=>si(s,a));f.observe(s),d.signal.addEventListener("abort",()=>f.disconnect(),{once:!0})}return{input:s,inlinePillContainer:a,dropdown:i,submitButton:l,abort:d}}function Nt(n,e,t){let{input:i,inlinePillContainer:o,dropdown:r,submitButton:s}=n,{pillPlacement:a,setActivePill:l,selectOption:c,store:d}=t;i.setAttribute("aria-expanded",String(e.isDropdownOpen));let u=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(u?i.setAttribute("aria-activedescendant",u):i.removeAttribute("aria-activedescendant"),s){let f=!!e.text||e.completedParams.length>0;s.disabled=!f}let p=i.dataset.newParamId??"",g=e.newParamId!==null&&e.newParamId!==p;if(kt({input:i,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?Be(o,e.actionableSuggestions,0,l,!1,f,e.isActivePillSelected):Tt(o)}else Tt(o);si(i,o),g?(i.focus(),D(i,e.caretOffset??e.text.length)):e.isFocused&&Ie(i)!==e.text&&D(i,e.text.length);let b=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:e.editingIdentified?{type:e.editingIdentified.type,text:W(e.editingIdentified.type),required:!0,options:[]}:null,y=b??e.actionableSuggestions[0],S=de(e);qe(r,{suggestions:y?[{...y,options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation||e.isSearchingOptions,listboxId:t.listboxId,pills:b?[b]: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",formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:S.selectedIso,selectedDateRange:S.selectedRange,dateRangeStart:S.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 li(n,e){let t=n.actionableSuggestions[0];if(!t)return null;let i=n.filterBase,o=n.text.slice(0,i),r=o.length===0&&n.text.length===0,s=o.length===0&&n.text.length>0&&n.placeholderText.length>0&&n.placeholderText.toLowerCase().startsWith(n.text.toLowerCase());(r||s)&&n.placeholderText&&(o=`${n.placeholderText} `);let a=an(o,e.text);a>0&&(o=o.slice(0,o.length-a));let l=o.length>0&&o[o.length-1]!==" ",c=`${o}${l?" ":""}${e.text} `,d=(r||s)&&c.length>0?c[0].toUpperCase()+c.slice(1):c,u=d.toLowerCase().lastIndexOf(e.text.toLowerCase()),p=u>=0?d.slice(u,u+e.text.length):e.text,g={id:crypto.randomUUID(),placeholder:"",type:t.type,text:p,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},b=n.actionableSuggestions.length-1;return{patch:{text:d,filterBase:d.length,completedParams:[...n.completedParams,g],newParamId:g.id,caretOffset:d.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:!0,inSelectionAnimation:!0,pendingSpan:null},telemetry:{selectedOption:e.text,otherOptions:n.filteredOptions.filter(y=>y.text!==e.text).map(y=>y.text)},consumedSuggestion:t,remainingActionable:b}}function Ft(n){let e=n,t=new Set,i=[],o=!1;return{get:()=>e,set:r=>{let s=typeof r=="function"?r(e):r,a=e;if(e={...e,...s},i.push([e,a]),!o){o=!0;try{let l=0;for(let c=i.shift();c;c=i.shift()){if(++l>1e4)throw i.length=0,new Error("createStore: notifications did not settle after 10000 deliveries \u2014 a listener is likely calling set() on every notification");let[d,u]=c;for(let p of t)p(d,u)}}catch(l){throw i.length=0,l}finally{o=!1}}},subscribe:r=>(t.add(r),()=>{t.delete(r)})}}function di(n,e){let t,i,o=r=>(r!==t&&(t=r,i=e(r)),i);return{get:()=>{let r=n.get();return{...r,...o(r)}},set:r=>{typeof r=="function"?n.set(s=>{let a={...s,...o(s)};return r(a)}):n.set(r)},peek:r=>{let s={...n.get(),...r};return{...s,...e(s)}},subscribe:r=>n.subscribe((s,a)=>{let l={...a,...o(a)},c={...s,...o(s)};r(c,l)})}}var Ht=new WeakSet,ci=new WeakMap;function pi(n){return n.nodeType===Node.DOCUMENT_NODE}function Yo(n){return pi(n)?n:n.ownerDocument}function jo(n){let e=ci.get(n);if(e)return e;let t=n.defaultView?.CSSStyleSheet;if(typeof t!="function")return null;try{let i=new t;return typeof i.replaceSync!="function"?null:(i.replaceSync(fi),ci.set(n,i),i)}catch{return null}}function ui(n,e){if(e.querySelector("style[data-magicx-aia]"))return;let t=n.createElement("style");t.setAttribute("data-magicx-aia",""),t.textContent=fi,e.appendChild(t)}function mi(n){if(typeof document>"u")return;let e=n??document;if(Ht.has(e))return;let t=Yo(e);if(pi(e)){let r=e.head??e.documentElement;if(!r)return;ui(t,r),Ht.add(e);return}let i=jo(t),o=e.adoptedStyleSheets;i&&Array.isArray(o)?o.includes(i)||(e.adoptedStyleSheets=[...o,i]):ui(t,e),Ht.add(e)}var fi=`.aia-stack {
|
|
1
|
+
function Xe(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9]+/).filter(Boolean).map(e=>e.toLowerCase())}function G(n){let e=Xe(n);return e.length>0?e.join(" "):n}var z=["January","February","March","April","May","June","July","August","September","October","November","December"],be=["S","M","T","W","T","F","S"],Yt=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],jt="aiaDate",zt="aiaDay",Kt=n=>String(n).padStart(2,"0");function M(n){return`${n.getFullYear()}-${Kt(n.getMonth()+1)}-${Kt(n.getDate())}`}function Je(n){return new Date(n.getFullYear(),n.getMonth(),n.getDate())}function Ii(n){let e=Je(n).getTime()-Je(new Date).getTime();return Math.round(e/864e5)}function Xt(n){let e=Ii(n);return e>=0&&e<7?Yt[n.getDay()]:X(n)}function X(n){return n.getFullYear()===new Date().getFullYear()?`${z[n.getMonth()]} ${n.getDate()}`:`${z[n.getMonth()]} ${n.getDate()} ${n.getFullYear()}`}function ye(n){if(!n)return null;let e=Yt.findIndex(a=>a.toLowerCase()===n.trim().toLowerCase());if(e>=0){let a=Je(new Date),l=(e-a.getDay()+7)%7;return new Date(a.getFullYear(),a.getMonth(),a.getDate()+l)}let t=/^\s*([A-Za-z]+)\s+(\d{1,2})(?:\s+(\d{4}))?\s*$/.exec(n);if(!t)return null;let i=z.findIndex(a=>a.toLowerCase()===t[1].toLowerCase());if(i<0)return null;let o=Number(t[2]),r=t[3]?Number(t[3]):new Date().getFullYear(),s=new Date(r,i,o);return s.getMonth()!==i||s.getDate()!==o?null:s}function Ze(n){return`${z[n.month]} ${n.year}`}function et(){let n=new Date;return{year:n.getFullYear(),month:n.getMonth()}}function Jt(n){return{year:n.getFullYear(),month:n.getMonth()}}function tt(n,e){let t=new Date(n.year,n.month+e,1);return{year:t.getFullYear(),month:t.getMonth()}}function Qt(){return{text:"",is_tappable:!1,kind:null}}function nt(n){let e=new Date(n.year,n.month,1).getDay(),t=new Date(n.year,n.month+1,0).getDate(),i=[];for(let o=0;o<e;o++)i.push(Qt());for(let o=1;o<=t;o++){let r=new Date(n.year,n.month,o);i.push({text:Xt(r),is_tappable:!0,kind:null,metadata:{[jt]:M(r),[zt]:o}})}for(;i.length%be.length!==0;)i.push(Qt());return i}function it(n){let e=ye(n);return e?M(e):null}function N(n){let e=n?.metadata?.[jt];return typeof e=="string"?e:null}function ot(n){let e=n?.metadata?.[zt];return typeof e=="number"?e:null}function Ri(n){return n.replace(/(\d+)(?:st|nd|rd|th)\b/g,"$1")}function Zt(n){let e=n.toLowerCase().replace(/\.$/,"");return e.length<3?-1:z.findIndex(t=>t.toLowerCase().startsWith(e))}function Di(n,e,t){let i=new Date(t.getFullYear(),n,e);if(i.getMonth()!==n||i.getDate()!==e)return null;let o=new Date(t.getFullYear(),t.getMonth(),t.getDate());if(i>=o)return i;let r=new Date(t.getFullYear()+1,n,e);return r.getMonth()===n&&r.getDate()===e?r:null}function en(n,e,t){let i=new Date(n,e,t);return i.getMonth()===e&&i.getDate()===t?i:null}function q(n,e={}){if(!n)return null;let t=e.today??new Date,i=Ri(n.trim().toLowerCase()).replace(/\s+/g," "),o=/^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(i);if(o){let l=en(Number(o[1]),Number(o[2])-1,Number(o[3]));return l?M(l):null}let r=/^([a-z]+)\.? (\d{1,2})(?:,? (\d{4}))?$/.exec(i);if(r){let l=Zt(r[1]);if(l>=0)return Se(l,Number(r[2]),r[3],t)}let s=/^(\d{1,2}) (?:of )?([a-z]+)\.?(?:,? (\d{4}))?$/.exec(i);if(s){let l=Zt(s[2]);if(l>=0)return Se(l,Number(s[1]),s[3],t)}let a=/^(\d{1,2})[/\-.](\d{1,2})(?:[/\-.](\d{2,4}))?$/.exec(i);if(a){let l=Number(a[1]),c=Number(a[2]);return l>12&&c<=12?Se(c-1,l,a[3],t):c>12&&l<=12?Se(l-1,c,a[3],t):null}return null}function Se(n,e,t,i){if(t){if(t.length!==4)return null;let r=en(Number(t),n,e);return r?M(r):null}let o=Di(n,e,i);return o?M(o):null}function rt(n,e={}){let t=n.isoDate;return typeof t=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t)?t:q(n.text,e)}var nn=" - ",at="aiaDateRangeStart",lt="aiaDateRangeEnd";function se(n,e){return n<=e?{start:n,end:e}:{start:e,end:n}}var st=/^\d{4}-\d{2}-\d{2}$/;function tn(n){if(!st.test(n))return null;let[e,t,i]=n.split("-").map(Number),o=new Date(e,t-1,i);return o.getMonth()===t-1&&o.getDate()===i?o:null}var Li=/\s+(?:to|through|thru|until|til|till)\s+/g,Mi=/[-–—]/g;function ki(n){let e=[];for(let t of[Li,Mi]){t.lastIndex=0;let i=t.exec(n);for(;i!==null;)e.push([n.slice(0,i.index),n.slice(i.index+i[0].length)]),i=t.exec(n)}return e}function J(n,e={}){if(!n)return null;let t=new Set,i=null;for(let[o,r]of ki(n.trim())){let s=q(o.trim(),e);if(!s)continue;let a=q(r.trim(),e);!a||a<s||(t.add(`${s}|${a}`),i={start:s,end:a})}return t.size===1?i:null}function on(n){let e=tn(n.start),t=tn(n.end);return!e||!t?"":n.start===n.end?X(e):`${X(e)}${nn}${X(t)}`}function rn(n,e){let t=se(n,e);return{text:on(t),is_tappable:!0,kind:null,metadata:{[at]:t.start,[lt]:t.end}}}function ae(n,e={}){let t=n?.metadata?.[at],i=n?.metadata?.[lt];return typeof t=="string"&&typeof i=="string"&&st.test(t)&&st.test(i)?se(t,i):J(n?.text,e)}function P(n){return n==="date"||n==="date-range"}var _i=new Set(["date","dates"]),Ni=new Set(["range","ranges","span","period","window"]),sn=3;function Fi(n){let e={single:0,range:0};if(!n)return e;for(let t of n)t.is_tappable&&(J(t.text)!==null?e.range+=1: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=Fi(n.options);if(t.single+t.range>=sn&&t.range>t.single)return"date-range";let i=Xe(n.type);return i.some(o=>_i.has(o))?i.some(o=>Ni.has(o))?"date-range":"date":t.single>=sn?"date":"options"}var xe=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 Hi="https://api.ai-autocomplete.com",ve=`${Hi}/api/suggest`,an=new WeakMap;function le(n){return n?.type==="accessToken"}function Bi(n){if(!(!n||le(n)))return n}function we(n){let e=an.get(n.getAccessToken);return e||(e=new xe(n),an.set(n.getAccessToken,e)),e}function Pe(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function Ee(n){let e=Bi(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}function de(n){return n.map(e=>({type:e.type,value:e.text}))}var ln="skipped";function ce(n,e){if(e.length===0)return n;let t=new Set(n.map(o=>o.type)),i=e.filter(o=>!t.has(o.type)).map(o=>({placeholder:"",type:o.type,text:ln,kind:null}));return i.length>0?[...n,...i]:n}var Wi="0.28.1",dn=!1;function $i(){return crypto.randomUUID()}function Gi(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.value??n.text},kind:n.kind}}function qi(n,e,t,i,o,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:ce(e.map(u=>Gi(u,t)),a??[]),...r&&r.length>0&&{identified_params:de(r)},...s&&s.length>0&&{recently_suggested:s},...d!=null&&{contact_account_count:d},...l!==void 0&&{additional_context:l}},meta:{request_id:$i(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:Wi,session_id:i,source:o}}}async function cn(n,e,t,i,o){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:o})}async function un(n,e,t){let i=t.apiConfig,o=!t.maskCompletedText,r=qi(n,e,o,t.sessionId,t.source,t.identifiedParams,t.recentlySuggested,t.skippedParams,t.additionalContext),s=Pe(i),a=i?.endpoint??ve,l=JSON.stringify(r);if(le(i)){let u=we(i),m=await u.getToken(),f=await cn(a,s,m,l,t.signal);if(f.status===401){let h=await u.getToken(!0);f=await cn(a,s,h,l,t.signal)}if(!f.ok)throw new Error(`API error: ${f.status} ${f.statusText}`);return f.json()}let c=Ee(i);!c&&!dn&&(dn=!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,i={},o=[],r=[],s=0;for(let a of e){let l=(i[a.type]??0)+1;i[a.type]=l;let d=`{{${a.type.toUpperCase().replace(/\s+/g,"_")}_${l}}}`,u=f=>{let h=t.indexOf(a.text,f);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 f=d.length-a.text.length;for(let h of r)h.start>=m+a.text.length&&(h.start+=f,h.end+=f);r.push({start:m,end:m+d.length}),s=m>=s?m+d.length:s+f}o.push({...a,placeholder:d})}return{rawQuery:t,completedParams:o}}function F(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function Te(n,e,t){return e===0&&n.length>0&&t.length>0&&t.toLowerCase().startsWith(n.toLowerCase())}function V(n,e,t){let i=n.slice(e);if(t||e===0||n[e-1]===" ")return i;let o=i.indexOf(" ");return o===-1?"":i.slice(o+1)}function pn(n,e){let t=n.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let i=t.split(" "),o=e.toLowerCase();for(let r=0;r<i.length;r++){let s=i.slice(r).join(" ");if(o.startsWith(s.toLowerCase())){let a=t.length-s.length;return n.length-a}}return 0}function K(n,e){if(!n)return[];let t=e.trimStart();if(!t)return n;let i=t.toLowerCase();return n.filter(o=>!o.is_tappable||o.text.toLowerCase().includes(i))}function Z(n,e){if(!n)return null;let t=e.trim();if(!t)return null;let i=t.toLowerCase();return n.find(o=>o.is_tappable&&o.text.toLowerCase()===i)??null}function mn(n,e){return e?n.map(t=>e[t.type]?{...t,options:[]}:t):n}function fn(n,e){let t=0,i=e;for(let o of n)t+=o.value.length,o.type!=="text"&&(i=Math.max(i,t));return i}function gn(n,e){let t=0;for(let i of n){let o=t+i.value.length;if(i.type==="text"&&o>e&&i.value.slice(Math.max(e-t,0)).trim().length>0)return!1;t=o}return!0}function hn(n,e){let t=[],i=new Set;for(let o of[...n,...e])o.type==="placeholder"||i.has(o.type)||(i.add(o.type),t.push({type:o.type,text:o.text}));return t}function bn(n,e,t){if(n===e)return t;let i=Math.min(n.length,e.length),o=0;for(;o<i&&n[o]===e[o];)o++;if(o>=t)return t;let r=0;for(;r<i-o&&n[n.length-1-r]===e[e.length-1-r];)r++;return n.length-r<=t?t+(e.length-n.length):null}function dt(n,e){let t=[],i=[],o=0;for(let r of e){let s=n.indexOf(r.text,o);if(s===-1){i.push(r);continue}t.push({start:s,end:s+r.text.length,param:r}),o=s+r.text.length}return{located:t,missing:i}}function yn(n,e,t){let i=[],o=[],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){o.push(s);continue}i.push({start:a,end:a+s.text.length,param:s}),r=a+s.text.length}return{located:i,missing:o}}function Sn(n,e,t=[]){let i=dt(n,e).located,o=yn(n,i,t).located,r=[...i.map(c=>({start:c.start,end:c.end,segment:{type:"completed",value:c.param.text,param:c.param}})),...o.map(c=>({start:c.start,end:c.end,segment:{type:"identified",value:c.param.text,param:c.param}}))].sort((c,d)=>c.start-d.start),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 xn(n,e){let{located:t,missing:i}=dt(n,e);return{valid:t.map(o=>o.param),invalid:i}}function Ce(n,e,t){let i=dt(n,e).located,{located:o,missing:r}=yn(n,i,t);return{valid:o.map(s=>s.param),invalid:r}}function Ui(n){if(n instanceof Error)return n;try{return new Error(String(n))}catch{return new Error("Unknown error")}}var Vi=100,Ki=300,Qi=2,Oe=class{constructor(e,t,i,o,r,s,a,l,c={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=o;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(i=>{(i.text!==e||i.completedParams!==t)&&(e=i.text,t=i.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let i=new AbortController;this.abortController=i;let o=++this.fetchVersion,r=this.store.get().text.length;try{this.callbacks.onRequest?.({query:this.store.get().text,signal:i.signal,isCurrent:()=>o===this.fetchVersion})}catch{}try{this.store.set({isLoading:!0,error:null});let s=this.store.get(),a=s.pendingSpan?hn(s.pendingSpan.snapshot,s.actionableSuggestions):void 0,l=await un(e,t,{sessionId:this.getSessionId(),source:this.getSource(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig(),identifiedParams:s.identifiedParams,recentlySuggested:a,skippedParams:s.skippedParams,additionalContext:this.getAdditionalContext()});if(o!==this.fetchVersion)return;let c=(l.data.input??[]).filter(x=>x.source==="identified").map(x=>({id:crypto.randomUUID(),type:x.type,text:x.text})),d=mn(l.data.suggestions??[],this.getOptionOverrides()),u=l.data.input??[],m=u[u.length-1],f=this.store.get().text,h,S;if(m?.state==="in_progress"){S=!0;let x=f.toLowerCase().lastIndexOf(m.text.toLowerCase());h=x!==-1?x:r}else S=!1,h=r;let g=d.filter(x=>x.type!=="placeholder")[0],p=null;if(g&&!P(U(g))){let x=V(f,h,S),E=Z(g.options,x);E&&(p={id:crypto.randomUUID(),placeholder:"",type:g.type,text:E.text,value:E.value,kind:E.kind,suggestionType:g.type,suggestionPlaceholder:g.text,options:g.options??[],metadata:E.metadata,icon:E.icon,icon_svg:E.icon_svg,image_url:E.image_url},d=d.filter(A=>A!==g),this.callbacks.onAutoMatch?.({active:g,matched:E,rawQuery:e}))}let b=l.data.custom_fields??null,y=this.callbacks.productsForResponse?.(b);this.store.set(x=>{let E=p?[...x.completedParams,p]:x.completedParams,A=Ce(x.text,E,c).valid,L=new Set(s.skippedParams.map(C=>C.id)),T=new Set(x.skippedParams.filter(C=>!L.has(C.id)).map(C=>C.type));return{suggestions:T.size>0?d.filter(C=>C.type==="placeholder"||!T.has(C.type)):d,isLoading:!1,isReady:l.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:h,filterInProgress:S,identifiedParams:A,customFields:b,...y!==void 0?{products:y}:{},...p?{completedParams:E}:{}}}),this.callbacks.onResponse?.()}catch(s){let a=Ui(s);o===this.fetchVersion&&(this.store.set({error:a,isLoading:!1}),this.getOnError()?.(a))}finally{if(o===this.fetchVersion&&this.store.get().isLoading)try{this.store.set({isLoading:!1})}catch{}}}attemptNow(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}this.attemptFetch(1,!0)}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}this.debounceTimer=setTimeout(()=>{this.attemptFetch(Qi)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},Vi),this.slowDebounceTimer=setTimeout(()=>this.attemptFetch(1),Ki)}attemptFetch(e,t=!1){let i=this.store.get();if(!i.text&&i.completedParams.length===0)return this.doFetch("",[]),!0;let o=this.callbacks.consumerTick?.(i,e)??"no";if(o==="asked")return!0;if(o==="owns")return!1;let r=i.suggestions.filter(y=>y.type==="placeholder").map(y=>y.text).join(" "),s=F(i.text,i.filterBase,r),a=V(i.text,s,i.filterInProgress),c=i.suggestions.filter(y=>y.type!=="placeholder")[0],d=P(i.activeFormatType),m=(c&&!d?K(c.options,a):[]).filter(y=>y.is_tappable),f=c&&!d?Z(c.options,a)!==null:!1,h=a.trim().length>0;if(m.length>0&&!f&&h||Te(i.text,i.completedParams.length,r))return!1;let{rawQuery:S,completedParams:v}=R(i.text,i.completedParams),g=S.length<i.lastRawQuery.length,p=Math.abs(S.length-i.lastRawQuery.length),b=t&&S!==i.lastRawQuery;return g||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 Yi(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&&Yi(e)?e:n.ownerDocument??n}function O(n){return n.ownerDocument??n}function ji(n){return n.nodeType===Node.DOCUMENT_FRAGMENT_NODE}function vn(n){let e=Q(n);return!ji(e)||typeof e.getSelection=="function"?null:e}function wn(n){let e=vn(n);if(!e)return null;let t=O(n).getSelection?.();return!t||typeof t.getComposedRanges!="function"?null:e}function Pn(n,e){let t=n,i;try{i=t.getComposedRanges({shadowRoots:[e]})}catch{i=t.getComposedRanges(e)}return i.length>0?i[0]:null}function ct(n){let t=Q(n).getSelection?.();return t||(O(n).getSelection?.()??null)}function Y(n){let e=ct(n);if(!e||e.rangeCount===0)return null;let t=wn(n);if(t){let i=Pn(e,t);return i?{node:i.startContainer,offset:i.startOffset,collapsed:i.startContainer===i.endContainer&&i.startOffset===i.endOffset}:null}return e.anchorNode?{node:e.anchorNode,offset:e.anchorOffset,collapsed:e.isCollapsed}:null}function Ae(n){let e=ct(n);if(!e||e.rangeCount===0)return null;let t=wn(n);if(!t)return e.getRangeAt(0);let i=Pn(e,t);if(!i)return null;let o=O(n).createRange();return o.setStart(i.startContainer,i.startOffset),o.setEnd(i.endContainer,i.endOffset),o}function ue(n,e,t){let i=ct(n);if(!i)return null;if(vn(n))return i.collapse(e,t),i;let o=O(n).createRange();return o.setStart(e,t),o.collapse(!0),i.removeAllRanges(),i.addRange(o),i}function Ie(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 Re=2,zi="magicx-aia";function En(n){return n==="auto"||n==="scroll"||n==="hidden"||n==="overlay"}function Xi(n){let e=O(n),t=e.defaultView;if(!t?.getComputedStyle)return null;let i=n;for(;i&&i!==e.body&&i!==e.documentElement;){let o=i.scrollWidth>i.clientWidth,r=i.scrollHeight>i.clientHeight;if(o||r){let s=t.getComputedStyle(i);if(o&&En(s.overflowX)||r&&En(s.overflowY))return i}if(i.classList.contains(zi))return null;i=i.parentElement}return null}function ut(n){let e=Ae(n);if(!e||!e.collapsed||!n.contains(e.startContainer))return;let t=Xi(n);if(!t||typeof e.getBoundingClientRect!="function")return;let i=e.getBoundingClientRect();if(i.height===0)return;let o=t.getBoundingClientRect();if(t.scrollWidth>t.clientWidth){let r=o.left+t.clientLeft,s=r+t.clientWidth;i.right>s?t.scrollLeft+=i.right-s+Re:i.left<r&&(t.scrollLeft-=r-i.left+Re)}if(t.scrollHeight>t.clientHeight){let r=o.top+t.clientTop,s=r+t.clientHeight;i.bottom>s?t.scrollTop+=i.bottom-s+Re:i.top<r&&(t.scrollTop-=r-i.top+Re)}}var On='[contenteditable="false"]',Ji="strong[data-param-id]",ee;function Zi(){if(ee!==void 0)return ee;let n=globalThis.Intl.Segmenter;if(!n)return ee=null,null;try{ee=new n(void 0,{granularity:"grapheme"})}catch{ee=null}return ee??null}function De(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(On))return!0;t=t.parentNode}return!1}function Le(n){return O(n).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return De(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function Me(n){let e=Le(n),t="",i=e.nextNode();for(;i;)t+=i.data,i=e.nextNode();return t}function pt(n){let e=Le(n),t=0,i=e.nextNode();for(;i;)t+=i.data.length,i=e.nextNode();return t}function _(n){let e=Y(n);if(!e)return null;let t=e.node,i=e.offset;if(!n.contains(t))return null;if(t.nodeType===Node.ELEMENT_NODE){let o=t;if(De(o,n)&&o!==n)return null;let r=0;for(let s=0;s<i&&s<o.childNodes.length;s++)r+=An(o.childNodes[s],n);return r+Tn(o,n)}return t.nodeType!==Node.TEXT_NODE||De(t,n)?null:Tn(t,n)+i}function An(n,e){if(n.nodeType===Node.TEXT_NODE)return De(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(On))return 0;let i=0;for(let o of Array.from(t.childNodes))i+=An(o,e);return i}function Tn(n,e){let t=Le(e),i=0,o=t.nextNode();for(;o;){if(o===n||n.nodeType===Node.ELEMENT_NODE&&n.contains(o))return i;i+=o.data.length,o=t.nextNode()}return i}function D(n,e){let t=O(n),i=Math.max(0,Math.min(e,pt(n))),o=Le(n),r=0,s=null,a=0,l=o.nextNode(),c=null;for(;l;){let u=l.data.length;if(i<r+u){s=l,a=i-r;break}if(i===r+u){let m=o.nextNode();m?(s=m,a=0):(s=l,a=u);break}r+=u,c=l,l=o.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),ue(n,d.startContainer,d.startOffset)&&(eo(n,d,i),ut(n))}function Cn(n,e){if(!n||!e.contains(n))return null;let i=(n.nodeType===Node.ELEMENT_NODE?n:n.parentElement)?.closest(Ji)??null;return i&&e.contains(i)?i:null}function eo(n,e,t){let i=Cn(Y(n)?.node??null,n);if(i&&i!==Cn(e.startContainer,n)){n.dataset.aiaCaretEscapedChip=`${t}:${i.dataset.paramId}`;return}delete n.dataset.aiaCaretEscapedChip}function In(n,e){let t=n.dataset.aiaCaretEscapedChip;if(!t)return!1;let i=_(n);return i!==null&&t===`${i}:${e}`}function Rn(n){return Q(n).activeElement===n}function mt(n){let e=_(n);return e==null?!1:e>=pt(n)}function ft(n,e){if(e<=0)return 0;let t=Zi();if(!t)return e-1;let i=n.slice(0,e),o=0;for(let{index:r}of t.segment(i))r<e&&(o=r);return o}function j(n,e,t=[],i={}){let{rawQuery:o,completedParams:r}=R(n,e);return{query:n.trim(),raw_query:o,completed_params:ce(r,t),identified_params:de(i.identifiedParams??[]),is_ready:i.isReady??!1,...i.customFields?{custom_fields:i.customFields}:{}}}function gt(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")?mt(n):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function ht(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?_(n):null}var ke=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:o}=this.ctx,r=e.target instanceof Node?e.target:null,s=this.getEffectiveColumns(r),a=o(),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=gt(e.target,t),u=!!t.editingParam;if(!d&&!u&&t.activeDropdownIndex<0)break;if(t.activeDropdownIndex<0){if(c)break;e.preventDefault();let h=P(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(P(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),f=m<l.length-1?m+1:0;this.store.set({activeDropdownIndex:l[f]});break}case"ArrowUp":{if(t.activeDropdownIndex<0){if(!c)break;let m=gt(e.target,t),f=!!t.editingParam;if(!m&&!f)break;e.preventDefault();let h=P(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(),P(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(),P(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?.(),D(u,m);break}gt(e.target,t)&&t.actionableSuggestions.length>=1&&(e.preventDefault(),this.ctx.skipActivePill());break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),P(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=ht(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?.(),D(d,u);break}if(this.ctx.startEditingParamAtCaret){let d=ht(e.target);d!=null&&this.ctx.startEditingParamAtCaret(d)&&e.preventDefault()}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let d=ht(e.target);if(d==null)break;this.ctx.removeParamAtCaret(d)&&e.preventDefault();break}case"Enter":{e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable?this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i,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((f,h)=>f.is_tappable?h:-1).filter(f=>f!==-1);if(d.length===0)break;if(!t.isDropdownOpen){if(t.actionableSuggestions.length===0)break;e.preventDefault();let f=e.shiftKey?d[d.length-1]:d[0];this.store.set({pillTapped:!0,activeDropdownIndex:f});break}e.preventDefault();let u=d.indexOf(t.activeDropdownIndex),m;if(u<0)m=e.shiftKey?d.length-1:0;else{let f=e.shiftKey?-1:1;m=(u+f+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?.(),D(d,u)}this.store.set({activeDropdownIndex:-1});break}}}firstTappableInBottomRow(e){let t=this.store.get();if(t.filteredOptions.length===0)return null;let o=Math.floor((t.filteredOptions.length-1)/e)*e;for(let r=o;r<t.filteredOptions.length;r++)if(t.filteredOptions[r]?.is_tappable)return r;return null}dateEntryIndex(e,t){let i=M(new Date),o=e.filteredOptions.findIndex(s=>N(s)===i);if(o>=0)return o;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 i=e.activeDropdownIndex+t;i>=0&&i<e.filteredOptions.length;i+=t)if(e.filteredOptions[i]?.is_tappable){this.store.set({activeDropdownIndex:i});return}}stepDateWeek(e,t){let i=e.activeDropdownIndex+t;this.store.set({activeDropdownIndex:e.filteredOptions[i]?.is_tappable?i:-1})}getTappableIndices(e){let i=this.store.get().filteredOptions.map((r,s)=>r.is_tappable?s:-1).filter(r=>r!==-1),o=Array.from({length:e},()=>[]);for(let r of i)o[r%e].push(r);return o.flat()}getEffectiveColumns(e){let t=Ie(e,this.ctx.listboxId);if(!t)return this.ctx.columns;let o=Ie(e,`${this.ctx.listboxId}-option-0`)?.parentElement??null;for(;o;){let r=getComputedStyle(o).gridTemplateColumns;if(r&&r!=="none"){let s=r.split(" ").filter(Boolean).length;if(s>0)return s}if(o===t)break;o=o.parentElement}return this.ctx.columns}clickOrSelect(e,t,i,o){let r=Ie(o,`${i}-option-${e}`);r?r.click():this.ctx.selectOption(t[e])}};var _e=class{constructor(e,t,i={}){this.store=e;this.getOverrides=t;this.callbacks=i;this.unsubscribe=null;this.current=null;this.version=0;this.lastMiss=null;this.hasLoggedError=!1}start(){this.unsubscribe=this.store.subscribe(e=>this.sync(e)),this.sync(this.store.get())}dispose(){this.unsubscribe?.(),this.unsubscribe=null,this.cancel(),this.current=null}reset(){this.cancel(),this.current=null,this.lastMiss=null}refresh(){this.reset(),this.sync(this.store.get())}hasOverride(e){return!!this.getOverrides()?.[e]}owns(e,t){return this.hasOverride(e)&&!this.missCovers(e,t)}tick(e,t){let i=this.resolveTarget(e);if(!i||this.missCovers(i.type,i.query))return"no";let o=this.current;if(o&&o.key===i.key){if(o.query===i.query)return"owns";let r=Math.abs(i.query.length-o.query.length),s=i.query.length<o.query.length;if(t>1&&!s&&r<t)return"owns"}return this.ask(i),"asked"}sync(e){let t=this.resolveTarget(e);if(!t){this.current&&(this.cancel(),this.current=null),e.optionSearch&&this.store.set({optionSearch:null});return}this.current&&this.current.key===t.key||this.ask(t)}resolveTarget(e){if(P(e.activeFormatType)||e.editingIdentified)return null;let t=e.editingParam;if(t&&e.editingAnchor!=null)return this.hasOverride(t.suggestionType)?{mode:"edit",key:t.id,type:t.suggestionType,suggestion:{type:t.suggestionType,text:t.suggestionPlaceholder,required:!0,options:t.options},query:e.optionQuery}:null;let i=e.actionableSuggestions[0];return!i||!this.hasOverride(i.type)?null:{mode:"pill",key:i,type:i.type,suggestion:i,query:e.optionQuery}}missCovers(e,t){return this.lastMiss!=null&&this.lastMiss.type===e&&this.lastMiss.query===t}ask(e){this.cancel();let t=this.getOverrides()?.[e.type],i=++this.version;if(!t||this.missCovers(e.type,e.query)){this.current={key:e.key,type:e.type,query:e.query,abort:null},this.setSearch(e,"done");return}let o=new AbortController;this.current={key:e.key,type:e.type,query:e.query,abort:o};let r;try{r=t(e.query,o.signal,e.suggestion)}catch(s){this.logOnce(s),this.commit(e,[],i);return}if(Array.isArray(r)){this.commit(e,r,i);return}this.setSearch(e,"loading"),this.await(e,r,o.signal,i)}async await(e,t,i,o){let r;try{let s=await t;if(i.aborted||o!==this.version)return;r=Array.isArray(s)?s:[]}catch(s){if(i.aborted||o!==this.version||to(s))return;this.logOnce(s),r=[]}this.commit(e,r,o)}commit(e,t,i){if(i!==this.version)return;let o=this.resolveTarget(this.store.get());if(!o||o.key!==e.key)return;t.length===0?this.lastMiss={type:e.type,query:e.query}:this.lastMiss?.type===e.type&&(this.lastMiss=null);let 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 i=this.store.get().optionSearch;i&&i.type===e.type&&i.query===e.query&&i.status===t||this.store.set({optionSearch:{type:e.type,query:e.query,status:t}})}cancel(){this.current?.abort?.abort(),this.version++}logOnce(e){this.hasLoggedError||(this.hasLoggedError=!0,console.warn("[AIAutocomplete] an optionOverrides entry threw or rejected \u2014 treated as no options. Later failures on this instance are not logged.",e))}};function to(n){return n instanceof Error&&n.name==="AbortError"}var Ne=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),i=t.suggestions.filter(c=>c.type!=="placeholder");if(e<0||e>=i.length)return;let o=i[e],r=i.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:o.text,otherPills:r.map(d=>d.text)})}let a=[...s,o,...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 Ln="/products/",Dn="https://relative.invalid";function no(n){if(!n)return;let e;try{e=new URL(n,`${Dn}/`)}catch{return}if(!(e.protocol!=="http:"&&e.protocol!=="https:"))return n.startsWith("/")?e.origin===Dn?n:void 0:/^https?:\/\//i.test(n)?n:void 0}function Mn(n){let e=no(n.item_url)??(n.handle?`${Ln}${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 bt(n){return(n?.items.matched??[]).map(Mn)}var Fe=class{constructor(e,t,i=()=>!0){this.store=e;this.getConfig=t;this.isEnabled=i;this.hasLoggedError=!1}forResponse(e){if(!this.isEnabled())return[];if(!this.getConfig())return bt(e)}async run(e,t,i){if(!this.isEnabled())return;let o=this.getConfig();if(!o)return;if(e.trim().length===0){this.clear(i);return}let r=()=>t.aborted||!i()||!this.owns(o);try{let s=await o.fetch(e,t);if(r())return;let a=o.transform(s),l=Array.isArray(a)?a:[],c=o.limit!=null?l.slice(0,o.limit):l;if(r())return;this.commit(c)}catch(s){if(t.aborted||io(s)||(this.logOnce(s),r()))return;this.clear(i)}}owns(e){return this.isEnabled()&&this.getConfig()===e}resync(){let e=this.forResponse(this.store.get().customFields);this.commit(e??[])}clear(e){e()&&this.commit([])}commit(e){e.length===0&&this.store.get().products.length===0||this.store.set({products:e})}logOnce(e){this.hasLoggedError||(this.hasLoggedError=!0,console.warn("[AIAutocomplete] products.fetch/transform failed \u2014 the product strip is hidden. Later failures on this instance are not logged.",e))}};function io(n){return n instanceof Error&&n.name==="AbortError"}var He="(max-width: 768px)";var oo="var(--aia-option-row-height, 37px)",ro="var(--aia-grid-scroll-top, 0px) + var(--aia-grid-scroll-bottom, 0px)";function kn(n,e){return e?yt(1,Math.min(n,5)):yt(1,Math.min(n,4))}function yt(n,e){return{cols:n,rows:e,maxHeight:`calc(${e} * ${oo} + ${ro})`}}function xt(n,e){return!e&&n>=5}function vt(n,e,t,i){if(!(!e&&n>=5&&so(t,i))){let s=kn(n,e);return{...s,template:St(s.cols),scrollHintIndices:!e&&n>s.rows?[s.rows-1]:[]}}let r=6;return{...yt(2,3),template:St(2),scrollHintIndices:n>r?[r-2,r-1]:[]}}function so(n,e){return!n||n.length===0||e==null||e<=0||n.some(i=>i<=0)?!1:Math.ceil(Math.max(...n))*2<=e}function wt(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 i=Array.from(t.children).map(s=>s.offsetWidth);t.remove();let o=getComputedStyle(n),r=n.clientWidth-(Number.parseFloat(o.paddingLeft)||0)-(Number.parseFloat(o.paddingRight)||0)-(Number.parseFloat(o.columnGap)||0);return{rowWidths:i,gridWidth:r}}function St(n){return Array.from({length:n},()=>"minmax(0,1fr)").join(" ")}function Pt(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(He).matches}function _n(n,e){let t=e.dropdownTrigger??"auto",i=e.closeDropdownOnBlur??!0,s=n.filteredOptionsLength>0||n.activePillHasNoOptions||n.hasProducts;if(n.inEditMode){let a=i?n.isFocused:!0;return s&&a}if(t==="auto"){let a=i?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 pe(n){if(n.editingIdentified){let{type:t,anchor:i}=n.editingIdentified;return`identified:${t}@${i}`}return n.editingParam!=null&&n.editingAnchor!=null?`edit:${n.editingParam?.id}`:`pill:${n.actionableSuggestions[0]?.type??""}`}function Nn(n){if(!n)return et();let[e,t]=n.split("-").map(Number);return{year:e,month:t-1}}function ao(n){let e=ye(n);return e?Jt(e):et()}function Fn(n,e){let t=Sn(n.text,n.completedParams,n.identifiedParams),i=n.suggestions.filter(w=>w.type!=="placeholder"),o=i[0],r=n.suggestions.filter(w=>w.type==="placeholder").map(w=>w.text).join(" "),s=F(n.text,Math.min(n.filterBase,n.text.length),r),l=s===0&&Te(n.text,n.completedParams.length,r)?"":V(n.text,s,n.filterInProgress),c=o?.options??[],d=n.editingParam!=null&&n.editingAnchor!=null,u,m,f,h;if(d&&n.editingParam&&n.editingAnchor!=null){let w=n.editingParam.id,k=n.completedParams.some(Ai=>Ai.id===w),re=n.caretOffset??n.editingAnchor,Vt=k?"":n.text.slice(n.editingAnchor,re);m=Vt.trim(),f=n.editingParam.options,h=n.editingParam.suggestionType,u=K(n.editingParam.options,Vt)}else m=l.trim(),f=c,h=o?.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=f);let g=v&&S.status==="loading",p=e.showNonTappableOptions===!1;p&&(u=u.filter(w=>w.is_tappable));let b=n.editingIdentified,y=d?n.editingParam&&{type:n.editingParam.suggestionType,options:n.editingParam.options}:o,x=b?b.format:U(y),E=d&&P(x)?ae(n.editingParam):null;E&&(x="date-range");let A=null,L=null;if(P(x)){let w=pe({...n,actionableSuggestions:i}),k=n.dateViewMonth;A=k&&k.key===w?{year:k.year,month:k.month}:b?Nn(b.iso):E?Nn(E.start):ao(n.editingParam?.text),u=nt(A);let re=n.pendingRangeStart;x==="date-range"&&re&&re.key===w&&(L=re.iso)}let T=w=>p?w.is_tappable:!0,I;if(d){let w=n.editingParam?.options??[];I=n.editingParam!=null&&w.filter(T).length===0}else I=o!=null&&c.filter(T).length===0;let C=_n({inEditMode:d||b!=null,filteredOptionsLength:u.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading||g,pillTapped:n.pillTapped,activePillHasNoOptions:I,hasProducts:n.products.length>0},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),ze=C&&n.activeDropdownIndex>=0&&!!u[n.activeDropdownIndex]?.is_tappable;return{segments:t,actionableSuggestions:i,filteredOptions:u,activeFormatType:x,dateView:A,dateRangeStart:L,placeholderText:r,optionQuery:m,isSearchingOptions:g,isDropdownOpen:C,isActivePillSelected:ze}}function Be(n){return n.mode==="fresh"?lo(n):co(n)}function lo(n){let{text:e,completedParams:t,suggestions:i,filterBase:o,filterInProgress:r}=n,a=i.filter(y=>y.type!=="placeholder")[0];if(!a?.options)return null;let l=i.filter(y=>y.type==="placeholder").map(y=>y.text).join(" "),c=F(e,o,l),d=V(e,c,r),u=Z(a.options,d);if(!u)return null;let m=u.text.toLowerCase(),f=e.toLowerCase().lastIndexOf(m),h=f>=0?f: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:i.filter(y=>y!==a),filterBase:p,newParamId:b.id,caretOffset:p,activeDropdownIndex:-1},caretPos:p}}function co(n){let{text:e,completedParams:t,editingParam:i,editingAnchor:o,editingTail:r}=n;if(t.some(b=>b.id===i.id))return null;let s=e.slice(o,r),a=Z(i.options,s);if(!a)return null;let l=a.text.toLowerCase(),c=s.toLowerCase().lastIndexOf(l),d=o+Math.max(0,c),u=d+a.text.length,m=e.slice(d,u),f=u<e.length&&e[u]===" "?u+1:u,h=e.length,S={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:m,value:a.value,kind:a.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:a.metadata,icon:a.icon,icon_svg:a.icon_svg,image_url:a.image_url},v=t.length,g=0;for(let b=0;b<t.length;b++){let y=e.indexOf(t[b].text,g);if(y!==-1){if(y>=f){v=b;break}g=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 We(n,e,t){let i=n.slice(0,e),o=n.slice(t),r=(i===""||i.endsWith(" "))&&o.startsWith(" ");return r&&(o=o.slice(1)),{text:i+o,removed:t-e+(r?1:0)}}var $e=class{constructor(e){this.deps=e}start(e){let t=this.deps.store.get();if(t.editingParam?.id===e)return;let i=t.completedParams.find(s=>s.id===e);if(!i)return;let o=0,r=-1;for(let s of t.completedParams){let a=t.text.indexOf(s.text,o);if(a!==-1){if(s.id===e){r=a;break}o=a+s.text.length}}r<0||this.deps.store.set({editingParam:i,editingAnchor:r,editingTail:r+i.text.length,caretOffset:r+i.text.length,activeDropdownIndex:-1,editingIdentified:null})}exit(){this.deps.store.get().editingParam&&this.deps.store.set({editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1})}replaceRange(e){let t=this.deps.store.get(),i=t.editingParam,o=t.editingAnchor,r=t.editingTail;if(!i||o==null||r==null||!t.completedParams.some(l=>l.id===i.id))return!1;let{text:s}=e===""?We(t.text,o,r):{text:t.text.slice(0,o)+e+t.text.slice(r)},a=o+e.length;return this.deps.store.set(l=>({text:s,completedParams:l.completedParams.filter(c=>c.id!==i.id),editingTail:a,caretOffset:a,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(a),this.promoteIfExact(),!0}caretAfterInput(e){let t=this.deps.store.get(),i={caretOffset:e};t.editingParam&&t.editingAnchor!=null&&e!=null&&(e<t.editingAnchor?(i.editingParam=null,i.editingAnchor=null,i.editingTail=null,i.activeDropdownIndex=-1):t.editingTail!=null&&(i.editingTail=Math.max(t.editingTail,e))),this.deps.store.set(i),this.promoteIfExact()}caretMove(e){let t=this.deps.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null&&e!=null&&(e<t.editingAnchor||e>t.editingTail)){this.deps.store.set({caretOffset:e,editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1});return}this.deps.store.set({caretOffset:e})}selectOption(e){let t=this.deps.store.get(),i=t.editingParam,o=t.editingAnchor,r=t.editingTail;if(!i||o==null||r==null)return;this.deps.fireTelemetry("option",{raw_query:R(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:i.options.filter(g=>g.text!==e.text).map(g=>g.text)});let s=t.text.slice(0,o),a=t.text.slice(r),l=o===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,d=a.length===0||a[0]!==" "?`${l} `:l,u=s+d+a,m=u.length,f={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:l,value:e.value,kind:e.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url},h=t.completedParams.findIndex(g=>g.id===i.id),S=t.completedParams.filter(g=>g.id!==i.id),v=h>=0?Math.min(h,S.length):S.length;S.splice(v,0,f),this.deps.store.set({text:u,completedParams:S,newParamId:f.id,filterBase:m,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:m,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.deps.startSelectionAnimationTimer(),this.deps.scheduleSetCursor(m),this.deps.fetchNow()}promoteIfExact(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let t=Be({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 uo=33,po=70,mo=120,fo=50,te="data-aia-placeholder-leaving",ne=new WeakMap;function Ge(n){n.timer!==null&&(clearTimeout(n.timer),n.timer=null)}function go(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function Bn(n,e,t){e.shown=t,n.dataset.placeholder=e.target.slice(0,t)}function Wn(n,e){if(e.timer=null,!n.isConnected||e.shown>=e.target.length||(Bn(n,e,e.shown+1),e.shown>=e.target.length))return;let t=e.target[e.shown-1],i=t===" "||t==="-"?70:0;e.timer=setTimeout(()=>Wn(n,e),33+i)}function Hn(n,e){Bn(n,e,0),e.timer=setTimeout(()=>Wn(n,e),33)}function $n(n,e){let t=ne.get(n);if(e===""){t&&(Ge(t),ne.delete(n)),n.removeAttribute(te),delete n.dataset.placeholder;return}if(t?.target===e)return;if(go(n)){t&&Ge(t),n.removeAttribute(te),ne.set(n,{target:e,shown:e.length,timer:null}),n.dataset.placeholder=e;return}let i={target:e,shown:0,timer:null},o=t&&t.shown>0?t:null;if(t&&Ge(t),ne.set(n,i),o){n.setAttribute(te,""),i.timer=setTimeout(()=>{i.timer=null,n.removeAttribute(te),n.isConnected&&Hn(n,i)},170);return}n.removeAttribute(te),Hn(n,i)}function Gn(n){let e=ne.get(n);e&&(Ge(e),ne.delete(n))}var qn="https://ai-autocomplete.com";function Et(n=qn){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 Tt(n,e){return n?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}var Un=new WeakMap,Vn=new WeakSet;function H(n,e,t){if(Un.set(n,t),Vn.has(n))return;Vn.add(n);let i=()=>Un.get(n),o=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=o(r.target);s&&e.onClick?.(s,i(),r)}),e.onEnter&&n.addEventListener("mouseenter",r=>{let s=r.target;s instanceof HTMLElement&&s.matches(e.itemSelector)&&e.onEnter?.(s,i())},!0),e.preventMousedown&&n.addEventListener("mousedown",r=>r.preventDefault())}function ie(n){return Number.parseInt(n.dataset.aiaIndex??"-1",10)}function B(n){n.offsetWidth}var ho={selectedIso:null,selectedRange:null,rangeStart:null};function me(n){if(!P(n.activeFormatType))return ho;let e=n.editingIdentified;if(e){let{iso:i,isoEnd:o}=e;return{selectedIso:o?null:i,selectedRange:i&&o?se(i,o):null,rangeStart:n.dateRangeStart}}let t=ae(n.editingParam);return{selectedIso:t?null:it(n.editingParam?.text),selectedRange:t,rangeStart:n.dateRangeStart}}function Ct(n){return n.pendingStart?se(n.pendingStart,n.highlightedIso??n.pendingStart):n.selected}function Ot(n,e){if(n==null)return{selected:!1,inRange:!1};let{selectedIso:t,range:i}=e,o=n===t||i!=null&&(n===i.start||n===i.end),r=i!=null&&n>i.start&&n<i.end;return{selected:o,inRange:r}}var Kn="data-aia-key";function W(n,e,t){let i=new Map;for(let s of Array.from(n.children)){let a=s.getAttribute(Kn);a!=null&&i.set(a,s)}let o=new Set,r=[];for(let s=0;s<e.length;s++){let a=e[s],l=t.keyOf(a,s);o.add(l);let c=i.get(l);c||(c=t.create(a,s),c.setAttribute(Kn,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 i)o.has(s)||a.remove();return r}function Qn(n,e){if(!e.interactive)return null;let t=e.options[ie(n)];return t?.is_tappable?t:null}var bo={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=Qn(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")&&Qn(n,e)&&e.callbacks.onHighlight(ie(n))}};function jn(n,e,t,i,o,r,s,a=!0){let l=n.querySelector(".magicx-aia-datepicker");if(!o||e.length===0){l?.remove();return}if(!l){l=xo(),n.appendChild(l),B(l);for(let u of l.querySelectorAll(".magicx-aia-datepicker-nav"))u.disabled=!1}H(l,bo,{options:e,callbacks:s,interactive:a});let c=l.querySelector(".magicx-aia-datepicker-month");c&&(c.textContent=Ze(o));let d=l.querySelector(".magicx-aia-datepicker-grid");d&&yo(d,e,t,i,r)}function yo(n,e,t,i,o){let r=M(new Date),s=Ct({pendingStart:o.rangeStart,highlightedIso:N(e[t]),selected:o.selectedRange});W(n,e,{keyOf:(a,l)=>N(a)??`pad-${l}`,create:a=>So(a),update:(a,l,c)=>{let d=N(l),u=Ot(d,{selectedIso:o.selectedIso,range:s}),m=c===t&&l.is_tappable;a.id=`${i}-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 So(n){let e=document.createElement("div");e.setAttribute("role","option"),e.setAttribute("data-aia-option",""),e.setAttribute("data-aia-date-cell","");let t=ot(n);if(t==null)return e.className="magicx-aia-date-cell magicx-aia-date-cell--blank",e.setAttribute("aria-hidden","true"),e.tabIndex=-1,e;e.className="magicx-aia-date-cell magicx-aia-date-cell--day",e.tabIndex=0,e.setAttribute("aria-label",n.text);let i=document.createElement("span");return i.className="magicx-aia-date-cell-number",i.textContent=String(t),e.appendChild(i),e}function xo(){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(Yn("prev","Previous month","\u2039"),t,Yn("next","Next month","\u203A"));let i=document.createElement("div");i.className="magicx-aia-datepicker-weekdays",i.setAttribute("aria-hidden","true");for(let r of be){let s=document.createElement("span");s.className="magicx-aia-datepicker-weekday",s.textContent=r,i.appendChild(s)}let o=document.createElement("div");return o.className="magicx-aia-datepicker-grid",o.setAttribute("data-aia-date-grid",""),n.append(e,i,o),n}function Yn(n,e,t){let i=document.createElement("button");return i.type="button",i.tabIndex=-1,i.className="magicx-aia-datepicker-nav",i.setAttribute(`data-aia-date-${n}`,""),i.setAttribute("aria-label",e),i.textContent=t,i.disabled=!0,i}var vo={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},zn=[125,69];function Xn(n,e){return e?1:n===0?.7:n===1?.4:.2}function qe(n,e,t,i,o=!1,r=!1,s=!1){let a=n.querySelector(".magicx-aia-pill-list");if(a||(a=document.createElement("span"),a.className="magicx-aia-pill-list",n.appendChild(a)),H(a,vo,{onSelectPill:i,loading:r}),r&&e.length===0){a.setAttribute("data-aia-pill-list-loading",""),a.innerHTML="";for(let l=0;l<zn.length;l++){let c=zn[l],d=document.createElement("span");d.setAttribute("data-aia-pill-skeleton",""),d.className=`magicx-aia-pill magicx-aia-pill--skeleton${o?" magicx-aia-pill--rounded":""}`,d.style.width=`${c}px`,d.style.opacity=String(Xn(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,f=["magicx-aia-pill"];o&&f.push("magicx-aia-pill--rounded"),r&&f.push("magicx-aia-pill--skeleton"),u.className=f.join(" "),u.style.width="",u.style.opacity=String(Xn(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 At(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var wo=32;function Jn(n,e){if(e.ctrlKey)return null;let t=e.deltaY||0,i=e.deltaX||0;if(!t||Math.abs(i)>=Math.abs(t))return null;let o=n.scrollWidth-n.clientWidth;if(o<=1)return null;let r=n.scrollLeft,s=t;return e.deltaMode===1?s*=32:e.deltaMode===2&&(s*=n.clientWidth),Math.max(0,Math.min(o,r+s))}function It(n){let e=t=>{let i=Jn(n,t);i!==null&&(t.preventDefault(),n.scrollLeft=i)};return n.addEventListener("wheel",e,{passive:!1}),()=>n.removeEventListener("wheel",e)}var Rt=new WeakMap,Po="Products";function Zn(n,e,t,i,o,r="row"){let s=n.querySelector(".magicx-aia-products");if(e.length===0){s?.remove();return}if(!s){s=document.createElement("section"),s.className="magicx-aia-products",s.setAttribute("data-aia-products",""),s.setAttribute("role","group"),s.setAttribute("aria-labelledby",`${t}-products-label`);let l=document.createElement("div");l.className="magicx-aia-products-label",l.id=`${t}-products-label`,l.setAttribute("data-aia-products-label",""),l.textContent=Po;let c=document.createElement("div");c.className="magicx-aia-products-row",c.setAttribute("data-aia-products-row",""),It(c),s.append(l,c),n.appendChild(s)}s.setAttribute("data-aia-products-layout",r);let a=s.querySelector(".magicx-aia-products-row");if(a){W(a,e,{keyOf:l=>Eo(l),create:l=>To(l,i,o),update:(l,c,d)=>{l.id=`${t}-product-${d}`,l.dataset.aiaIndex=String(d)}}),B(a);for(let l of a.querySelectorAll("[data-aia-product]")){let c=Rt.get(l);c&&(Rt.delete(l),c())}}}function Dt(n,e){let t=n.querySelectorAll("[data-aia-product]");for(let i of t)i.tabIndex=e?0:-1}function Eo(n){return[n.id,n.title,n.url,n.imageUrl,n.price,n.vendor].map(e=>e??"").join("\0")}function To(n,e,t){let i=document.createElement("a");i.className="magicx-aia-product",i.setAttribute("data-aia-product",""),i.setAttribute("role","option"),i.setAttribute("aria-selected","false"),i.tabIndex=0;let o=document.createElement("span");if(o.className="magicx-aia-product-media",n.imageUrl){let a=document.createElement("img");a.className="magicx-aia-product-image",a.src=n.imageUrl,a.alt="",a.loading="lazy",a.decoding="async",o.appendChild(a)}else o.setAttribute("data-aia-product-placeholder","");i.appendChild(o);let r=document.createElement("span");if(r.className="magicx-aia-product-body",n.vendor){let a=document.createElement("span");a.className="magicx-aia-product-vendor",a.textContent=n.vendor,r.appendChild(a)}let s=document.createElement("span");if(s.className="magicx-aia-product-title",s.textContent=n.title,r.appendChild(s),n.price){let a=document.createElement("span");a.className="magicx-aia-product-price",a.textContent=n.price,r.appendChild(a)}return i.appendChild(r),Rt.set(i,()=>{n.url&&(i.href=n.url),i.addEventListener("click",a=>{a.metaKey||a.ctrlKey||a.shiftKey||a.altKey||a.button!==0||(a.preventDefault(),e(n))})}),i.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),e(n))}),i.addEventListener("focus",()=>t(!0)),i.addEventListener("blur",a=>{a.relatedTarget?.closest("[data-aia-dropdown]")||t(!1)}),i}var Co=80,Oo=150,Ao=280,Io=16,Lt="--aia-option-enter-delay";function Mt(n,e,t,i="below"){let o=Math.max(1,Math.floor(e)),r=Math.floor(Math.max(0,n)/o);if(i!=="above")return r*80;let s=Math.max(1,Math.ceil(Math.max(0,t)/o));return Math.max(0,s-1-r)*80}function kt(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 $(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 fe(n){return n===void 0||!Number.isInteger(n)||n<0?null:n.toLocaleString()}var ei={one:"item",other:"items"};function Ro(n,e=ei){let t=fe(n);if(t===null)return null;let i=typeof e=="string"?e:n===1?e.one:e.other;return i===""?t:`${t} ${i}`}function Do(n){return $(n.image_url)!==null}var ti="http://www.w3.org/2000/svg",Lo=new Set(["svg","g","path","circle","ellipse","line","polyline","polygon","rect"]);function Mo(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 ko=["fill","stroke","stroke-width","stroke-linecap","stroke-linejoin","fill-rule","clip-rule","opacity","fill-opacity","stroke-opacity"],_o=/^[a-zA-Z0-9#.,%\s()-]+$/;function No(n){let e=[];for(let t of ko){let i=n.getAttribute(t);i===null||!_o.test(i)||/url\s*\(/i.test(i)||e.push(`${t}: ${i.trim()}`)}e.length>0&&n.setAttribute("style",e.join("; "))}function ni(n){for(let e of Array.from(n.attributes))Mo(e.name,e.value)&&n.removeAttribute(e.name);No(n);for(let e of Array.from(n.childNodes))if(e.nodeType===Node.ELEMENT_NODE){let t=e;!Lo.has(t.localName)||t.namespaceURI!==ti?t.remove():ni(t)}else e.remove()}function ge(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!==ti||e.getElementsByTagName("parsererror").length>0?null:(ni(t),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false"),new XMLSerializer().serializeToString(t))}function _t(n){return n.text}function Fo(n,e,t){let i=Pt(),o=!t&&xt(e,i)?wt(n):null,r=vt(e,i,o?.rowWidths??null,o?.gridWidth??null);return n.style.gridTemplateColumns=r.template,n.style.setProperty("--aia-grid-max-height",r.maxHeight),n.querySelectorAll("[data-aia-option]").forEach((s,a)=>{s.classList.toggle("magicx-aia-option--scroll-hint",!t&&r.scrollHintIndices.includes(a))}),r.cols}function ii(n,e){if(e.loading||!e.interactive)return null;let t=e.options[ie(n)];return t?.is_tappable?t:null}var Ho={itemSelector:"[data-aia-option]",onClick:(n,e)=>{let t=ii(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)=>{ii(n,e)&&e.onHighlight(ie(n))}};function oi(n,e,t,i,o,r,s,a="",l="below",c=!0,d=!0,u=!0,m=!0){let f=n.querySelector(".aia-grid");if(e.length===0){f?.remove();return}f||(f=document.createElement("div"),f.className="aia-grid magicx-aia-grid",f.setAttribute("data-scroll",""),f.style.setProperty("--aia-grid-min","250px"),f.style.setProperty("--aia-grid-max","1fr"),f.style.setProperty("--aia-grid-gap","0"),n.appendChild(f)),H(f,Ho,{options:e,onSelect:i,onHighlight:o,loading:s,interactive:m});let h=f.dataset.aiaGroup!==a;f.dataset.aiaGroup=a,Bo(f,e,t,r,s,{showIcons:c,showImages:d,showCounts:u});let S=Fo(f,e.length,s);Wo(f,e.length,S,s,l),h&&(f.scrollTop=0)}function Bo(n,e,t,i,o,r){let s=o?"1":"0",a=n.dataset.aiaGroup??"",{showIcons:l,showImages:c,showCounts:d}=r,u=l?h=>h.icon??h.icon_svg??"":()=>"",m=c?h=>$(h.image_url)??"":()=>"",f=d?h=>fe(h.item_count)??"":()=>"";W(n,e,{keyOf:h=>`${h.text}\0${u(h)}\0${m(h)}\0${f(h)}\0${s}\0${a}`,create:(h,S)=>{let v=$o(h,o,r);return o||(v.dataset.aiaEntering=""),v},update:(h,S,v)=>{let g=v===t&&!o;h.id=`${i}-option-${v}`,h.dataset.aiaIndex=String(v),h.setAttribute("aria-selected",String(g)),h.classList.toggle("magicx-aia-option--highlighted",g)}})}function Wo(n,e,t,i,o){for(let r of n.querySelectorAll("[data-aia-entering]")){if(!i){let s=Number.parseInt(r.dataset.aiaIndex??"-1",10);s>=0&&r.style.setProperty(Lt,`${Mt(s,t,e,o)}ms`)}delete r.dataset.aiaEntering}}function $o(n,e,{showIcons:t,showImages:i,showCounts:o}){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=i?$(n.image_url):null;if(l){let m=document.createElement("span");m.className="magicx-aia-option-image",m.setAttribute("aria-hidden","true");let f=document.createElement("img");f.setAttribute("alt",""),f.setAttribute("loading","lazy"),f.setAttribute("decoding","async"),f.setAttribute("referrerpolicy","no-referrer"),f.setAttribute("draggable","false"),f.onerror=()=>{f.hidden=!0},f.src=l,m.appendChild(f),a.appendChild(m),r.dataset.aiaImage=""}let c=!l&&t&&n.icon_svg?ge(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=_t(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=o?fe(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 ri="magicx-aia-scroll-arrow",si="data-aia-scroll-arrow",oe="data-aia-visible",ai=1e3,li=160,di="--aia-scroll-arrow-bottom",ci="Scroll down for more options",Go="[data-aia-products-label]",qo=4,Uo=8,Vo=240;function Ko(n,e,t,i){let o=n.scrollTop,r=t?.requestAnimationFrame,s=n.ownerDocument?.visibilityState==="hidden";if(!r||s||Nt(n)){n.scrollTop=o+e,i();return}let a=t.performance?.now?.()??Date.now(),l=()=>t.performance?.now?.()??Date.now(),c=()=>{let d=Math.min(1,(l()-a)/Vo),u=1-(1-d)*(1-d);n.scrollTop=o+e*u,d<1?r.call(t,c):i()};r.call(t,c)}function Qo(n=document){let e="http://www.w3.org/2000/svg",t=n.createElementNS(e,"svg");t.setAttribute("viewBox","0 0 16 16"),t.setAttribute("width","18"),t.setAttribute("height","18"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.75"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let i=n.createElementNS(e,"path");return i.setAttribute("d","M4 6.5 8 10.5l4-4"),t.appendChild(i),t}function ui(n=document){let e=n.createElement("button");return e.type="button",e.tabIndex=-1,e.className=ri,e.setAttribute(si,""),e.setAttribute("aria-label",ci),e.setAttribute("aria-hidden","true"),e.disabled=!0,e.appendChild(Qo(n)),e}function Yo(n){let e=n.style.gridTemplateColumns.trim();return e?Math.max(1,e.split(/\s+/).length):1}function Nt(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function Ft({dropdown:n,grid:e,button:t}){let i=e.ownerDocument?.defaultView??(typeof window<"u"?window:null),o=!1;t.disabled=!0;let r=null,s=null,a=null,l=null,c=p=>{if(p){if(t.hasAttribute(oe))return;if(t.setAttribute(oe,""),t.setAttribute("aria-hidden","false"),l!==null&&clearTimeout(l),Nt(e)){t.disabled=!1;return}l=setTimeout(()=>{l=null,!o&&t.hasAttribute(oe)&&(t.disabled=!1)},ai)}else t.removeAttribute(oe),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(Go),b;if(p){let y=d(p)+p.offsetHeight/2;b=n.clientHeight-y-t.offsetHeight/2}else{let y=d(e),x=i&&Number.parseFloat(i.getComputedStyle(e).paddingBottom)||0;b=n.clientHeight-(y+e.offsetHeight)+(x>0?0:Uo)}t.style.setProperty(di,`${Math.max(0,Math.round(b))}px`)},m=()=>{if(o||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>qo)},f=()=>{if(o)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=Nt(e)?0:kt(b,Yo(e));s=setTimeout(()=>{s=null,m()},y);return}m()},h=()=>{o||s!==null||(c(!1),a!==null&&clearTimeout(a),a=setTimeout(()=>{a=null,m()},li))};e.addEventListener("scroll",h,{passive:!0});let S=p=>p.preventDefault(),v=()=>{let p=i?(Number.parseFloat(i.getComputedStyle(e).paddingTop)||0)+(Number.parseFloat(i.getComputedStyle(e).paddingBottom)||0):0,b=Math.max(1,e.clientHeight-p);Ko(e,b,i,h)};t.addEventListener("mousedown",S),t.addEventListener("click",v);let g=null;return i&&typeof i.ResizeObserver=="function"&&(g=new i.ResizeObserver(()=>{u(),m()}),g.observe(e)),f(),{update:f,destroy(){o||(o=!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),g?.disconnect(),t.removeAttribute(oe),t.setAttribute("aria-hidden","true"))}}}var jo=[159,119,164];function Ve(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 Ue=new WeakMap;function zo(n,e){let t=Ue.get(n);if(t||(t={button:ui(n.ownerDocument),grid:null,controller:null},n.appendChild(t.button),Ue.set(n,t)),t.grid!==e&&(t.controller?.destroy(),t.controller=null,t.grid=e,e)){t.controller=Ft({dropdown:n,grid:e,button:t.button});return}t.controller?.update()}function Ht(n){let e=Ue.get(n);e&&(e.controller?.destroy(),Ue.delete(n))}function Ke(n,e){let{filteredOptions:t,activeIndex:i,isOpen:o,isLoading:r,pills:s,showPills:a,isActivePillSelected:l,onSelect:c,onHighlight:d,onPillClick:u,onSkip:m}=e,f=s.length>0,h=a&&f,S=t.length>0,v=e.products.length>0,g=o&&(S||h||r||v);if(g?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"),!g){Dt(n,!1);return}v?n.setAttribute("data-aia-has-products",""):n.removeAttribute("data-aia-has-products");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&&f&&!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 w=x.querySelector(".magicx-aia-pill-scroll");w||(w=document.createElement("span"),w.className="magicx-aia-pill-scroll",w.setAttribute("data-aia-pill-scroll",""),x.insertBefore(w,x.firstChild)),qe(w,a?s:[],0,u,!0,r&&a,l),Zo(x,b,r||e.skipDisabled,s[0],m)}else x&&x.remove();let E=e.suggestions[0],A=E?`${E.type} ${E.text}`:"",L=P(e.formatType),T=L&&!r;oi(p,L?[]:t,i,c,d,e.listboxId,r,A,e.optionsPosition??"below",e.showOptionIcons??!0,e.showOptionImages??!0,e.showOptionCounts??!0,!e.skipDisabled),zo(n,p.querySelector(".aia-grid")),jn(p,T?t:[],i,e.listboxId,T?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 I=p.querySelector(".magicx-aia-skeleton-bars");if(r&&(!S||L)){if(!I){I=document.createElement("div"),I.className="magicx-aia-skeleton-bars",I.setAttribute("data-aia-skeleton-bars","");for(let w of jo){let k=document.createElement("span");k.className="magicx-aia-skeleton-bar",k.style.width=`${w}px`,I.appendChild(k)}p.appendChild(I)}}else I&&I.remove();Zn(p,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange,e.productsLayout??"row"),Dt(n,!0);let C=p.querySelector(".magicx-aia-footer")??tr(),ze=i>=0&&!!t[i]?.is_tappable;er(C,Tt(ze,e.isInputEmpty)),C.isConnected||p.appendChild(C),Xo(p,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-datepicker",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"])}function Xo(n,e){let t=e.map(i=>n.querySelector(`:scope > ${i}`)).filter(i=>i!==null);for(let i=0;i<t.length;i++)n.children[i]!==t[i]&&n.insertBefore(t[i],n.children[i]??null)}var Jo={itemSelector:".magicx-aia-skip",onClick:(n,e)=>{e.loading||e.onSkip()}};function Zo(n,e,t,i,o){H(n,Jo,{onSkip:o,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",i?`Skip ${i.text}`:"Skip"),r.disabled=t}function er(n,{key:e,hint:t}){let i=n.querySelector(".magicx-aia-footer-key"),o=n.querySelector(".magicx-aia-footer-hint");!i||!o||(i.textContent!==e&&(i.textContent=e),o.textContent!==t&&(o.textContent=t))}function tr(){let n=document.createElement("footer");n.className="magicx-aia-footer",n.setAttribute("data-aia-footer","");let e=document.createElement("div");e.className="aia-cluster magicx-aia-footer-row",e.setAttribute("data-align","center"),e.setAttribute("data-justify","between"),e.setAttribute("data-nowrap","");let t=document.createElement("div");t.className="aia-cluster magicx-aia-footer-hint-group",t.setAttribute("data-align","center"),t.style.setProperty("--aia-cluster-gap","5px");let i=document.createElement("kbd");i.className="magicx-aia-footer-key",i.textContent="tab";let o=document.createElement("span");o.className="magicx-aia-footer-hint",o.textContent="to select",t.append(i,o);let r=document.createElement("a");r.className="aia-cluster magicx-aia-footer-brand-link",r.setAttribute("data-align","center"),r.href=Et(),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 pi(n,e){let t=Ve(e.listboxId);return n.appendChild(t),{dropdown:t}}function Bt(n,e,t){let i=me(e);Ke(n.dropdown,{suggestions:e.editingIdentified?[{type:e.editingIdentified.type,text:G(e.editingIdentified.type),required:!0,options:e.filteredOptions}]:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation||e.isSearchingOptions,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,showSkipButton:t.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:t.showOptionIcons??!0,showOptionImages:t.showOptionImages??!0,showOptionCounts:t.showOptionCounts??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,productsLayout:t.productsLayout??"row",formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:i.selectedIso,selectedDateRange:i.selectedRange,dateRangeStart:i.rangeStart,optionsPosition:t.optionsPosition??"below",onSelect:t.selectOption,onHighlight:o=>t.store.set({activeDropdownIndex:o}),onPillClick:t.setActivePill,onSkip:t.skipActivePill,onPreviousMonth:t.showPreviousMonth,onNextMonth:t.showNextMonth,onProductSelect:t.selectProduct,onProductFocusChange:o=>t.store.set({isFocused:o})})}var nr=6,ir=.3;function mi(n){return n<=0?"0px":`${(-Math.min(ir,2*nr/n)).toFixed(3)}px`}function Wt(n){let{input:e,segments:t,newParamId:i,editingParamId:o,placeholderText:r,isFocused:s}=n,a=n.showChipIcons??!0,l=n.showChipImages??!0,c=t.length===0;e.dataset.aiaEmpty=c?"true":"false",$n(e,c?r:"");let d=t.map(p=>p.type==="completed"?`${p.type}:${p.value}${a?p.param.icon??p.param.icon_svg??"":""}${l?$(p.param.image_url)??"":""}`:`${p.type}:${p.value}`).join("\0"),u=e.dataset.segKey??"",m=e.dataset.newParamId??"",f=e.dataset.editingParamId??"";if(d===u&&(i??"")===m&&(o??"")===f)return;if(d===u){e.dataset.newParamId=i??"",e.dataset.editingParamId=o??"";for(let p of e.querySelectorAll("strong[data-param-id]")){let b=p.dataset.paramId,y=p.dataset.seg==="completed"&&b===i;p.classList.toggle("magicx-aia-shimmer-revealed",y),p.classList.toggle("magicx-aia-shimmer-sweep",y),p.classList.toggle("magicx-aia-segment--editing",b===o)}return}let h=s?_(e):null;e.dataset.segKey=d,e.dataset.newParamId=i??"",e.dataset.editingParamId=o??"";let S=O(e),v=S.createDocumentFragment(),g=0;for(let p of t)if(g+=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===i,x=p.param.id===o,E=["magicx-aia-segment","magicx-aia-segment--completed"];y&&E.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),x&&E.push("magicx-aia-segment--editing"),b.className=E.join(" "),b.style.letterSpacing=mi(p.value.length);let A=l?$(p.param.image_url):null;if(A){let T=S.createElement("span");T.className="magicx-aia-segment-image",T.setAttribute("contenteditable","false"),T.setAttribute("aria-hidden","true"),T.style.setProperty("--aia-chip-image",`url("${A}")`),b.appendChild(T),b.dataset.aiaImage=""}let L=!A&&a&&p.param.icon_svg?ge(p.param.icon_svg):null;if(L){let T=S.createElement("span");T.className="magicx-aia-segment-icon",T.setAttribute("contenteditable","false"),T.setAttribute("aria-hidden","true"),T.innerHTML=L,b.appendChild(T),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===o&&y.push("magicx-aia-segment--editing"),b.className=y.join(" "),b.style.letterSpacing=mi(p.value.length),b.textContent=p.value,v.appendChild(b)}else v.appendChild(S.createTextNode(p.value));e.replaceChildren(v),e.dataset.aiaTextLength=String(g),h!=null?D(e,Math.max(0,Math.min(h,g))):s&&Rn(e)&&D(e,g)}var or='<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 fi(){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=or,n}function rr(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function gi(n,e){let t=e.firstElementChild;if(!t){e.removeAttribute("data-aia-pill-wrapped");return}let i=t.getBoundingClientRect(),o=n.getBoundingClientRect();i.top>=o.bottom-2?e.setAttribute("data-aia-pill-wrapped",""):e.removeAttribute("data-aia-pill-wrapped")}function hi(n,e){let{listboxId:t}=e,i=Ve(t);n.appendChild(i);let o=document.createElement("div");o.className="magicx-aia-input-wrapper",o.setAttribute("data-aia-input-wrapper",""),n.appendChild(o);let r=document.createElement("div");r.className="magicx-aia-editor",r.setAttribute("data-aia-editor",""),o.appendChild(r);let s=document.createElement("div");s.className="magicx-aia-input",s.setAttribute("data-aia-input",""),s.setAttribute("contenteditable",rr()?"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=fi(),o.appendChild(l),c=l):e.submitButton!==null&&(c=e.submitButton,c.hasAttribute("data-aia-submit")||c.setAttribute("data-aia-submit",""),c.setAttribute("data-aia-submit-slot",""),o.appendChild(c));let d=new AbortController,{signal:u}=d,m=!1,f=0,h=()=>{let g=Me(s),b=g.length>0&&g[0]!==g[0].toUpperCase()?g[0].toUpperCase()+g.slice(1):g;e.handleChange(b)},S=()=>{let g=Y(s)?.node??null;if(!g||!s.contains(g))return null;let y=(g.nodeType===Node.ELEMENT_NODE?g:g.parentElement)?.closest("strong[data-param-id]")?.dataset.paramId??null;return y&&In(s,y)?null:y};if(o.addEventListener("click",g=>{g.target?.closest("[data-aia-pill]")||s.focus()},{signal:u}),s.addEventListener("input",()=>{m||(f=performance.now(),h(),e.handleCaretAfterInput(_(s)))},{signal:u}),O(s).addEventListener("selectionchange",()=>{let g=Y(s);if(!g||!s.contains(g.node))return;let p=g.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()-f<50||e.handleCaretMove(_(s))},{signal:u}),s.addEventListener("compositionstart",()=>{m=!0},{signal:u}),s.addEventListener("compositionend",()=>{m=!1,h()},{signal:u}),s.addEventListener("beforeinput",g=>{let p=g,b=p.inputType;if(b==="insertParagraph"||b==="insertLineBreak"||b==="insertFromDrop"){g.preventDefault();return}if(b.startsWith("insert")||b.startsWith("delete")){let y=b.startsWith("delete")?"":p.data??"";e.replaceEditingRange(y)&&g.preventDefault()}},{signal:u}),s.addEventListener("paste",g=>{g.preventDefault();let p=(g.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!p)return;let b=O(s),y=Ae(s);if(!y||!s.contains(y.startContainer))return;y.deleteContents();let x=b.createTextNode(p);y.insertNode(x),y.setStartAfter(x),ue(s,y.startContainer,y.startOffset),h()},{signal:u}),s.addEventListener("keydown",g=>e.handleKeyDown(g),{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",g=>{let p=e.store.get();if(!(!!p.text||p.completedParams.length>0)||!e.onSubmit)return;g.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 g=Y(s);(!g||!s.contains(g.node))&&ue(s,s,0)}if(typeof ResizeObserver<"u"){let g=new ResizeObserver(()=>gi(s,a));g.observe(s),d.signal.addEventListener("abort",()=>g.disconnect(),{once:!0})}return{input:s,inlinePillContainer:a,dropdown:i,submitButton:l,abort:d}}function $t(n,e,t){let{input:i,inlinePillContainer:o,dropdown:r,submitButton:s}=n,{pillPlacement:a,setActivePill:l,selectOption:c,store:d}=t;i.setAttribute("aria-expanded",String(e.isDropdownOpen));let u=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(u?i.setAttribute("aria-activedescendant",u):i.removeAttribute("aria-activedescendant"),s){let g=!!e.text||e.completedParams.length>0;s.disabled=!g}let m=i.dataset.newParamId??"",f=e.newParamId!==null&&e.newParamId!==m;if(Wt({input:i,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 g=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;g||e.actionableSuggestions.length>0?qe(o,e.actionableSuggestions,0,l,!1,g,e.isActivePillSelected):At(o)}else At(o);gi(i,o),f?(i.focus(),D(i,e.caretOffset??e.text.length)):e.isFocused&&Me(i)!==e.text&&D(i,e.text.length);let h=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:e.editingIdentified?{type:e.editingIdentified.type,text:G(e.editingIdentified.type),required:!0,options:[]}:null,S=h??e.actionableSuggestions[0],v=me(e);Ke(r,{suggestions:S?[{...S,options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation||e.isSearchingOptions,listboxId:t.listboxId,pills:h?[h]:e.actionableSuggestions,showPills:a==="dropdown",showSkipButton:t.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:t.showOptionIcons??!0,showOptionImages:t.showOptionImages??!0,showOptionCounts:t.showOptionCounts??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,productsLayout:t.productsLayout??"row",formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:v.selectedIso,selectedDateRange:v.selectedRange,dateRangeStart:v.rangeStart,optionsPosition:t.optionsPosition??"below",onSelect:c,onHighlight:g=>d.set({activeDropdownIndex:g}),onPillClick:l,onSkip:t.skipActivePill,onPreviousMonth:t.showPreviousMonth,onNextMonth:t.showNextMonth,onProductSelect:t.selectProduct,onProductFocusChange:g=>d.set({isFocused:g})})}function bi(n,e){let t=n.actionableSuggestions[0];if(!t)return null;let i=n.filterBase,o=n.text.slice(0,i),r=o.length===0&&n.text.length===0,s=o.length===0&&n.text.length>0&&n.placeholderText.length>0&&n.placeholderText.toLowerCase().startsWith(n.text.toLowerCase());(r||s)&&n.placeholderText&&(o=`${n.placeholderText} `);let a=pn(o,e.text);a>0&&(o=o.slice(0,o.length-a));let l=o.length>0&&o[o.length-1]!==" ",c=`${o}${l?" ":""}${e.text} `,d=(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,f={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,f],newParamId:f.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 Gt(n){let e=n,t=new Set,i=[],o=!1;return{get:()=>e,set:r=>{let s=typeof r=="function"?r(e):r,a=e;if(e={...e,...s},i.push([e,a]),!o){o=!0;try{let l=0;for(let c=i.shift();c;c=i.shift()){if(++l>1e4)throw i.length=0,new Error("createStore: notifications did not settle after 10000 deliveries \u2014 a listener is likely calling set() on every notification");let[d,u]=c;for(let m of t)m(d,u)}}catch(l){throw i.length=0,l}finally{o=!1}}},subscribe:r=>(t.add(r),()=>{t.delete(r)})}}function yi(n,e){let t,i,o=r=>(r!==t&&(t=r,i=e(r)),i);return{get:()=>{let r=n.get();return{...r,...o(r)}},set:r=>{typeof r=="function"?n.set(s=>{let a={...s,...o(s)};return r(a)}):n.set(r)},peek:r=>{let s={...n.get(),...r};return{...s,...e(s)}},subscribe:r=>n.subscribe((s,a)=>{let l={...a,...o(a)},c={...s,...o(s)};r(c,l)})}}var qt=new WeakSet,Si=new WeakMap;function vi(n){return n.nodeType===Node.DOCUMENT_NODE}function sr(n){return vi(n)?n:n.ownerDocument}function ar(n){let e=Si.get(n);if(e)return e;let t=n.defaultView?.CSSStyleSheet;if(typeof t!="function")return null;try{let i=new t;return typeof i.replaceSync!="function"?null:(i.replaceSync(Pi),Si.set(n,i),i)}catch{return null}}function xi(n,e){if(e.querySelector("style[data-magicx-aia]"))return;let t=n.createElement("style");t.setAttribute("data-magicx-aia",""),t.textContent=Pi,e.appendChild(t)}function wi(n){if(typeof document>"u")return;let e=n??document;if(qt.has(e))return;let t=sr(e);if(vi(e)){let r=e.head??e.documentElement;if(!r)return;xi(t,r),qt.add(e);return}let i=ar(t),o=e.adoptedStyleSheets;i&&Array.isArray(o)?o.includes(i)||(e.adoptedStyleSheets=[...o,i]):xi(t,e),qt.add(e)}var Pi=`.aia-stack {
|
|
2
2
|
display: flex;
|
|
3
3
|
flex-direction: column;
|
|
4
4
|
gap: var(--aia-stack-space, 0.5rem);
|
|
@@ -110,8 +110,9 @@ function Ye(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9
|
|
|
110
110
|
10px the two sides would diverge; flooring both keeps them together. */
|
|
111
111
|
padding: 12px 16px 12px max(10px, var(--aia-content-inset-left, 16px));
|
|
112
112
|
border: 1px solid var(--aia-border, #b0b0b0);
|
|
113
|
-
border-radius:
|
|
113
|
+
border-radius: 10px;
|
|
114
114
|
background: var(--aia-surface, #ffffff);
|
|
115
|
+
/* Flat by default; consumers can set --aia-shadow for elevation. */
|
|
115
116
|
box-shadow: var(--aia-shadow, none);
|
|
116
117
|
overflow: hidden;
|
|
117
118
|
display: flex;
|
|
@@ -438,8 +439,9 @@ function Ye(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9
|
|
|
438
439
|
frosted-glass look with data-aia-surface="glass". */
|
|
439
440
|
background: var(--aia-surface, #ffffff);
|
|
440
441
|
border: 1px solid var(--aia-dropdown-border, rgba(231, 231, 231, 0.5));
|
|
441
|
-
border-radius:
|
|
442
|
-
|
|
442
|
+
border-radius: 9px;
|
|
443
|
+
/* Flat by default; consumers can set --aia-dropdown-shadow for elevation. */
|
|
444
|
+
box-shadow: var(--aia-dropdown-shadow, none);
|
|
443
445
|
}
|
|
444
446
|
|
|
445
447
|
.magicx-aia-dropdown[data-aia-surface="glass"] {
|
|
@@ -454,8 +456,7 @@ function Ye(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9
|
|
|
454
456
|
hsla(0, 0%, 100%, 0.15) 0px -1.6px 0px -1.6px inset,
|
|
455
457
|
hsla(0, 0%, 100%, 0.3) 0px 1.6px 0px 0px inset,
|
|
456
458
|
hsla(0, 0%, 100%, 0.3) 1.6px 0px 0px 0px inset,
|
|
457
|
-
inset 0 0 30px 5px hsla(0, 0%, 0%, 0.05)
|
|
458
|
-
hsla(0, 0%, 0%, 0.08) 0px 0px 30px 2px;
|
|
459
|
+
inset 0 0 30px 5px hsla(0, 0%, 0%, 0.05);
|
|
459
460
|
backdrop-filter: blur(30px);
|
|
460
461
|
}
|
|
461
462
|
|
|
@@ -866,6 +867,13 @@ function Ye(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9
|
|
|
866
867
|
opacity: 1;
|
|
867
868
|
}
|
|
868
869
|
|
|
870
|
+
/* Visible but not yet armed: the arrow is disabled for the length of its
|
|
871
|
+
fade-in (scrollArrow.ts \u2014 a native button appearing clickable cancels an
|
|
872
|
+
iOS tap in flight). No pointer cursor over a button that takes no click. */
|
|
873
|
+
.magicx-aia-scroll-arrow:disabled {
|
|
874
|
+
cursor: default;
|
|
875
|
+
}
|
|
876
|
+
|
|
869
877
|
/* The chevron's size and paint by class \u2014 see .magicx-aia-submit svg. */
|
|
870
878
|
.magicx-aia-scroll-arrow svg {
|
|
871
879
|
width: 14px;
|
|
@@ -898,7 +906,7 @@ function Ye(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9
|
|
|
898
906
|
badge sits as far from the right edge as it does from the bottom \u2014 12px
|
|
899
907
|
both ways (dropdown padding 10 + pill 2 down, dropdown padding 8 + pill 4
|
|
900
908
|
across). */
|
|
901
|
-
padding: var(--aia-footer-gap,
|
|
909
|
+
padding: var(--aia-footer-gap, 12px) 0 0 8px;
|
|
902
910
|
/* The fade itself lives in appearance.css, on the footer's background.
|
|
903
911
|
Paints above the rows it covers: option content sits at z-index 2 (see
|
|
904
912
|
.magicx-aia-option-content) in this same stacking context, so anything
|
|
@@ -1284,9 +1292,14 @@ function Ye(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9
|
|
|
1284
1292
|
}
|
|
1285
1293
|
}
|
|
1286
1294
|
|
|
1295
|
+
/* Starts a hair above zero on purpose. iOS reads an element at exactly
|
|
1296
|
+
\`opacity: 0\` as hidden, and a clickable element (a pill is a native button,
|
|
1297
|
+
a chip sits in the editable) going from hidden to visible while a finger is
|
|
1298
|
+
down cancels that tap \u2014 see delegatedEvents.ts. 0.01 is invisible and never
|
|
1299
|
+
"hidden". */
|
|
1287
1300
|
@keyframes magicx-aia-fadeIn {
|
|
1288
1301
|
from {
|
|
1289
|
-
opacity: 0;
|
|
1302
|
+
opacity: 0.01;
|
|
1290
1303
|
}
|
|
1291
1304
|
}
|
|
1292
1305
|
|
|
@@ -1324,13 +1337,13 @@ function Ye(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9
|
|
|
1324
1337
|
SuggestionItem selection. The 9px/10px inset is the item's own padding. */
|
|
1325
1338
|
border-radius: 8px;
|
|
1326
1339
|
padding: 8px 10px;
|
|
1327
|
-
/*
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1340
|
+
/* No entrance animation on the row itself \u2014 deliberately. The row is the
|
|
1341
|
+
tappable element, and iOS Safari drops a tap on a scripted-clickable
|
|
1342
|
+
element (a div with a click handler; a native button is exempt) whose
|
|
1343
|
+
own opacity is mid-animation \u2014 its tap-or-hover pass counts the change
|
|
1344
|
+
as content moving under the finger, fires only the hover events (the
|
|
1345
|
+
row highlights) and never the click. Both halves of the entrance run
|
|
1346
|
+
on the inner content instead (next rule). */
|
|
1334
1347
|
}
|
|
1335
1348
|
|
|
1336
1349
|
@keyframes magicx-aia-optionFadeIn {
|
|
@@ -1348,9 +1361,17 @@ function Ye(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9
|
|
|
1348
1361
|
.magicx-aia-option-content {
|
|
1349
1362
|
position: relative;
|
|
1350
1363
|
z-index: 2;
|
|
1351
|
-
/* The entrance
|
|
1352
|
-
|
|
1353
|
-
|
|
1364
|
+
/* The entrance: fade in while rising into place, each row a beat after the
|
|
1365
|
+
one before it (--aia-option-enter-delay is set inline per row from the
|
|
1366
|
+
core's optionEnterDelayMs). Both run here, on the inner content, never on
|
|
1367
|
+
the row: the rise because a transformed cell extends the grid's
|
|
1368
|
+
scrollable area (see the overflow note on the row), the fade because iOS
|
|
1369
|
+
Safari drops a tap on a tappable element whose own opacity is animating
|
|
1370
|
+
(see the row's own comment). The durations and distance mirror
|
|
1371
|
+
OPTION_ENTER_* in derive/optionsEntrance.ts \u2014 change both together. */
|
|
1372
|
+
animation:
|
|
1373
|
+
magicx-aia-optionRiseIn 280ms cubic-bezier(0.25, 0.46, 0.45, 0.94) both,
|
|
1374
|
+
magicx-aia-optionFadeIn 150ms ease-out both;
|
|
1354
1375
|
animation-delay: var(--aia-option-enter-delay, 0ms);
|
|
1355
1376
|
}
|
|
1356
1377
|
|
|
@@ -1788,15 +1809,14 @@ function Ye(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9
|
|
|
1788
1809
|
:where(.magicx-aia[data-mode="light"]) {
|
|
1789
1810
|
--aia-surface: var(--aia-primitive-neutral-1000);
|
|
1790
1811
|
--aia-border: rgba(17, 24, 39, 0.14); /* subtle slate hairline (off-palette) */
|
|
1791
|
-
/*
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
0 8px 24px rgba(16, 24, 40, 0.08);
|
|
1812
|
+
/* Flat by default \u2014 no elevation on the input container. Consumers set
|
|
1813
|
+
--aia-shadow to add one. */
|
|
1814
|
+
--aia-shadow: none;
|
|
1795
1815
|
/* Half-strength stroke: neutral-900 (was #e5e7eb \u2014 snapped to palette,
|
|
1796
1816
|
\u03942) at 50% alpha over the surface, so the hairline lands exactly
|
|
1797
1817
|
halfway between its old value and the white behind it. */
|
|
1798
1818
|
--aia-dropdown-border: var(--aia-primitive-neutral-900-a50);
|
|
1799
|
-
--aia-dropdown-shadow:
|
|
1819
|
+
--aia-dropdown-shadow: none; /* flat by default */
|
|
1800
1820
|
/* Suggestion pills (Figma "ParamPill"): transparent fill, no visible border;
|
|
1801
1821
|
per-pill opacity via getPillOpacity. --aia-pill-bg is retained for
|
|
1802
1822
|
consumer overrides but the default ParamPill no longer paints a fill. */
|
|
@@ -1844,15 +1864,13 @@ function Ye(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9
|
|
|
1844
1864
|
:where(.magicx-aia[data-mode="dark"]) {
|
|
1845
1865
|
--aia-surface: var(--aia-primitive-neutral-0);
|
|
1846
1866
|
--aia-border: var(--aia-primitive-neutral-500);
|
|
1847
|
-
/*
|
|
1848
|
-
|
|
1849
|
-
--aia-shadow:
|
|
1850
|
-
inset 0 1px 0 rgba(255, 255, 255, 0.06), 0 1px 2px rgba(0, 0, 0, 0.2),
|
|
1851
|
-
0 8px 24px rgba(0, 0, 0, 0.25);
|
|
1867
|
+
/* Flat by default \u2014 no elevation on the input container. Consumers set
|
|
1868
|
+
--aia-shadow to add one. */
|
|
1869
|
+
--aia-shadow: none;
|
|
1852
1870
|
/* Half-strength stroke \u2014 neutral-400 (was #484848 \u2014 snapped to palette,
|
|
1853
1871
|
\u03942) at 50% alpha; see the light-mode note above. */
|
|
1854
1872
|
--aia-dropdown-border: var(--aia-primitive-neutral-400-a50);
|
|
1855
|
-
--aia-dropdown-shadow:
|
|
1873
|
+
--aia-dropdown-shadow: none; /* flat by default */
|
|
1856
1874
|
/* Suggestion pills (Figma "ParamPill"): transparent fill, no visible border. */
|
|
1857
1875
|
--aia-pill-bg: var(--aia-primitive-neutral-750);
|
|
1858
1876
|
--aia-pill-color: var(--aia-primitive-neutral-700);
|
|
@@ -1912,7 +1930,7 @@ function Ye(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9
|
|
|
1912
1930
|
(the kbd is shorter and centers against it). The band derives from it, so
|
|
1913
1931
|
restyling the badge's height keeps the overlap in step. */
|
|
1914
1932
|
--aia-footer-row-height: 23px;
|
|
1915
|
-
--aia-footer-band: calc(var(--aia-footer-gap,
|
|
1933
|
+
--aia-footer-band: calc(var(--aia-footer-gap, 12px) + var(--aia-footer-row-height, 23px));
|
|
1916
1934
|
--aia-grid-scroll-bottom: var(--aia-footer-band);
|
|
1917
1935
|
--aia-grid-overlap-bottom: calc(-1 * (var(--aia-footer-band) + 8px));
|
|
1918
1936
|
/* How far above the band the fade starts. */
|
|
@@ -2020,7 +2038,7 @@ function Ye(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9
|
|
|
2020
2038
|
/* The footer now sits on top of the list, so its breathing room flips to the
|
|
2021
2039
|
bottom edge \u2014 the side the option rows scroll under. */
|
|
2022
2040
|
:where(.magicx-aia[data-options-position="above"]) [data-aia-dropdown] [data-aia-footer] {
|
|
2023
|
-
padding: 0 0 var(--aia-footer-gap,
|
|
2041
|
+
padding: 0 0 var(--aia-footer-gap, 12px) 8px;
|
|
2024
2042
|
}
|
|
2025
2043
|
|
|
2026
2044
|
/* ...and the fade runs the other way, out of the footer and down into the list. */
|
|
@@ -2050,5 +2068,5 @@ function Ye(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9
|
|
|
2050
2068
|
background: var(--aia-surface, #ffffff);
|
|
2051
2069
|
}
|
|
2052
2070
|
}
|
|
2053
|
-
`;var Ue=class{constructor(){this.reported=new Set}run(e,t){try{return t()}catch(i){this.report(e,i,e);return}}runListener(e,t,i=e){try{return t(),!0}catch(o){return this.report(e,o,i),!1}}report(e,t,i){this.reported.has(i)||(this.reported.add(i),console.error(`[AIAutocomplete] "${e}" threw. The error is contained \u2014 SDK state is unaffected. Later failures of "${e}" on this instance are not logged.`,t))}};var Ve=class{constructor(e){this.boundary=e;this.listeners={};this.keys=new WeakMap;this.registrationCount=0}on(e,t){let i=`${String(e)}#${++this.registrationCount}`,o=(...s)=>t(...s);this.keys.set(o,i);let r=this.listeners[e];return r||(r=new Set,this.listeners[e]=r),r.add(o),()=>{this.listeners[e]?.delete(o)}}emit(e,...t){let i=this.listeners[e];if(!i)return!0;let o=!0;for(let r of i)this.boundary.runListener(String(e),()=>r(...t),this.keys.get(r)??String(e))||(o=!1);return o}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var Ke=class{constructor(){this.timers=new Map}schedule(e,t,i){this.clear(e);let o=setTimeout(()=>{this.timers.delete(e),t()},i);this.timers.set(e,o)}clear(e){let t=this.timers.get(e);t!==void 0&&(clearTimeout(t),this.timers.delete(e))}clearAll(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};var pe=class{constructor(e,t="auto",i){this.container=e;this.mode=t;this.onResolve=i;this.mediaQuery=null;this.onSystemChange=e=>{this.setResolved(e.matches?"dark":"light")};this.apply()}setMode(e){this.detachListener(),this.mode=e,this.apply()}destroy(){this.detachListener()}apply(){this.mode==="auto"?(this.mediaQuery??(this.mediaQuery=window.matchMedia("(prefers-color-scheme: dark)")),this.mediaQuery.addEventListener("change",this.onSystemChange),this.setResolved(this.mediaQuery.matches?"dark":"light")):this.setResolved(this.mode)}setResolved(e){this.container.dataset.mode=e,this.onResolve?.(e)}detachListener(){this.mediaQuery?.removeEventListener("change",this.onSystemChange)}};function zo(n){return(n??be).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function Xo(n){return oe(n)?`Bearer ${await ye(n).getToken()}`:xe(n)}async function gi(n){try{let e=zo(n.apiConfig?.endpoint),t=Se(n.apiConfig),i=await Xo(n.apiConfig);i&&(t.Authorization=i);let o=JSON.stringify({source:n.source,session_id:n.sessionId,type:n.type,at:new Date().toISOString(),query_data:n.queryData});await fetch(e,{method:"POST",headers:t,body:o})}catch{}}var Jo="newParam",hi="suggestionRemoval",Zo="selectionAnimation",er=650,tr=0;function nr(){return`:ac-${++tr}:`}var bi=170;function yi(){return{text:"",completedParams:[],identifiedParams:[],skippedParams:[],pendingSpan:null,suggestions:[],products:[],customFields:null,optionSearch:null,activeDropdownIndex:-1,newParamId:null,isLoading:!1,isReady:!1,error:null,filterBase:0,filterInProgress:!1,pillTapped:!1,skipNextFetch:!1,lastRawQuery:"",isFocused:!1,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:null,inSelectionAnimation:!1,dateViewMonth:null,pendingRangeStart:null,editingIdentified:null}}var Bt=class{constructor(e,t={}){this.inputStore=Ft(yi());this._listboxId=nr();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new Ke;this.boundary=new Ue;this.subscriberCount=0;this.emitter=new Ve(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=di(this.inputStore,i=>Ln(i,this.opts)),t.onSubmit&&this.emitter.on("submit",t.onSubmit),t.onResult&&this.emitter.on("result",t.onResult),t.onError&&this.emitter.on("error",t.onError),t.onChange&&this.emitter.on("change",t.onChange),t.onParamsChange&&this.emitter.on("paramsChange",t.onParamsChange),t.onStateChange&&this.emitter.on("stateChange",t.onStateChange),t.onFocus&&this.emitter.on("focus",t.onFocus),t.onBlur&&this.emitter.on("blur",t.onBlur),t.onProductSelect&&this.emitter.on("productSelect",t.onProductSelect),t.value!==void 0&&this.store.set({text:t.value}),t.completedParams!==void 0&&this.store.set({completedParams:t.completedParams}),this.pillsController=new Le(this.store,{onPillSelected:({rawQuery:i,selectedPill:o,otherPills:r})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:o,other_pills:r})}}),this.reEdit=new Fe({store:this.store,scheduleSetCursor:i=>this.scheduleSetCursor(i),fireTelemetry:(i,o)=>this.fireTelemetry(i,o),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer(),fetchNow:()=>this.fetchNow()}),this.productsController=new Me(this.store,()=>this.opts.products,()=>this.opts.showProducts!==!1),this.optionSource=new De(this.store,()=>this.opts.optionOverrides,{onAnswer:i=>{i==="edit"?this.reEdit.promoteIfExact():this.maybePromoteExactMatch(this.store.get().text)},onMiss:(i,o)=>{i==="pill"&&o.length>0&&this.fetchController.attemptNow()}}),this.fetchController=new Pe(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.emitter.hasListeners("error")?this.emitError:void 0,()=>this.sessionId,()=>this.resolveSource(),()=>this.opts.additionalContext,{onRequest:({query:i,signal:o,isCurrent:r})=>{this.productsController.run(i,o,r).catch(()=>{})},onAutoMatch:({active:i,matched:o,rawQuery:r})=>{this.fireTelemetry("option",{raw_query:r,selected_option:o.text,other_options:(i.options??[]).filter(s=>s.text!==o.text).map(s=>s.text)})},onResponse:()=>{this.emitter.hasListeners("result")&&this.emitter.emit("result",this.buildResult())},productsForResponse:i=>this.productsController.forResponse(i),consumerTick:(i,o)=>this.optionSource.tick(i,o)}),this.keyboardController=new Re(this.store,{columns:t.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.emitter.hasListeners("submit")?this.emitSubmit:void 0,getOptionsPosition:()=>this.opts.optionsPosition??"below",afterSubmit:this.renderMode==="full"?()=>this.reset():void 0,selectOption:i=>this.selectOption(i),removeParamAtCaret:i=>this.removeParamAtCaret(i),startEditingParamAtCaret:i=>this.startEditingParamAtCaret(i),exitEditMode:()=>this.exitEditMode(),exitEditingIdentified:()=>this.exitEditingIdentified(),skipActivePill:()=>this.skipActivePill()}),this.unsubscribers.push(this.store.subscribe((i,o)=>{i.text!==o.text&&this.emitter.emit("change",i.text),i.completedParams!==o.completedParams&&this.emitter.emit("paramsChange",i.completedParams),i.isFocused!==o.isFocused&&(i.isFocused?this.emitter.emit("focus"):this.emitter.emit("blur")),this.emitter.emit("stateChange",i)})),this.unsubscribers.push(this.store.subscribe(()=>this.maybeExitReEditOnNoMatch())),this.unsubscribers.push(this.store.subscribe((i,o)=>{if(i.text===o.text&&i.completedParams===o.completedParams||i.identifiedParams.length===0)return;let{valid:r,invalid:s}=we(i.text,i.completedParams,i.identifiedParams);s.length>0&&this.store.set({identifiedParams:r})})),this.unsubscribers.push(this.store.subscribe((i,o)=>{if(i.identifiedParams===o.identifiedParams)return;let r=i.editingIdentified;if(!r||i.identifiedParams.some(l=>l.id===r.id))return;let s=0,a;for(let l of i.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(i=>{let o=i.pendingRangeStart;!o||o.key===le(i)||this.store.set({pendingRangeStart:null})})),this.unsubscribers.push(this.store.subscribe((i,o)=>{let r=i.pendingSpan;if(!r||i.text===o.text&&i.completedParams===o.completedParams&&i.identifiedParams===o.identifiedParams)return;let s=r.anchor;if(i.text!==o.text){let l=pn(o.text,i.text,s);if(l===null){this.store.set({pendingSpan:null});return}s=l}i.text.slice(s).trim().length===0||cn(i.segments,s)?this.store.set({pendingSpan:null}):s!==r.anchor&&this.store.set({pendingSpan:{anchor:s,snapshot:r.snapshot}})})),this.renderMode!=="headless"&&(mi(this.opts.styleRoot??V(this.container)),this.setupContainer()),this.renderMode==="full"?this.buildAndRenderFull():this.renderMode==="dropdown"&&this.buildAndRenderDropdown(),this.optionSource.start(),this.fetchController.start()}focus(){this.domRefs?.input.focus()}blur(){this.domRefs?.input.blur()}reset(){let e=this.store.get().isFocused;this.optionSource.reset(),this.store.set({...yi(),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&&(Fn(this.domRefs.input),Mt(this.domRefs.dropdown)),this.dropdownRefs&&Mt(this.dropdownRefs.dropdown),this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}setValue(e){let t=this.store.get();if(t.editingIdentified&&e!==t.text){this.store.set({text:e,editingIdentified:null,activeDropdownIndex:-1});return}this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e);let t=this.store.get().text.length;this.store.set({caretOffset:t,isFocused:!0}),this.scheduleSetCursor(t)}removeLastParam(){this.pillsController.removeLastParam()}findChipSpanAt(e){let t=0;for(let i of this.store.get().segments){let o=t;if(t+=i.value.length,i.type!=="text"&&e>o&&e<=t)return{kind:i.type,param:i.param,start:o,end:t}}return null}withoutChip(e,t){return t.kind==="completed"?{completedParams:e.completedParams.filter(i=>i.id!==t.param.id)}:{identifiedParams:e.identifiedParams.filter(i=>i.id!==t.param.id)}}removeParamAtCaret(e){let t=this.findChipSpanAt(e);if(!t)return!1;let{text:i}=this.store.get(),{start:o,end:r}=t;if(e===r){let{text:l,removed:c}=Ne(i,o,r);return this.store.set(d=>({text:l,filterBase:Math.min(d.filterBase>o?Math.max(o,d.filterBase-c):d.filterBase,l.length),...this.withoutChip(d,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(o),!0}let s=ut(i,e),a=i.slice(0,s)+i.slice(e);return this.store.set(l=>({text:a,filterBase:Math.min(l.filterBase,a.length),...this.withoutChip(l,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(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(),D(t.input,e);else{let i=this.opts.setCursor;i&&this.boundary.runListener("setCursor",()=>i(e))}})}clearNewParamId(){this.store.set({newParamId:null})}startEditingIdentified(e){let t=this.store.get();if(t.editingIdentified?.id===e)return!0;let i=t.identifiedParams.find(d=>d.id===e);if(!i)return!1;let o=G(i);if(!P(o))return!1;let r=z(i.text),s=o==="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+i.text.length;return this.store.set({editingIdentified:{id:e,type:i.type,anchor:l,tail:c,text:i.text,iso:r?r.start:nt(i),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(!P(t.activeFormatType)||!t.dateView)return;let i=Je(t.dateView,e);this.store.set({dateViewMonth:{...i,key:le(t)},activeDropdownIndex:-1})}skipActivePill(){let e=this.store.get();if(e.editingParam||e.inSelectionAnimation)return;let t=e.suggestions.filter(a=>a.type==="placeholder"),i=e.suggestions.filter(a=>a.type!=="placeholder");if(i.length===0)return;let o=i[0],r=i.slice(1),s=e.skippedParams.some(a=>a.type===o.type);this.store.set({suggestions:[...t,...r],pillTapped:r.length>0,activeDropdownIndex:-1,...s?{}:{skippedParams:[...e.skippedParams,{id:crypto.randomUUID(),type:o.type,suggestionPlaceholder:o.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(i=>{this.boundary.runListener("subscribe",()=>e(i),t)})}getState(){return this.store.get()}getResult(){return this.buildResult()}buildResult(){let e=this.store.get();return Q(e.text,e.completedParams,e.skippedParams,{identifiedParams:e.identifiedParams,isReady:e.isReady,customFields:e.customFields})}get listboxId(){return this._listboxId}get isReady(){return this.store.get().isReady}on(e,t){return this.emitter.on(e,t)}update(e){let t=this.opts.products,i=this.opts.showProducts,o=this.opts.optionOverrides;Object.assign(this.opts,e),"optionOverrides"in e&&e.optionOverrides!==o&&this.optionSource.refresh(),("products"in e&&e.products!==t||"showProducts"in e&&e.showProducts!==i)&&this.productsController.resync(),e.mode!==void 0&&this.modeController?.setMode(e.mode),e.optionsPosition!==void 0&&(this.container.dataset.optionsPosition=e.optionsPosition),e.animations!==void 0&&(this.container.dataset.animations=e.animations?"on":"off"),e.pillPlacement!==void 0&&(this.container.dataset.pillPlacement=e.pillPlacement,this.store.set({})),(e.dropdownTrigger!==void 0||e.closeDropdownOnBlur!==void 0||e.showNonTappableOptions!==void 0||e.showSkipButton!==void 0||e.showOptionIcons!==void 0||e.showOptionImages!==void 0||e.showOptionCounts!==void 0||e.productsLayout!==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 o=N(e);if(o){let r=t.dateRangeStart;if(!r){this.store.set({pendingRangeStart:{iso:o,key:le(t)}});return}this.store.set({pendingRangeStart:null}),this.selectOption(Zt(r,o));return}}if(t.editingIdentified){this.commitIdentifiedDate(e);return}if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null){this.reEdit.selectOption(e);return}let i=li(t,e);if(i){if(this.fireTelemetry("option",{raw_query:R(t.text,t.completedParams).rawQuery,selected_option:i.telemetry.selectedOption,other_options:P(t.activeFormatType)?[]:i.telemetry.otherOptions}),this.store.set(i.patch),this.startSelectionAnimationTimer(),this.timers.clear(hi),i.remainingActionable>0){let o=i.consumedSuggestion;this.timers.schedule(hi,()=>{this.store.get().suggestions.includes(o)&&this.store.set(r=>({suggestions:r.suggestions.filter(s=>s!==o)}))},bi)}this.fetchNow()}}startSelectionAnimationTimer(){this.timers.schedule(Zo,()=>this.store.set({inSelectionAnimation:!1}),bi)}resolveSource(){return this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk")}fireTelemetry(e,t){let i=this.resolveSource();gi({source:i,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}setupContainer(){this.container.classList.add("magicx-aia"),this.container.dataset.pillPlacement=this.renderMode==="dropdown"?"dropdown":this.opts.pillPlacement??"dropdown",this.container.dataset.optionsPosition=this.opts.optionsPosition??"below",this.container.dataset.animations=this.opts.animations??!0?"on":"off",this.modeController=new pe(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 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:o=>this.selectOption(o),setActivePill:o=>this.pillsController.setActivePill(o),skipActivePill:()=>this.skipActivePill(),selectProduct:o=>this.selectProduct(o),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth(),handleKeyDown:o=>this.keyboardController.handleKeyDown(o),handleChange:o=>this.handleChange(o),startEditingParam:o=>this.startEditingParam(o),handleCaretAfterInput:o=>this.handleCaretAfterInput(o),handleCaretMove:o=>this.handleCaretMove(o),replaceEditingRange:o=>this.replaceEditingRange(o)};this.domRefs=ai(this.container,t);let i=()=>{this.domRefs&&Nt(this.domRefs,this.store.get(),t)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),Nt(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 optionsPosition(){return e.opts.optionsPosition??"below"},selectOption:o=>this.selectOption(o),setActivePill:o=>this.pillsController.setActivePill(o),skipActivePill:()=>this.skipActivePill(),selectProduct:o=>this.selectProduct(o),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth()};this.dropdownRefs=ii(this.container,t);let i=()=>{this.dropdownRefs&&_t(this.dropdownRefs,this.store.get(),t)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),_t(this.dropdownRefs,this.store.get(),t),this.subscribeNewParamTimer()}subscribeViewportBreakpoint(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;let t=window.matchMedia(_e),i=()=>e();t.addEventListener("change",i),this.unsubscribers.push(()=>t.removeEventListener("change",i))}subscribeBatchedRender(e){let t=!1;this.unsubscribers.push(this.store.subscribe(()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,t)=>{e.newParamId&&e.newParamId!==t.newParamId&&this.timers.schedule(Jo,()=>this.store.set({newParamId:null}),er)}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:o}=gn(e,t.completedParams);o.length>0&&this.store.set({completedParams:i}),this.maybePromoteExactMatch(e),this.maybeOpenPendingSpan()}maybeOpenPendingSpan(){let e=this.store.get();if(e.pendingSpan||e.actionableSuggestions.length===0)return;let t=F(e.text,Math.min(e.filterBase,e.text.length),e.placeholderText),i=dn(e.segments,t);e.text.slice(i).trim().length!==0&&this.store.set({pendingSpan:{anchor:i,snapshot:e.actionableSuggestions}})}maybeExitReEditOnNoMatch(){let e=this.store.get();if(!e.editingParam||e.editingAnchor==null||e.completedParams.some(r=>r.id===e.editingParam?.id)||this.optionSource.owns(e.editingParam.suggestionType,e.optionQuery))return;let t=e.caretOffset??e.editingAnchor,i=e.text.slice(e.editingAnchor,t);U(e.editingParam.options,i).some(r=>r.is_tappable)||(this.reEdit.exit(),this.fetchNow())}fetchNow(){let e=this.store.get(),{rawQuery:t,completedParams:i}=R(e.text,e.completedParams);this.fetchController.doFetch(t,i)}commitIdentifiedDate(e){let t=this.store.get(),i=t.editingIdentified;if(!i)return;if(t.text.slice(i.anchor,i.tail)!==i.text){this.store.set({editingIdentified:null,activeDropdownIndex:-1});return}let o=t.text.slice(0,i.anchor),r=t.text.slice(i.tail),s=i.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=o+l+r,d=c.length,u={id:crypto.randomUUID(),placeholder:"",type:i.type,text:s,value:e.value,kind:e.kind,suggestionType:i.type,suggestionPlaceholder:W(i.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(p=>p.id!==i.id),newParamId:u.id,filterBase:d,caretOffset:d,editingIdentified:null,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.startSelectionAnimationTimer(),this.scheduleSetCursor(d),this.fetchNow()}maybePromoteExactMatch(e){let t=this.store.get();if(P(t.activeFormatType))return;let i=ke({mode:"fresh",text:e,completedParams:t.completedParams,suggestions:t.suggestions,filterBase:t.filterBase,filterInProgress:t.filterInProgress});i&&this.store.set(i.patch)}};export{Bt as AIAutocomplete,Hn as ATTRIBUTION_URL,rt as DATE_RANGE_META_END,ot as DATE_RANGE_META_START,Kn as DEFAULT_OPTION_COUNT_UNIT,pe as ModeController,_e as OPTIONS_GRID_MOBILE_QUERY,At as OPTION_ENTER_DELAY_VAR,ho as OPTION_ENTER_FADE_MS,bo as OPTION_ENTER_RISE_MS,yo as OPTION_ENTER_RISE_PX,go as OPTION_ENTER_STAGGER_MS,io as PLACEHOLDER_FADE_OUT_MS,Z as PLACEHOLDER_LEAVING_ATTR,oo as PLACEHOLDER_SWAP_GAP_MS,to as PLACEHOLDER_TYPE_MS,no as PLACEHOLDER_WORD_PAUSE_MS,On as PRODUCT_PATH_PREFIX,uo as PRODUCT_ROW_PX_PER_LINE,Xt as RANGE_SEPARATOR,Xn as SCROLL_ARROW_ATTR,Zn as SCROLL_ARROW_BOTTOM_VAR,zn as SCROLL_ARROW_CLASS,Ro as SCROLL_ARROW_FADE_MS,ei as SCROLL_ARROW_LABEL,Jn as SCROLL_ARROW_SCROLL_IDLE_MS,We as SCROLL_ARROW_VISIBLE_ATTR,nn as SKIPPED_PARAM_TEXT,me as WEEKDAY_LABELS,Je as addMonths,Ct as attachProductRowWheel,Lt as attachScrollArrow,vt as buildAttributionUrl,Ze as buildDateOptions,R as buildQuery,Q as buildSubmitResult,tt as cellDay,N as cellIso,In as computeOptionsGridLayout,Ft as createStore,ct as cursorIsAtEnd,Et as dateCellMarks,de as dateSelectionFor,Ie as extractPlainText,j as formatAbsoluteDate,Kt as formatDate,Jt as formatDateRange,ce as formatOptionCount,k as getCursorOffset,wt as getFooterHint,W as identifiedParamLabel,P as isCalendarFormat,xt as isOptionsGridMobileViewport,M as isoDate,St as measureOptionsGrid,ze as monthLabel,bt as needsOptionsGridMeasurement,So as optionCountLabel,It as optionEnterDelayMs,xo as optionHasImage,B as optionImageSrc,Dt as optionLabel,Rt as optionsEntranceDurationMs,ht as optionsGridTemplateColumns,fe as parseDate,$ as parseLooseDate,z as parseLooseDateRange,dt as plainTextLength,yt as planOptionsGrid,ut as previousGraphemeBoundary,An as productFromMatchedItem,Un as productRowWheelTarget,ft as productsFromCustomFields,kt as renderEditableContent,G as resolveFormatType,nt as resolveIdentifiedDate,ue as sanitizeOptionIconSvg,lt as scrollCaretIntoView,et as selectedIsoFromText,ie as selectedRangeFor,D as setCursorOffset,re as toWireIdentifiedParams,Pt as visibleDateRange,se as withSkippedParams};
|
|
2071
|
+
`;var Qe=class{constructor(){this.reported=new Set}run(e,t){try{return t()}catch(i){this.report(e,i,e);return}}runListener(e,t,i=e){try{return t(),!0}catch(o){return this.report(e,o,i),!1}}report(e,t,i){this.reported.has(i)||(this.reported.add(i),console.error(`[AIAutocomplete] "${e}" threw. The error is contained \u2014 SDK state is unaffected. Later failures of "${e}" on this instance are not logged.`,t))}};var Ye=class{constructor(e){this.boundary=e;this.listeners={};this.keys=new WeakMap;this.registrationCount=0}on(e,t){let i=`${String(e)}#${++this.registrationCount}`,o=(...s)=>t(...s);this.keys.set(o,i);let r=this.listeners[e];return r||(r=new Set,this.listeners[e]=r),r.add(o),()=>{this.listeners[e]?.delete(o)}}emit(e,...t){let i=this.listeners[e];if(!i)return!0;let o=!0;for(let r of i)this.boundary.runListener(String(e),()=>r(...t),this.keys.get(r)??String(e))||(o=!1);return o}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var je=class{constructor(){this.timers=new Map}schedule(e,t,i){this.clear(e);let o=setTimeout(()=>{this.timers.delete(e),t()},i);this.timers.set(e,o)}clear(e){let t=this.timers.get(e);t!==void 0&&(clearTimeout(t),this.timers.delete(e))}clearAll(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};var he=class{constructor(e,t="auto",i){this.container=e;this.mode=t;this.onResolve=i;this.mediaQuery=null;this.onSystemChange=e=>{this.setResolved(e.matches?"dark":"light")};this.apply()}setMode(e){this.detachListener(),this.mode=e,this.apply()}destroy(){this.detachListener()}apply(){this.mode==="auto"?(this.mediaQuery??(this.mediaQuery=window.matchMedia("(prefers-color-scheme: dark)")),this.mediaQuery.addEventListener("change",this.onSystemChange),this.setResolved(this.mediaQuery.matches?"dark":"light")):this.setResolved(this.mode)}setResolved(e){this.container.dataset.mode=e,this.onResolve?.(e)}detachListener(){this.mediaQuery?.removeEventListener("change",this.onSystemChange)}};function lr(n){return(n??ve).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function dr(n){return le(n)?`Bearer ${await we(n).getToken()}`:Ee(n)}async function Ei(n){try{let e=lr(n.apiConfig?.endpoint),t=Pe(n.apiConfig),i=await dr(n.apiConfig);i&&(t.Authorization=i);let o=JSON.stringify({source:n.source,session_id:n.sessionId,type:n.type,at:new Date().toISOString(),query_data:n.queryData});await fetch(e,{method:"POST",headers:t,body:o})}catch{}}var cr="newParam",Ti="suggestionRemoval",ur="selectionAnimation",pr=650,mr=0;function fr(){return`:ac-${++mr}:`}var Ci=170;function Oi(){return{text:"",completedParams:[],identifiedParams:[],skippedParams:[],pendingSpan:null,suggestions:[],products:[],customFields:null,optionSearch:null,activeDropdownIndex:-1,newParamId:null,isLoading:!1,isReady:!1,error:null,filterBase:0,filterInProgress:!1,pillTapped:!1,skipNextFetch:!1,lastRawQuery:"",isFocused:!1,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:null,inSelectionAnimation:!1,dateViewMonth:null,pendingRangeStart:null,editingIdentified:null}}var Ut=class{constructor(e,t={}){this.inputStore=Gt(Oi());this._listboxId=fr();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new je;this.boundary=new Qe;this.subscriberCount=0;this.emitter=new Ye(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=yi(this.inputStore,i=>Fn(i,this.opts)),t.onSubmit&&this.emitter.on("submit",t.onSubmit),t.onResult&&this.emitter.on("result",t.onResult),t.onError&&this.emitter.on("error",t.onError),t.onChange&&this.emitter.on("change",t.onChange),t.onParamsChange&&this.emitter.on("paramsChange",t.onParamsChange),t.onStateChange&&this.emitter.on("stateChange",t.onStateChange),t.onFocus&&this.emitter.on("focus",t.onFocus),t.onBlur&&this.emitter.on("blur",t.onBlur),t.onProductSelect&&this.emitter.on("productSelect",t.onProductSelect),t.value!==void 0&&this.store.set({text:t.value}),t.completedParams!==void 0&&this.store.set({completedParams:t.completedParams}),this.pillsController=new Ne(this.store,{onPillSelected:({rawQuery:i,selectedPill:o,otherPills:r})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:o,other_pills:r})}}),this.reEdit=new $e({store:this.store,scheduleSetCursor:i=>this.scheduleSetCursor(i),fireTelemetry:(i,o)=>this.fireTelemetry(i,o),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer(),fetchNow:()=>this.fetchNow()}),this.productsController=new Fe(this.store,()=>this.opts.products,()=>this.opts.showProducts!==!1),this.optionSource=new _e(this.store,()=>this.opts.optionOverrides,{onAnswer:i=>{i==="edit"?this.reEdit.promoteIfExact():this.maybePromoteExactMatch(this.store.get().text)},onMiss:(i,o)=>{i==="pill"&&o.length>0&&this.fetchController.attemptNow()}}),this.fetchController=new Oe(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.emitter.hasListeners("error")?this.emitError:void 0,()=>this.sessionId,()=>this.resolveSource(),()=>this.opts.additionalContext,{onRequest:({query:i,signal:o,isCurrent:r})=>{this.productsController.run(i,o,r).catch(()=>{})},onAutoMatch:({active:i,matched:o,rawQuery:r})=>{this.fireTelemetry("option",{raw_query:r,selected_option:o.text,other_options:(i.options??[]).filter(s=>s.text!==o.text).map(s=>s.text)})},onResponse:()=>{this.emitter.hasListeners("result")&&this.emitter.emit("result",this.buildResult())},productsForResponse:i=>this.productsController.forResponse(i),consumerTick:(i,o)=>this.optionSource.tick(i,o)}),this.keyboardController=new ke(this.store,{columns:t.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.emitter.hasListeners("submit")?this.emitSubmit:void 0,getOptionsPosition:()=>this.opts.optionsPosition??"below",afterSubmit:this.renderMode==="full"?()=>this.reset():void 0,selectOption:i=>this.selectOption(i),removeParamAtCaret:i=>this.removeParamAtCaret(i),startEditingParamAtCaret:i=>this.startEditingParamAtCaret(i),exitEditMode:()=>this.exitEditMode(),exitEditingIdentified:()=>this.exitEditingIdentified(),skipActivePill:()=>this.skipActivePill()}),this.unsubscribers.push(this.store.subscribe((i,o)=>{i.text!==o.text&&this.emitter.emit("change",i.text),i.completedParams!==o.completedParams&&this.emitter.emit("paramsChange",i.completedParams),i.isFocused!==o.isFocused&&(i.isFocused?this.emitter.emit("focus"):this.emitter.emit("blur")),this.emitter.emit("stateChange",i)})),this.unsubscribers.push(this.store.subscribe(()=>this.maybeExitReEditOnNoMatch())),this.unsubscribers.push(this.store.subscribe((i,o)=>{if(i.text===o.text&&i.completedParams===o.completedParams||i.identifiedParams.length===0)return;let{valid:r,invalid:s}=Ce(i.text,i.completedParams,i.identifiedParams);s.length>0&&this.store.set({identifiedParams:r})})),this.unsubscribers.push(this.store.subscribe((i,o)=>{if(i.identifiedParams===o.identifiedParams)return;let r=i.editingIdentified;if(!r||i.identifiedParams.some(l=>l.id===r.id))return;let s=0,a;for(let l of i.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(i=>{let o=i.pendingRangeStart;!o||o.key===pe(i)||this.store.set({pendingRangeStart:null})})),this.unsubscribers.push(this.store.subscribe((i,o)=>{let r=i.pendingSpan;if(!r||i.text===o.text&&i.completedParams===o.completedParams&&i.identifiedParams===o.identifiedParams)return;let s=r.anchor;if(i.text!==o.text){let l=bn(o.text,i.text,s);if(l===null){this.store.set({pendingSpan:null});return}s=l}i.text.slice(s).trim().length===0||gn(i.segments,s)?this.store.set({pendingSpan:null}):s!==r.anchor&&this.store.set({pendingSpan:{anchor:s,snapshot:r.snapshot}})})),this.renderMode!=="headless"&&(wi(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({...Oi(),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&&(Gn(this.domRefs.input),Ht(this.domRefs.dropdown)),this.dropdownRefs&&Ht(this.dropdownRefs.dropdown),this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}setValue(e){let t=this.store.get();if(t.editingIdentified&&e!==t.text){this.store.set({text:e,editingIdentified:null,activeDropdownIndex:-1});return}this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e);let t=this.store.get().text.length;this.store.set({caretOffset:t,isFocused:!0}),this.scheduleSetCursor(t)}removeLastParam(){this.pillsController.removeLastParam()}findChipSpanAt(e){let t=0;for(let i of this.store.get().segments){let o=t;if(t+=i.value.length,i.type!=="text"&&e>o&&e<=t)return{kind:i.type,param:i.param,start:o,end:t}}return null}withoutChip(e,t){return t.kind==="completed"?{completedParams:e.completedParams.filter(i=>i.id!==t.param.id)}:{identifiedParams:e.identifiedParams.filter(i=>i.id!==t.param.id)}}removeParamAtCaret(e){let t=this.findChipSpanAt(e);if(!t)return!1;let{text:i}=this.store.get(),{start:o,end:r}=t;if(e===r){let{text:l,removed:c}=We(i,o,r);return this.store.set(d=>({text:l,filterBase:Math.min(d.filterBase>o?Math.max(o,d.filterBase-c):d.filterBase,l.length),...this.withoutChip(d,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(o),!0}let s=ft(i,e),a=i.slice(0,s)+i.slice(e);return this.store.set(l=>({text:a,filterBase:Math.min(l.filterBase,a.length),...this.withoutChip(l,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(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(),D(t.input,e);else{let i=this.opts.setCursor;i&&this.boundary.runListener("setCursor",()=>i(e))}})}clearNewParamId(){this.store.set({newParamId:null})}startEditingIdentified(e){let t=this.store.get();if(t.editingIdentified?.id===e)return!0;let i=t.identifiedParams.find(d=>d.id===e);if(!i)return!1;let o=U(i);if(!P(o))return!1;let r=J(i.text),s=o==="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+i.text.length;return this.store.set({editingIdentified:{id:e,type:i.type,anchor:l,tail:c,text:i.text,iso:r?r.start:rt(i),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(!P(t.activeFormatType)||!t.dateView)return;let i=tt(t.dateView,e);this.store.set({dateViewMonth:{...i,key:pe(t)},activeDropdownIndex:-1})}skipActivePill(){let e=this.store.get();if(e.editingParam||e.inSelectionAnimation)return;let t=e.suggestions.filter(a=>a.type==="placeholder"),i=e.suggestions.filter(a=>a.type!=="placeholder");if(i.length===0)return;let o=i[0],r=i.slice(1),s=e.skippedParams.some(a=>a.type===o.type);this.store.set({suggestions:[...t,...r],pillTapped:r.length>0,activeDropdownIndex:-1,...s?{}:{skippedParams:[...e.skippedParams,{id:crypto.randomUUID(),type:o.type,suggestionPlaceholder:o.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(i=>{this.boundary.runListener("subscribe",()=>e(i),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,i=this.opts.showProducts,o=this.opts.optionOverrides;Object.assign(this.opts,e),"optionOverrides"in e&&e.optionOverrides!==o&&this.optionSource.refresh(),("products"in e&&e.products!==t||"showProducts"in e&&e.showProducts!==i)&&this.productsController.resync(),e.mode!==void 0&&this.modeController?.setMode(e.mode),e.optionsPosition!==void 0&&(this.container.dataset.optionsPosition=e.optionsPosition),e.animations!==void 0&&(this.container.dataset.animations=e.animations?"on":"off"),e.pillPlacement!==void 0&&(this.container.dataset.pillPlacement=e.pillPlacement,this.store.set({})),(e.dropdownTrigger!==void 0||e.closeDropdownOnBlur!==void 0||e.showNonTappableOptions!==void 0||e.showSkipButton!==void 0||e.showOptionIcons!==void 0||e.showOptionImages!==void 0||e.showOptionCounts!==void 0||e.productsLayout!==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 o=N(e);if(o){let r=t.dateRangeStart;if(!r){this.store.set({pendingRangeStart:{iso:o,key:pe(t)}});return}this.store.set({pendingRangeStart:null}),this.selectOption(rn(r,o));return}}if(t.editingIdentified){this.commitIdentifiedDate(e);return}if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null){this.reEdit.selectOption(e);return}let i=bi(t,e);if(i){if(this.fireTelemetry("option",{raw_query:R(t.text,t.completedParams).rawQuery,selected_option:i.telemetry.selectedOption,other_options:P(t.activeFormatType)?[]:i.telemetry.otherOptions}),this.store.set(i.patch),this.startSelectionAnimationTimer(),this.timers.clear(Ti),i.remainingActionable>0){let o=i.consumedSuggestion;this.timers.schedule(Ti,()=>{this.store.get().suggestions.includes(o)&&this.store.set(r=>({suggestions:r.suggestions.filter(s=>s!==o)}))},Ci)}this.fetchNow()}}startSelectionAnimationTimer(){this.timers.schedule(ur,()=>this.store.set({inSelectionAnimation:!1}),Ci)}resolveSource(){return this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk")}fireTelemetry(e,t){let i=this.resolveSource();Ei({source:i,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}setupContainer(){this.container.classList.add("magicx-aia"),this.container.dataset.pillPlacement=this.renderMode==="dropdown"?"dropdown":this.opts.pillPlacement??"dropdown",this.container.dataset.optionsPosition=this.opts.optionsPosition??"below",this.container.dataset.animations=this.opts.animations??!0?"on":"off",this.modeController=new he(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 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:o=>this.selectOption(o),setActivePill:o=>this.pillsController.setActivePill(o),skipActivePill:()=>this.skipActivePill(),selectProduct:o=>this.selectProduct(o),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth(),handleKeyDown:o=>this.keyboardController.handleKeyDown(o),handleChange:o=>this.handleChange(o),startEditingParam:o=>this.startEditingParam(o),handleCaretAfterInput:o=>this.handleCaretAfterInput(o),handleCaretMove:o=>this.handleCaretMove(o),replaceEditingRange:o=>this.replaceEditingRange(o)};this.domRefs=hi(this.container,t);let i=()=>{this.domRefs&&$t(this.domRefs,this.store.get(),t)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),$t(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 optionsPosition(){return e.opts.optionsPosition??"below"},selectOption:o=>this.selectOption(o),setActivePill:o=>this.pillsController.setActivePill(o),skipActivePill:()=>this.skipActivePill(),selectProduct:o=>this.selectProduct(o),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth()};this.dropdownRefs=pi(this.container,t);let i=()=>{this.dropdownRefs&&Bt(this.dropdownRefs,this.store.get(),t)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),Bt(this.dropdownRefs,this.store.get(),t),this.subscribeNewParamTimer()}subscribeViewportBreakpoint(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;let t=window.matchMedia(He),i=()=>e();t.addEventListener("change",i),this.unsubscribers.push(()=>t.removeEventListener("change",i))}subscribeBatchedRender(e){let t=!1;this.unsubscribers.push(this.store.subscribe(()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,t)=>{e.newParamId&&e.newParamId!==t.newParamId&&this.timers.schedule(cr,()=>this.store.set({newParamId:null}),pr)}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:o}=xn(e,t.completedParams);o.length>0&&this.store.set({completedParams:i}),this.maybePromoteExactMatch(e),this.maybeOpenPendingSpan()}maybeOpenPendingSpan(){let e=this.store.get();if(e.pendingSpan||e.actionableSuggestions.length===0)return;let t=F(e.text,Math.min(e.filterBase,e.text.length),e.placeholderText),i=fn(e.segments,t);e.text.slice(i).trim().length!==0&&this.store.set({pendingSpan:{anchor:i,snapshot:e.actionableSuggestions}})}maybeExitReEditOnNoMatch(){let e=this.store.get();if(!e.editingParam||e.editingAnchor==null||e.completedParams.some(r=>r.id===e.editingParam?.id)||this.optionSource.owns(e.editingParam.suggestionType,e.optionQuery))return;let t=e.caretOffset??e.editingAnchor,i=e.text.slice(e.editingAnchor,t);K(e.editingParam.options,i).some(r=>r.is_tappable)||(this.reEdit.exit(),this.fetchNow())}fetchNow(){let e=this.store.get(),{rawQuery:t,completedParams:i}=R(e.text,e.completedParams);this.fetchController.doFetch(t,i)}commitIdentifiedDate(e){let t=this.store.get(),i=t.editingIdentified;if(!i)return;if(t.text.slice(i.anchor,i.tail)!==i.text){this.store.set({editingIdentified:null,activeDropdownIndex:-1});return}let o=t.text.slice(0,i.anchor),r=t.text.slice(i.tail),s=i.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=o+l+r,d=c.length,u={id:crypto.randomUUID(),placeholder:"",type:i.type,text:s,value:e.value,kind:e.kind,suggestionType:i.type,suggestionPlaceholder:G(i.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!==i.id),newParamId:u.id,filterBase:d,caretOffset:d,editingIdentified:null,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.startSelectionAnimationTimer(),this.scheduleSetCursor(d),this.fetchNow()}maybePromoteExactMatch(e){let t=this.store.get();if(P(t.activeFormatType))return;let i=Be({mode:"fresh",text:e,completedParams:t.completedParams,suggestions:t.suggestions,filterBase:t.filterBase,filterInProgress:t.filterInProgress});i&&this.store.set(i.patch)}};export{Ut as AIAutocomplete,qn as ATTRIBUTION_URL,lt as DATE_RANGE_META_END,at as DATE_RANGE_META_START,ei as DEFAULT_OPTION_COUNT_UNIT,he as ModeController,He as OPTIONS_GRID_MOBILE_QUERY,Lt as OPTION_ENTER_DELAY_VAR,Oo as OPTION_ENTER_FADE_MS,Ao as OPTION_ENTER_RISE_MS,Io as OPTION_ENTER_RISE_PX,Co as OPTION_ENTER_STAGGER_MS,mo as PLACEHOLDER_FADE_OUT_MS,te as PLACEHOLDER_LEAVING_ATTR,fo as PLACEHOLDER_SWAP_GAP_MS,uo as PLACEHOLDER_TYPE_MS,po as PLACEHOLDER_WORD_PAUSE_MS,Ln as PRODUCT_PATH_PREFIX,wo as PRODUCT_ROW_PX_PER_LINE,nn as RANGE_SEPARATOR,si as SCROLL_ARROW_ATTR,di as SCROLL_ARROW_BOTTOM_VAR,ri as SCROLL_ARROW_CLASS,ai as SCROLL_ARROW_FADE_MS,ci as SCROLL_ARROW_LABEL,li as SCROLL_ARROW_SCROLL_IDLE_MS,oe as SCROLL_ARROW_VISIBLE_ATTR,ln as SKIPPED_PARAM_TEXT,be as WEEKDAY_LABELS,tt as addMonths,It as attachProductRowWheel,Ft as attachScrollArrow,Et as buildAttributionUrl,nt as buildDateOptions,R as buildQuery,j as buildSubmitResult,ot as cellDay,N as cellIso,kn as computeOptionsGridLayout,Gt as createStore,mt as cursorIsAtEnd,Ot as dateCellMarks,me as dateSelectionFor,Me as extractPlainText,X as formatAbsoluteDate,Xt as formatDate,on as formatDateRange,fe as formatOptionCount,_ as getCursorOffset,Tt as getFooterHint,G as identifiedParamLabel,P as isCalendarFormat,Pt as isOptionsGridMobileViewport,M as isoDate,wt as measureOptionsGrid,Ze as monthLabel,xt as needsOptionsGridMeasurement,Ro as optionCountLabel,Mt as optionEnterDelayMs,Do as optionHasImage,$ as optionImageSrc,_t as optionLabel,kt as optionsEntranceDurationMs,St as optionsGridTemplateColumns,ye as parseDate,q as parseLooseDate,J as parseLooseDateRange,pt as plainTextLength,vt as planOptionsGrid,ft as previousGraphemeBoundary,Mn as productFromMatchedItem,Jn as productRowWheelTarget,bt as productsFromCustomFields,Wt as renderEditableContent,U as resolveFormatType,rt as resolveIdentifiedDate,ge as sanitizeOptionIconSvg,ut as scrollCaretIntoView,it as selectedIsoFromText,ae as selectedRangeFor,D as setCursorOffset,de as toWireIdentifiedParams,Ct as visibleDateRange,ce as withSkippedParams};
|
|
2054
2072
|
//# sourceMappingURL=index.mjs.map
|