@magicx-eng/ai-autocomplete-vanilla 0.34.0 → 0.35.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -2
- package/dist/index.d.mts +22 -3
- package/dist/index.d.ts +22 -3
- package/dist/index.js +58 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +58 -2
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var Wt=Object.defineProperty;var po=Object.getOwnPropertyDescriptor;var mo=Object.getOwnPropertyNames;var fo=Object.prototype.hasOwnProperty;var go=(t,e)=>{for(var n in e)Wt(t,n,{get:e[n],enumerable:!0})},ho=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of mo(e))!fo.call(t,o)&&o!==n&&Wt(t,o,{get:()=>e[o],enumerable:!(i=po(e,o))||i.enumerable});return t};var bo=t=>ho(Wt({},"__esModule",{value:!0}),t);var Zr={};go(Zr,{AIAutocomplete:()=>Bt,ATTRIBUTION_URL:()=>sn,DATE_RANGE_META_END:()=>ke,DATE_RANGE_META_START:()=>Me,DEFAULT_OPTION_COUNT_UNIT:()=>un,ModeController:()=>he,OPTIONS_GRID_MOBILE_QUERY:()=>Pe,OPTION_ENTER_DELAY_VAR:()=>Ct,OPTION_ENTER_FADE_MS:()=>Fi,OPTION_ENTER_RISE_MS:()=>Hi,OPTION_ENTER_RISE_PX:()=>Bi,OPTION_ENTER_STAGGER_MS:()=>Ni,PLACEHOLDER_FADE_OUT_MS:()=>gi,PLACEHOLDER_LEAVING_ATTR:()=>te,PLACEHOLDER_SWAP_GAP_MS:()=>hi,PLACEHOLDER_TYPE_MS:()=>mi,PLACEHOLDER_WORD_PAUSE_MS:()=>fi,PRODUCT_PATH_PREFIX:()=>tn,PRODUCT_ROW_PX_PER_LINE:()=>Ri,RANGE_SEPARATOR:()=>Kt,SCROLL_ARROW_ATTR:()=>fn,SCROLL_ARROW_BOTTOM_VAR:()=>bn,SCROLL_ARROW_CLASS:()=>mn,SCROLL_ARROW_FADE_MS:()=>gn,SCROLL_ARROW_LABEL:()=>yn,SCROLL_ARROW_SCROLL_IDLE_MS:()=>hn,SCROLL_ARROW_VISIBLE_ATTR:()=>ne,SKIPPED_PARAM_TEXT:()=>Qt,WEEKDAY_LABELS:()=>ye,addMonths:()=>Ie,attachProductRowWheel:()=>Pt,attachScrollArrow:()=>Lt,buildAttributionUrl:()=>yt,buildDateOptions:()=>Oe,buildQuery:()=>A,buildSubmitResult:()=>V,cellDay:()=>Le,cellIso:()=>N,chipIdFromTap:()=>Je,computeOptionsGridLayout:()=>rn,containScroll:()=>xt,createStore:()=>_t,cursorIsAtEnd:()=>et,dateCellMarks:()=>Et,dateSelectionFor:()=>me,extractPlainText:()=>we,formatAbsoluteDate:()=>j,formatDate:()=>$t,formatDateRange:()=>Yt,formatOptionCount:()=>fe,getCursorOffset:()=>k,getFooterHint:()=>St,identifiedParamLabel:()=>B,isCalendarFormat:()=>v,isOptionsGridMobileViewport:()=>ut,isoDate:()=>M,keepCaretOnChip:()=>Ze,measureOptionsGrid:()=>ct,monthLabel:()=>Ce,needsOptionsGridMeasurement:()=>lt,optionCountLabel:()=>Wi,optionEnterDelayMs:()=>It,optionHasImage:()=>qi,optionImageSrc:()=>H,optionLabel:()=>At,optionsEntranceDurationMs:()=>Ot,optionsGridTemplateColumns:()=>at,parseDate:()=>Se,parseLooseDate:()=>W,parseLooseDateRange:()=>z,plainTextLength:()=>ze,planOptionsGrid:()=>dt,previousGraphemeBoundary:()=>tt,productFromMatchedItem:()=>nn,productInitial:()=>Tt,productRowWheelTarget:()=>ln,productsFromCustomFields:()=>rt,renderEditableContent:()=>kt,resolveFormatType:()=>q,resolveIdentifiedDate:()=>De,sameOptionRows:()=>pt,sanitizeOptionIconSvg:()=>ge,scrollCaretIntoView:()=>Qe,selectedIsoFromText:()=>Ae,selectedRangeFor:()=>se,setCursorOffset:()=>O,toWireIdentifiedParams:()=>ae,visibleDateRange:()=>vt,withSkippedParams:()=>le});module.exports=bo(Zr);function qt(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9]+/).filter(Boolean).map(e=>e.toLowerCase())}function B(t){let e=qt(t);return e.length>0?e.join(" "):t}var re=["January","February","March","April","May","June","July","August","September","October","November","December"],ye=["S","M","T","W","T","F","S"],On=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],An="aiaDate",Ln="aiaDay",Cn=t=>String(t).padStart(2,"0");function M(t){return`${t.getFullYear()}-${Cn(t.getMonth()+1)}-${Cn(t.getDate())}`}function Gt(t){return new Date(t.getFullYear(),t.getMonth(),t.getDate())}function yo(t){let e=Gt(t).getTime()-Gt(new Date).getTime();return Math.round(e/864e5)}function $t(t){let e=yo(t);return e>=0&&e<7?On[t.getDay()]:j(t)}function j(t){return t.getFullYear()===new Date().getFullYear()?`${re[t.getMonth()]} ${t.getDate()}`:`${re[t.getMonth()]} ${t.getDate()} ${t.getFullYear()}`}function Se(t){if(!t)return null;let e=On.findIndex(a=>a.toLowerCase()===t.trim().toLowerCase());if(e>=0){let a=Gt(new Date),l=(e-a.getDay()+7)%7;return new Date(a.getFullYear(),a.getMonth(),a.getDate()+l)}let n=/^\s*([A-Za-z]+)\s+(\d{1,2})(?:\s+(\d{4}))?\s*$/.exec(t);if(!n)return null;let i=re.findIndex(a=>a.toLowerCase()===n[1].toLowerCase());if(i<0)return null;let o=Number(n[2]),r=n[3]?Number(n[3]):new Date().getFullYear(),s=new Date(r,i,o);return s.getMonth()!==i||s.getDate()!==o?null:s}function Ce(t){return`${re[t.month]} ${t.year}`}function Vt(){let t=new Date;return{year:t.getFullYear(),month:t.getMonth()}}function Rn(t){return{year:t.getFullYear(),month:t.getMonth()}}function Ie(t,e){let n=new Date(t.year,t.month+e,1);return{year:n.getFullYear(),month:n.getMonth()}}function In(){return{text:"",is_tappable:!1,kind:null}}function Oe(t){let e=new Date(t.year,t.month,1).getDay(),n=new Date(t.year,t.month+1,0).getDate(),i=[];for(let o=0;o<e;o++)i.push(In());for(let o=1;o<=n;o++){let r=new Date(t.year,t.month,o);i.push({text:$t(r),is_tappable:!0,kind:null,metadata:{[An]:M(r),[Ln]:o}})}for(;i.length%ye.length!==0;)i.push(In());return i}function Ae(t){let e=Se(t);return e?M(e):null}function N(t){let e=t?.metadata?.[An];return typeof e=="string"?e:null}function Le(t){let e=t?.metadata?.[Ln];return typeof e=="number"?e:null}function So(t){return t.replace(/(\d+)(?:st|nd|rd|th)\b/g,"$1")}function Dn(t){let e=t.toLowerCase().replace(/\.$/,"");return e.length<3?-1:re.findIndex(n=>n.toLowerCase().startsWith(e))}function xo(t,e,n){let i=new Date(n.getFullYear(),t,e);if(i.getMonth()!==t||i.getDate()!==e)return null;let o=new Date(n.getFullYear(),n.getMonth(),n.getDate());if(i>=o)return i;let r=new Date(n.getFullYear()+1,t,e);return r.getMonth()===t&&r.getDate()===e?r:null}function Mn(t,e,n){let i=new Date(t,e,n);return i.getMonth()===e&&i.getDate()===n?i:null}function W(t,e={}){if(!t)return null;let n=e.today??new Date,i=So(t.trim().toLowerCase()).replace(/\s+/g," "),o=/^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(i);if(o){let l=Mn(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=Dn(r[1]);if(l>=0)return Re(l,Number(r[2]),r[3],n)}let s=/^(\d{1,2}) (?:of )?([a-z]+)\.?(?:,? (\d{4}))?$/.exec(i);if(s){let l=Dn(s[2]);if(l>=0)return Re(l,Number(s[1]),s[3],n)}let a=/^(\d{1,2})[/\-.](\d{1,2})(?:[/\-.](\d{2,4}))?$/.exec(i);if(a){let l=Number(a[1]),d=Number(a[2]);return l>12&&d<=12?Re(d-1,l,a[3],n):d>12&&l<=12?Re(l-1,d,a[3],n):null}return null}function Re(t,e,n,i){if(n){if(n.length!==4)return null;let r=Mn(Number(n),t,e);return r?M(r):null}let o=xo(t,e,i);return o?M(o):null}function De(t,e={}){let n=t.isoDate;return typeof n=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(n)?n:W(t.text,e)}var Kt=" - ",Me="aiaDateRangeStart",ke="aiaDateRangeEnd";function xe(t,e){return t<=e?{start:t,end:e}:{start:e,end:t}}var Ut=/^\d{4}-\d{2}-\d{2}$/;function kn(t){if(!Ut.test(t))return null;let[e,n,i]=t.split("-").map(Number),o=new Date(e,n-1,i);return o.getMonth()===n-1&&o.getDate()===i?o:null}var vo=/\s+(?:to|through|thru|until|til|till)\s+/g,Eo=/[-–—]/g;function wo(t){let e=[];for(let n of[vo,Eo]){n.lastIndex=0;let i=n.exec(t);for(;i!==null;)e.push([t.slice(0,i.index),t.slice(i.index+i[0].length)]),i=n.exec(t)}return e}function z(t,e={}){if(!t)return null;let n=new Set,i=null;for(let[o,r]of wo(t.trim())){let s=W(o.trim(),e);if(!s)continue;let a=W(r.trim(),e);!a||a<s||(n.add(`${s}|${a}`),i={start:s,end:a})}return n.size===1?i:null}function Yt(t){let e=kn(t.start),n=kn(t.end);return!e||!n?"":t.start===t.end?j(e):`${j(e)}${Kt}${j(n)}`}function _n(t,e){let n=xe(t,e);return{text:Yt(n),is_tappable:!0,kind:null,metadata:{[Me]:n.start,[ke]:n.end}}}function se(t,e={}){let n=t?.metadata?.[Me],i=t?.metadata?.[ke];return typeof n=="string"&&typeof i=="string"&&Ut.test(n)&&Ut.test(i)?xe(n,i):z(t?.text,e)}function v(t){return t==="date"||t==="date-range"}var Po=new Set(["date","dates"]),To=new Set(["range","ranges","span","period","window"]),Nn=3;function Co(t){let e={single:0,range:0};if(!t)return e;for(let n of t)n.is_tappable&&(z(n.text)!==null?e.range+=1:W(n.text)!==null&&(e.single+=1));return e}function q(t){if(!t)return"options";let e=t.formatType;if(e==="date"||e==="options"||e==="date-range")return e;let n=Co(t.options);if(n.single+n.range>=Nn&&n.range>n.single)return"date-range";let i=qt(t.type);return i.some(o=>Po.has(o))?i.some(o=>To.has(o))?"date-range":"date":n.single>=Nn?"date":"options"}var _e=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 Io="https://api.ai-autocomplete.com",Ne=`${Io}/api/suggest`,Fn=new WeakMap;function ve(t){return t?.type==="accessToken"}function Oo(t){if(!(!t||ve(t)))return t}function Fe(t){let e=Fn.get(t.getAccessToken);return e||(e=new _e(t),Fn.set(t.getAccessToken,e)),e}function He(t){return{"Content-Type":"application/json",...t?.appIdentifier&&{"X-App-Identifier":t.appIdentifier},...t?.headers}}function Be(t){let e=Oo(t),n=e?.apiKey;return n?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(n)}`:`Bearer ${n}`:null}function ae(t){return t.map(e=>({type:e.type,value:e.text}))}var Qt="skipped";function le(t,e){if(e.length===0)return t;let n=new Set(t.map(o=>o.type)),i=e.filter(o=>!n.has(o.type)).map(o=>({placeholder:"",type:o.type,text:Qt,kind:null}));return i.length>0?[...t,...i]:t}var Ao="0.34.0",Hn=!1;function Lo(t,e){return{placeholder:t.placeholder,type:t.type,...e&&{text:t.value??t.text},kind:t.kind}}function Ro(t,e,n,i,o,r,s,a,l,d){let c=e.find(m=>m.type==="contact"&&m.metadata?.contact_account_count)?.metadata?.contact_account_count,u=typeof c=="number"?c:void 0;return{data:{raw_query:t,completed_params:le(e.map(m=>Lo(m,n)),l??[]),...s&&s.length>0&&{identified_params:ae(s)},...a&&a.length>0&&{recently_suggested:a},...u!=null&&{contact_account_count:u},...d!==void 0&&{additional_context:d}},meta:{request_id:o,request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:Ao,session_id:i,source:r}}}async function Bn(t,e,n,i,o){return fetch(t,{method:"POST",headers:{...e,Authorization:`Bearer ${n}`},body:i,signal:o})}async function Wn(t,e,n){let i=n.apiConfig,o=!n.maskCompletedText,r=Ro(t,e,o,n.sessionId,n.requestId??crypto.randomUUID(),n.source,n.identifiedParams,n.recentlySuggested,n.skippedParams,n.additionalContext),s=He(i),a=i?.endpoint??Ne,l=JSON.stringify(r);if(ve(i)){let u=Fe(i),m=await u.getToken(),f=await Bn(a,s,m,l,n.signal);if(f.status===401){let h=await u.getToken(!0);f=await Bn(a,s,h,l,n.signal)}if(!f.ok)throw new Error(`API error: ${f.status} ${f.statusText}`);return f.json()}let d=Be(i);!d&&!Hn&&(Hn=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),d&&(s.Authorization=d);let c=await fetch(a,{method:"POST",headers:s,body:l,signal:n.signal});if(!c.ok)throw new Error(`API error: ${c.status} ${c.statusText}`);return c.json()}var We=/[\p{L}\p{N}]/u,Do=/['\u2019-]/;function qn(t,e,n){let i=t[e];if(i===void 0)return!1;if(We.test(i))return!0;let o=t[e+n];return Do.test(i)&&o!==void 0&&We.test(o)}function Mo(t,e,n){let i=e+n.length;return!(We.test(n[0])&&qn(t,e-1,-1)||We.test(n[n.length-1])&&qn(t,i,1))}function F(t,e,n=0,i=()=>!0){if(e.length===0)return t.indexOf(e,n);let o=-1,r=t.indexOf(e,n);for(;r!==-1;){if(i(r)){if(Mo(t,r,e))return r;o===-1&&(o=r)}r=t.indexOf(e,r+1)}return o}function A(t,e){let n=t,i={},o=[],r=[],s=0;for(let a of e){let l=(i[a.type]??0)+1;i[a.type]=l;let c=`{{${a.type.toUpperCase().replace(/\s+/g,"_")}_${l}}}`,u=f=>F(n,a.text,f,h=>!r.some(S=>h<S.end&&h+a.text.length>S.start)),m=u(s);if(m===-1&&(m=u(0)),m!==-1){n=n.slice(0,m)+c+n.slice(m+a.text.length);let f=c.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+c.length}),s=m>=s?m+c.length:s+f}o.push({...a,placeholder:c})}return{rawQuery:n,completedParams:o}}function G(t,e,n){return e>0||!n?e:t.toLowerCase().startsWith(n.toLowerCase())?n.length:e}function qe(t,e,n){return e===0&&t.length>0&&n.length>0&&n.toLowerCase().startsWith(t.toLowerCase())}function J(t,e,n){let i=t.slice(e);if(n||e===0||t[e-1]===" ")return i;let o=i.indexOf(" ");return o===-1?"":i.slice(o+1)}function Gn(t,e){let n=t.trimEnd().replace(/\s+/g," ");if(n.length===0||e.length===0)return 0;let i=n.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=n.length-s.length;return t.length-a}}return 0}function Z(t,e){if(!t)return[];let n=e.trimStart();if(!n)return t;let i=n.toLowerCase();return t.filter(o=>!o.is_tappable||o.text.toLowerCase().includes(i))}function de(t,e){if(!t)return null;let n=e.trim();if(!n)return null;let i=n.toLowerCase();return t.find(o=>o.is_tappable&&o.text.toLowerCase()===i)??null}function $n(t,e){return e?t.map(n=>e[n.type]?{...n,options:[]}:n):t}function Vn(t,e){let n=0,i=e;for(let o of t)n+=o.value.length,o.type!=="text"&&(i=Math.max(i,n));return i}function Un(t,e){let n=0;for(let i of t){let o=n+i.value.length;if(i.type==="text"&&o>e&&i.value.slice(Math.max(e-n,0)).trim().length>0)return!1;n=o}return!0}function Kn(t,e){let n=[],i=new Set;for(let o of[...t,...e])o.type==="placeholder"||i.has(o.type)||(i.add(o.type),n.push({type:o.type,text:o.text}));return n}function Yn(t,e,n){if(t===e)return n;let i=Math.min(t.length,e.length),o=0;for(;o<i&&t[o]===e[o];)o++;if(o>=n)return n;let r=0;for(;r<i-o&&t[t.length-1-r]===e[e.length-1-r];)r++;return t.length-r<=n?n+(e.length-t.length):null}function Ge(t,e){let n=[],i=[],o=0;for(let r of e){let s=F(t,r.text,o);if(s===-1){i.push(r);continue}n.push({start:s,end:s+r.text.length,param:r}),o=s+r.text.length}return{located:n,missing:i}}function Qn(t,e){let{located:n}=Ge(t,e);return n.length>0?n[n.length-1].end:0}function Xn(t,e,n){let i=[],o=[],r=0;for(let s of n){let a=F(t,s.text,r,l=>!e.some(d=>l<d.end&&l+s.text.length>d.start));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 jn(t,e,n=[]){let i=Ge(t,e).located,o=Xn(t,i,n).located,r=[...i.map(d=>({start:d.start,end:d.end,segment:{type:"completed",value:d.param.text,param:d.param}})),...o.map(d=>({start:d.start,end:d.end,segment:{type:"identified",value:d.param.text,param:d.param}}))].sort((d,c)=>d.start-c.start),s=[],a=0;for(let d of r)d.start>a&&s.push({type:"text",value:t.slice(a,d.start)}),s.push(d.segment),a=d.end;let l=t.slice(a);return l&&s.push({type:"text",value:l}),s}function zn(t,e){let{located:n,missing:i}=Ge(t,e);return{valid:n.map(o=>o.param),invalid:i}}function $e(t,e,n){let i=Ge(t,e).located,{located:o,missing:r}=Xn(t,i,n);return{valid:o.map(s=>s.param),invalid:r}}function ko(t){if(t instanceof Error)return t;try{return new Error(String(t))}catch{return new Error("Unknown error")}}var _o=100,No=300,Fo=2,Ve=class{constructor(e,n,i,o,r,s,a,l,d={}){this.store=e;this.getApiConfig=n;this.getOptionOverrides=i;this.getMaskCompletedText=o;this.getOnError=r;this.getSessionId=s;this.getSource=a;this.getAdditionalContext=l;this.callbacks=d;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null}start(){this.doFetch("",[]);let e=this.store.get().text,n=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(i=>{(i.text!==e||i.completedParams!==n)&&(e=i.text,n=i.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,n){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?Kn(s.pendingSpan.snapshot,s.actionableSuggestions):void 0,l=crypto.randomUUID(),d=await Wn(e,n,{sessionId:this.getSessionId(),requestId:l,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=(d.data.input??[]).filter(w=>w.source==="identified").map(w=>({id:crypto.randomUUID(),type:w.type,text:w.text})),u=$n(d.data.suggestions??[],this.getOptionOverrides()),m=d.data.input??[],f=m[m.length-1],h=this.store.get().text,S,x;if(f?.state==="in_progress"){x=!0;let w=h.toLowerCase().lastIndexOf(f.text.toLowerCase());S=w!==-1?w:r}else x=!1,S=r;let p=u.filter(w=>w.type!=="placeholder")[0],b=null;if(p&&!v(q(p))){let w=J(h,S,x),P=de(p.options,w);P&&(b={id:crypto.randomUUID(),placeholder:"",type:p.type,text:P.text,value:P.value,kind:P.kind,suggestionType:p.type,suggestionPlaceholder:p.text,options:p.options??[],metadata:P.metadata,icon:P.icon,icon_svg:P.icon_svg,image_url:P.image_url},u=u.filter(R=>R!==p),this.callbacks.onAutoMatch?.({active:p,matched:P,rawQuery:e}))}let y=d.data.custom_fields??null,E=this.callbacks.productsForResponse?.(y);this.store.set(w=>{let P=b?[...w.completedParams,b]:w.completedParams,R=$e(w.text,P,c).valid,T=new Set(s.skippedParams.map(D=>D.id)),I=new Set(w.skippedParams.filter(D=>!T.has(D.id)).map(D=>D.type));return{suggestions:I.size>0?u.filter(D=>D.type==="placeholder"||!I.has(D.type)):u,isLoading:!1,isReady:d.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:S,filterInProgress:x,identifiedParams:R,customFields:y,...E!==void 0?{products:E}:{},...b?{completedParams:P}:{}}}),this.callbacks.onResponse?.({requestId:l,funnelTelemetry:d.meta?.funnel_telemetry===!0})}catch(s){let a=ko(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(Fo)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},_o),this.slowDebounceTimer=setTimeout(()=>this.attemptFetch(1),No)}attemptFetch(e,n=!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=G(i.text,i.filterBase,r),a=J(i.text,s,i.filterInProgress),d=i.suggestions.filter(y=>y.type!=="placeholder")[0],c=v(i.activeFormatType),m=(d&&!c?Z(d.options,a):[]).filter(y=>y.is_tappable),f=d&&!c?de(d.options,a)!==null:!1,h=a.trim().length>0;if(m.length>0&&!f&&h||qe(i.text,i.completedParams.length,r))return!1;let{rawQuery:S,completedParams:x}=A(i.text,i.completedParams),g=S.length<i.lastRawQuery.length,p=Math.abs(S.length-i.lastRawQuery.length),b=n&&S!==i.lastRawQuery;return g||p>=e||b?(this.doFetch(S,x),!0):!1}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};function Ho(t){return t.nodeType===Node.DOCUMENT_NODE?!0:t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t}function ee(t){let e=typeof t.getRootNode=="function"?t.getRootNode():null;return e&&Ho(e)?e:t.ownerDocument??t}function L(t){return t.ownerDocument??t}function Bo(t){return t.nodeType===Node.DOCUMENT_FRAGMENT_NODE}function Jn(t){let e=ee(t);return!Bo(e)||typeof e.getSelection=="function"?null:e}function Zn(t){let e=Jn(t);if(!e)return null;let n=L(t).getSelection?.();return!n||typeof n.getComposedRanges!="function"?null:e}function ei(t,e){let n=t,i;try{i=n.getComposedRanges({shadowRoots:[e]})}catch{i=n.getComposedRanges(e)}return i.length>0?i[0]:null}function Xt(t){let n=ee(t).getSelection?.();return n||(L(t).getSelection?.()??null)}function $(t){let e=Xt(t);if(!e||e.rangeCount===0)return null;let n=Zn(t);if(n){let i=ei(e,n);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 Ue(t){let e=Xt(t);if(!e||e.rangeCount===0)return null;let n=Zn(t);if(!n)return e.getRangeAt(0);let i=ei(e,n);if(!i)return null;let o=L(t).createRange();return o.setStart(i.startContainer,i.startOffset),o.setEnd(i.endContainer,i.endOffset),o}function Ee(t,e,n){let i=Xt(t);if(!i)return null;if(Jn(t))return i.collapse(e,n),i;let o=L(t).createRange();return o.setStart(e,n),o.collapse(!0),i.removeAllRanges(),i.addRange(o),i}function Ke(t,e){let n=t?ee(t):typeof document<"u"?document:null;return n?typeof n.getElementById=="function"?n.getElementById(e):typeof document<"u"?document.getElementById(e):null:null}var Ye=2,Wo="magicx-aia";function ti(t){return t==="auto"||t==="scroll"||t==="hidden"||t==="overlay"}function qo(t){let e=L(t),n=e.defaultView;if(!n?.getComputedStyle)return null;let i=t;for(;i&&i!==e.body&&i!==e.documentElement;){let o=i.scrollWidth>i.clientWidth,r=i.scrollHeight>i.clientHeight;if(o||r){let s=n.getComputedStyle(i);if(o&&ti(s.overflowX)||r&&ti(s.overflowY))return i}if(i.classList.contains(Wo))return null;i=i.parentElement}return null}function Qe(t){let e=Ue(t);if(!e||!e.collapsed||!t.contains(e.startContainer))return;let n=qo(t);if(!n||typeof e.getBoundingClientRect!="function")return;let i=e.getBoundingClientRect();if(i.height===0)return;let o=n.getBoundingClientRect();if(n.scrollWidth>n.clientWidth){let r=o.left+n.clientLeft,s=r+n.clientWidth;i.right>s?n.scrollLeft+=i.right-s+Ye:i.left<r&&(n.scrollLeft-=r-i.left+Ye)}if(n.scrollHeight>n.clientHeight){let r=o.top+n.clientTop,s=r+n.clientHeight;i.bottom>s?n.scrollTop+=i.bottom-s+Ye:i.top<r&&(n.scrollTop-=r-i.top+Ye)}}var ii='[contenteditable="false"]',zt="strong[data-param-id]",ce;function Go(){if(ce!==void 0)return ce;let t=globalThis.Intl.Segmenter;if(!t)return ce=null,null;try{ce=new t(void 0,{granularity:"grapheme"})}catch{ce=null}return ce??null}function Xe(t,e){let n=t;for(;n&&n!==e;){if(n.nodeType===Node.ELEMENT_NODE&&n.matches(ii))return!0;n=n.parentNode}return!1}function je(t){return L(t).createTreeWalker(t,NodeFilter.SHOW_TEXT,{acceptNode(e){return Xe(e,t)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function we(t){let e=je(t),n="",i=e.nextNode();for(;i;)n+=i.data,i=e.nextNode();return n}function ze(t){let e=je(t),n=0,i=e.nextNode();for(;i;)n+=i.data.length,i=e.nextNode();return n}function k(t){let e=$(t);if(!e)return null;let n=e.node,i=e.offset;if(!t.contains(n))return null;if(n.nodeType===Node.ELEMENT_NODE){let o=n;if(Xe(o,t)&&o!==t)return null;let r=0;for(let s=0;s<i&&s<o.childNodes.length;s++)r+=Jt(o.childNodes[s],t);return r+jt(o,t)}return n.nodeType!==Node.TEXT_NODE||Xe(n,t)?null:jt(n,t)+i}function Jt(t,e){if(t.nodeType===Node.TEXT_NODE)return Xe(t,e)?0:t.data.length;if(t.nodeType!==Node.ELEMENT_NODE)return 0;let n=t;if(n.matches(ii))return 0;let i=0;for(let o of Array.from(n.childNodes))i+=Jt(o,e);return i}function jt(t,e){let n=je(e),i=0,o=n.nextNode();for(;o;){if(o===t||t.nodeType===Node.ELEMENT_NODE&&t.contains(o))return i;i+=o.data.length,o=n.nextNode()}return i}function O(t,e){let n=L(t),i=Math.max(0,Math.min(e,ze(t))),o=je(t),r=0,s=null,a=0,l=o.nextNode(),d=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,d=l,l=o.nextNode()}let c=n.createRange();if(s){let u=s.parentElement?.closest('strong[data-seg="completed"]');u&&u!==t&&t.contains(u)?a===0?c.setStartBefore(u):a===s.data.length?c.setStartAfter(u):c.setStart(s,a):c.setStart(s,a)}else d?c.setStart(d,d.data.length):c.setStart(t,0);c.collapse(!0),Ee(t,c.startContainer,c.startOffset)&&($o(t,c,i),Qe(t))}function ni(t,e){if(!t||!e.contains(t))return null;let i=(t.nodeType===Node.ELEMENT_NODE?t:t.parentElement)?.closest(zt)??null;return i&&e.contains(i)?i:null}function $o(t,e,n){let i=ni($(t)?.node??null,t);if(i&&i!==ni(e.startContainer,t)){t.dataset.aiaCaretEscapedChip=`${n}:${i.dataset.paramId}`;return}delete t.dataset.aiaCaretEscapedChip}function oi(t,e){let n=t.dataset.aiaCaretEscapedChip;if(!n)return!1;let i=k(t);return i!==null&&n===`${i}:${e}`}function ri(t){return ee(t).activeElement===t}function Je(t,e){if(!e||e.nodeType===void 0)return null;let n=e,o=(n.nodeType===Node.ELEMENT_NODE?n:n.parentElement)?.closest(zt);if(!o||!t.contains(o))return null;let r=$(t);return r&&!r.collapsed?null:o.dataset.paramId??null}function Ze(t,e){let n=null;for(let s of t.querySelectorAll(zt))if(s.dataset.paramId===e){n=s;break}if(!n)return;let i=jt(n,t),o=i+Jt(n,t),r=k(t);r!=null&&r>=i&&r<=o||O(t,i)}function et(t){let e=k(t);return e==null?!1:e>=ze(t)}function tt(t,e){if(e<=0)return 0;let n=Go();if(!n)return e-1;let i=t.slice(0,e),o=0;for(let{index:r}of n.segment(i))r<e&&(o=r);return o}function V(t,e,n=[],i={}){let{rawQuery:o,completedParams:r}=A(t,e);return{query:t.trim(),raw_query:o,completed_params:le(r,n),identified_params:ae(i.identifiedParams??[]),is_ready:i.isReady??!1,...i.customFields?{custom_fields:i.customFields}:{}}}function Zt(t,e){return t instanceof HTMLTextAreaElement||t instanceof HTMLInputElement?t.selectionStart!=null&&t.selectionStart===t.value.length:t instanceof HTMLElement&&t.hasAttribute("data-aia-input")?et(t):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function en(t){return t instanceof HTMLElement&&t.hasAttribute("data-aia-input")?k(t):null}var nt=class{constructor(e,n){this.store=e;this.ctx=n}handleKeyDown(e){let n=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 d=this.ctx.getOptionsPosition()==="above";switch(e.key){case"ArrowDown":{let c=Zt(e.target,n),u=!!n.editingParam;if(!c&&!u&&n.activeDropdownIndex<0)break;if(n.activeDropdownIndex<0){if(d)break;e.preventDefault();let h=v(n.activeFormatType)?this.dateEntryIndex(n,!1):l[0]??0;if(!n.isDropdownOpen&&n.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:h});break}if(l.length===0)return;this.store.set({activeDropdownIndex:h});break}if(e.preventDefault(),l.length===0)return;if(v(n.activeFormatType)){this.stepDateWeek(n,7);break}if(n.filteredOptions.length>0){let h=Math.floor((n.filteredOptions.length-1)/s);if(Math.floor(n.activeDropdownIndex/s)===h){this.store.set({activeDropdownIndex:-1});break}}let m=l.indexOf(n.activeDropdownIndex),f=m<l.length-1?m+1:0;this.store.set({activeDropdownIndex:l[f]});break}case"ArrowUp":{if(n.activeDropdownIndex<0){if(!d)break;let m=Zt(e.target,n),f=!!n.editingParam;if(!m&&!f)break;e.preventDefault();let h=v(n.activeFormatType)?this.dateEntryIndex(n,!0):this.firstTappableInBottomRow(s)??l[0]??0;if(!n.isDropdownOpen&&n.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:h});break}if(l.length===0)return;this.store.set({activeDropdownIndex:h});break}if(l.length===0)break;if(e.preventDefault(),v(n.activeFormatType)){this.stepDateWeek(n,-7);break}if(n.activeDropdownIndex<s){this.store.set({activeDropdownIndex:-1});break}let c=l.indexOf(n.activeDropdownIndex),u=c>0?c-1:l.length-1;this.store.set({activeDropdownIndex:l[u]});break}case"ArrowRight":{if(n.activeDropdownIndex>=0){if(e.preventDefault(),v(n.activeFormatType)){this.stepDateDay(n,1);break}if(n.activeDropdownIndex%s<s-1){let m=n.activeDropdownIndex+1;m<n.filteredOptions.length&&n.filteredOptions[m]?.is_tappable&&this.store.set({activeDropdownIndex:m})}break}if(n.editingParam&&e.target instanceof HTMLElement&&n.editingTail!=null){e.preventDefault();let u=e.target.closest("[data-aia-input]")??e.target,m=n.editingTail;this.ctx.exitEditMode?.(),O(u,m);break}Zt(e.target,n)&&n.actionableSuggestions.length>=1&&(e.preventDefault(),this.ctx.skipActivePill());break}case"ArrowLeft":{if(n.activeDropdownIndex>=0){if(e.preventDefault(),v(n.activeFormatType)){this.stepDateDay(n,-1);break}if(n.activeDropdownIndex%s>0){let c=n.activeDropdownIndex-1;c>=0&&n.filteredOptions[c]?.is_tappable&&this.store.set({activeDropdownIndex:c});break}if(!n.editingParam&&this.ctx.startEditingParamAtCaret){let c=en(e.target);c!=null&&this.ctx.startEditingParamAtCaret(c)}break}if(n.editingParam&&e.target instanceof HTMLElement&&n.editingAnchor!=null){e.preventDefault();let c=e.target.closest("[data-aia-input]")??e.target,u=n.editingAnchor;this.ctx.exitEditMode?.(),O(c,u);break}if(this.ctx.startEditingParamAtCaret){let c=en(e.target);c!=null&&this.ctx.startEditingParamAtCaret(c)&&e.preventDefault()}break}case"Backspace":{if(n.editingParam||!this.ctx.removeParamAtCaret)break;let c=en(e.target);if(c==null)break;this.ctx.removeParamAtCaret(c)&&e.preventDefault();break}case"Enter":{e.preventDefault(),n.activeDropdownIndex>=0&&n.filteredOptions[n.activeDropdownIndex]?.is_tappable?this.clickOrSelect(n.activeDropdownIndex,n.filteredOptions,i,r):a&&a(V(n.text,n.completedParams,n.skippedParams,{identifiedParams:n.identifiedParams,isReady:n.isReady,customFields:n.customFields}))&&this.ctx.afterSubmit?.();break}case"Tab":{let c=n.filteredOptions.map((f,h)=>f.is_tappable?h:-1).filter(f=>f!==-1);if(c.length===0)break;if(!n.isDropdownOpen){if(n.actionableSuggestions.length===0)break;e.preventDefault();let f=e.shiftKey?c[c.length-1]:c[0];this.store.set({pillTapped:!0,activeDropdownIndex:f});break}e.preventDefault();let u=c.indexOf(n.activeDropdownIndex),m;if(u<0)m=e.shiftKey?c.length-1:0;else{let f=e.shiftKey?-1:1;m=(u+f+c.length)%c.length}this.store.set({activeDropdownIndex:c[m]});break}case"Escape":{if(n.dateRangeStart){this.store.set({pendingRangeStart:null});break}if(n.editingIdentified){this.ctx.exitEditingIdentified?.(),this.store.set({activeDropdownIndex:-1});break}if(n.editingParam&&e.target instanceof HTMLElement&&n.editingTail!=null){let c=e.target.closest("[data-aia-input]")??e.target,u=n.editingTail;this.ctx.exitEditMode?.(),O(c,u)}this.store.set({activeDropdownIndex:-1});break}}}firstTappableInBottomRow(e){let n=this.store.get();if(n.filteredOptions.length===0)return null;let o=Math.floor((n.filteredOptions.length-1)/e)*e;for(let r=o;r<n.filteredOptions.length;r++)if(n.filteredOptions[r]?.is_tappable)return r;return null}dateEntryIndex(e,n){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(n?r[r.length-1]:r[0])??0}stepDateDay(e,n){for(let i=e.activeDropdownIndex+n;i>=0&&i<e.filteredOptions.length;i+=n)if(e.filteredOptions[i]?.is_tappable){this.store.set({activeDropdownIndex:i});return}}stepDateWeek(e,n){let i=e.activeDropdownIndex+n;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 n=Ke(e,this.ctx.listboxId);if(!n)return this.ctx.columns;let o=Ke(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===n)break;o=o.parentElement}return this.ctx.columns}clickOrSelect(e,n,i,o){let r=Ke(o,`${i}-option-${e}`);r?r.click():this.ctx.selectOption(n[e])}};var it=class{constructor(e,n,i={}){this.store=e;this.getOverrides=n;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,n){return this.hasOverride(e)&&!this.missCovers(e,n)}tick(e,n){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(n>1&&!s&&r<n)return"owns"}return this.ask(i),"asked"}sync(e){let n=this.resolveTarget(e);if(!n){this.current&&(this.cancel(),this.current=null),e.optionSearch&&this.store.set({optionSearch:null});return}this.current&&this.current.key===n.key||this.ask(n)}resolveTarget(e){if(v(e.activeFormatType)||e.editingIdentified)return null;let n=e.editingParam;if(n&&e.editingAnchor!=null)return this.hasOverride(n.suggestionType)?{mode:"edit",key:n.id,type:n.suggestionType,suggestion:{type:n.suggestionType,text:n.suggestionPlaceholder,required:!0,options:n.options},query:e.optionQuery}:null;let 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,n){return this.lastMiss!=null&&this.lastMiss.type===e&&this.lastMiss.query===n}ask(e){this.cancel();let n=this.getOverrides()?.[e.type],i=++this.version;if(!n||this.missCovers(e.type,e.query)){this.current={key:e.key,type:e.type,query:e.query,abort:null},this.setSearch(e,"done");return}let o=new AbortController;this.current={key:e.key,type:e.type,query:e.query,abort:o};let r;try{r=n(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,n,i,o){let r;try{let s=await n;if(i.aborted||o!==this.version)return;r=Array.isArray(s)?s:[]}catch(s){if(i.aborted||o!==this.version||Vo(s))return;this.logOnce(s),r=[]}this.commit(e,r,o)}commit(e,n,i){if(i!==this.version)return;let o=this.resolveTarget(this.store.get());if(!o||o.key!==e.key)return;n.length===0?this.lastMiss={type:e.type,query:e.query}:this.lastMiss?.type===e.type&&(this.lastMiss=null);let r={type:e.type,query:e.query,status:"done"};if(e.mode==="edit")this.store.set(s=>({editingParam:s.editingParam&&s.editingParam.id===e.key?{...s.editingParam,options:n}:s.editingParam,optionSearch:r}));else{let s={...e.suggestion,options:n};this.current&&this.current.key===e.key&&(this.current.key=s),this.store.set(a=>({suggestions:a.suggestions.map(l=>l===e.suggestion?s:l),optionSearch:r}))}n.length===0?this.callbacks.onMiss?.(e.mode,e.query):this.callbacks.onAnswer?.(e.mode,e.query)}setSearch(e,n){let i=this.store.get().optionSearch;i&&i.type===e.type&&i.query===e.query&&i.status===n||this.store.set({optionSearch:{type:e.type,query:e.query,status:n}})}cancel(){this.current?.abort?.abort(),this.version++}logOnce(e){this.hasLoggedError||(this.hasLoggedError=!0,console.warn("[AIAutocomplete] an optionOverrides entry threw or rejected \u2014 treated as no options. Later failures on this instance are not logged.",e))}};function Vo(t){return t instanceof Error&&t.name==="AbortError"}var ot=class{constructor(e,n={}){this.store=e;this.callbacks=n}setActivePill(e){let n=this.store.get(),i=n.suggestions.filter(d=>d.type!=="placeholder");if(e<0||e>=i.length)return;let o=i[e],r=i.filter((d,c)=>c!==e),s=n.suggestions.filter(d=>d.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:d}=A(n.text,n.completedParams);this.callbacks.onPillSelected({rawQuery:d,selectedPill:o.text,otherPills:r.map(c=>c.text)})}let a=[...s,o,...r],l=this.store.peek({suggestions:a}).filteredOptions.findIndex(d=>d.is_tappable);this.store.set({suggestions:a,pillTapped:!0,activeDropdownIndex:l})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(n=>({completedParams:n.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};var tn="/products/",si="https://relative.invalid";function Uo(t){if(!t)return;let e;try{e=new URL(t,`${si}/`)}catch{return}if(!(e.protocol!=="http:"&&e.protocol!=="https:"))return t.startsWith("/")?e.origin===si?t:void 0:/^https?:\/\//i.test(t)?t:void 0}function nn(t){let e=Uo(t.item_url)??(t.handle?`${tn}${encodeURIComponent(t.handle)}`:void 0);return{id:t.source_id,title:t.title,...e&&{url:e},imageUrl:t.image_url||null,...t.price&&{price:t.price},...t.vendor&&{vendor:t.vendor}}}function rt(t){return(t?.items.matched??[]).map(nn)}var st=class{constructor(e,n,i=()=>!0){this.store=e;this.getConfig=n;this.isEnabled=i;this.hasLoggedError=!1}forResponse(e){if(!this.isEnabled())return[];if(!this.getConfig())return rt(e)}async run(e,n,i){if(!this.isEnabled())return;let o=this.getConfig();if(!o)return;if(e.trim().length===0){this.clear(i);return}let r=()=>n.aborted||!i()||!this.owns(o);try{let s=await o.fetch(e,n);if(r())return;let a=o.transform(s),l=Array.isArray(a)?a:[],d=o.limit!=null?l.slice(0,o.limit):l;if(r())return;this.commit(d)}catch(s){if(n.aborted||Ko(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 Ko(t){return t instanceof Error&&t.name==="AbortError"}var Pe="(max-width: 768px)";var Yo="var(--aia-option-row-height, 37px)",Qo="var(--aia-grid-scroll-top, 0px) + var(--aia-grid-scroll-bottom, 0px)";function rn(t,e){return e?on(1,Math.min(t,5)):on(1,Math.min(t,4))}function on(t,e){return{cols:t,rows:e,maxHeight:`calc(${e} * ${Yo} + ${Qo})`}}function lt(t,e){return!e&&t>=5}function dt(t,e,n,i){if(!(!e&&t>=5&&Xo(n,i))){let s=rn(t,e);return{...s,template:at(s.cols),scrollHintIndices:!e&&t>s.rows?[s.rows-1]:[]}}let r=6;return{...on(2,3),template:at(2),scrollHintIndices:t>r?[r-2,r-1]:[]}}function Xo(t,e){return!t||t.length===0||e==null||e<=0||t.some(i=>i<=0)?!1:Math.ceil(Math.max(...t))*2<=e}function ct(t){if(typeof document>"u")return null;let e=Array.from(t.querySelectorAll("[data-aia-option]"));if(e.length===0)return null;let n=document.createElement("div");n.style.cssText="position:absolute;visibility:hidden;left:-9999px;top:0;";for(let s of e){let a=s.cloneNode(!0);a.removeAttribute("id"),a.removeAttribute("role"),a.removeAttribute("aria-selected"),a.style.whiteSpace="nowrap",a.style.width="max-content",n.appendChild(a)}t.appendChild(n);let i=Array.from(n.children).map(s=>s.offsetWidth);n.remove();let o=getComputedStyle(t),r=t.clientWidth-(Number.parseFloat(o.paddingLeft)||0)-(Number.parseFloat(o.paddingRight)||0)-(Number.parseFloat(o.columnGap)||0);return{rowWidths:i,gridWidth:r}}function at(t){return Array.from({length:t},()=>"minmax(0,1fr)").join(" ")}function ut(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(Pe).matches}function pt(t,e){return!t||t.length!==e.length?!1:t.every((n,i)=>n.text===e[i].text)}function ai(t,e){let n=e.dropdownTrigger??"auto",i=e.closeDropdownOnBlur??!0,s=t.filteredOptionsLength>0||t.activePillHasNoOptions||t.hasProducts;if(t.inEditMode){let a=i?t.isFocused:!0;return s&&a}if(n==="auto"){let a=i?t.isFocused:!0,l=t.text.replace(/\s+$/,"").length,d=t.caretOffset==null||t.caretOffset>=l;return(s||t.isLoading)&&a&&d}return n==="manual"?(s||t.isLoading)&&t.pillTapped:!1}function Te(t){if(t.editingIdentified){let{type:n,anchor:i}=t.editingIdentified;return`identified:${n}@${i}`}return t.editingParam!=null&&t.editingAnchor!=null?`edit:${t.editingParam?.id}`:`pill:${t.actionableSuggestions[0]?.type??""}`}function li(t){if(!t)return Vt();let[e,n]=t.split("-").map(Number);return{year:e,month:n-1}}function jo(t){let e=Se(t);return e?Rn(e):Vt()}function di(t,e){let n=jn(t.text,t.completedParams,t.identifiedParams),i=t.suggestions.filter(C=>C.type!=="placeholder"),o=i[0],r=t.suggestions.filter(C=>C.type==="placeholder").map(C=>C.text).join(" "),s=G(t.text,Math.min(t.filterBase,t.text.length),r),l=s===0&&qe(t.text,t.completedParams.length,r)?"":J(t.text,s,t.filterInProgress),d=o?.options??[],c=t.editingParam!=null&&t.editingAnchor!=null,u,m,f,h;if(c&&t.editingParam&&t.editingAnchor!=null){let C=t.editingParam.id,oe=t.completedParams.some(uo=>uo.id===C),be=t.caretOffset??t.editingAnchor,Tn=oe?"":t.text.slice(t.editingAnchor,be);m=Tn.trim(),f=t.editingParam.options,h=t.editingParam.suggestionType,u=Z(t.editingParam.options,Tn)}else m=l.trim(),f=d,h=o?.type,u=Z(d,l);let S=t.optionSearch,x=S!=null&&h!=null&&S.type===h;x&&S.status==="done"&&S.query===m&&(u=f);let g=x&&S.status==="loading",p=e.showNonTappableOptions===!1;p&&(u=u.filter(C=>C.is_tappable));let b=t.editingIdentified,y=c?t.editingParam&&{type:t.editingParam.suggestionType,options:t.editingParam.options}:o,E=b?b.format:q(y),w=c&&v(E)?se(t.editingParam):null;w&&(E="date-range");let P=null,R=null;if(v(E)){let C=Te({...t,actionableSuggestions:i}),oe=t.dateViewMonth;P=oe&&oe.key===C?{year:oe.year,month:oe.month}:b?li(b.iso):w?li(w.start):jo(t.editingParam?.text),u=Oe(P);let be=t.pendingRangeStart;E==="date-range"&&be&&be.key===C&&(R=be.iso)}let T=C=>p?C.is_tappable:!0,I;if(c){let C=t.editingParam?.options??[];I=t.editingParam!=null&&C.filter(T).length===0}else I=o!=null&&d.filter(T).length===0;let X=ai({inEditMode:c||b!=null,filteredOptionsLength:u.length,isFocused:t.isFocused,text:t.text,caretOffset:t.caretOffset,isLoading:t.isLoading||g,pillTapped:t.pillTapped,activePillHasNoOptions:I,hasProducts:t.products.length>0},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),D=X&&t.activeDropdownIndex>=0&&!!u[t.activeDropdownIndex]?.is_tappable,_=t.skeletonOptions!==null&&t.skeletonRequested&&!t.isLoading&&!t.editingParam&&!t.inSelectionAnimation,ie=t.isLoading&&!t.editingParam&&!t.inSelectionAnimation||g||_,Pn=ie&&t.skeletonOptions!==null,lo=Pn&&t.skeletonOptions?t.skeletonOptions:u,co=Pn?t.skeletonSuggestion:null;return{segments:n,actionableSuggestions:i,filteredOptions:u,dropdownLoading:ie,dropdownOptions:lo,dropdownSuggestion:co,skeletonExiting:_,activeFormatType:E,dateView:P,dateRangeStart:R,placeholderText:r,optionQuery:m,isSearchingOptions:g,isDropdownOpen:X,isActivePillSelected:D}}function mt(t){return t.mode==="fresh"?zo(t):Jo(t)}function zo(t){let{text:e,completedParams:n,suggestions:i,filterBase:o,filterInProgress:r}=t,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(" "),d=G(e,o,l),c=J(e,d,r),u=de(a.options,c);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,x=e.slice(h,S),p=S<e.length&&e[S]===" "?S+1:S,b={id:crypto.randomUUID(),placeholder:"",type:a.type,text:x,value:u.value,kind:u.kind,suggestionType:a.type,suggestionPlaceholder:a.text,options:a.options??[],metadata:u.metadata,icon:u.icon,icon_svg:u.icon_svg,image_url:u.image_url};return{patch:{text:e,completedParams:[...n,b],suggestions:i.filter(y=>y!==a),filterBase:p,newParamId:b.id,caretOffset:p,activeDropdownIndex:-1},caretPos:p}}function Jo(t){let{text:e,completedParams:n,editingParam:i,editingAnchor:o,editingTail:r}=t;if(n.some(b=>b.id===i.id))return null;let s=e.slice(o,r),a=de(i.options,s);if(!a)return null;let l=a.text.toLowerCase(),d=s.toLowerCase().lastIndexOf(l),c=o+Math.max(0,d),u=c+a.text.length,m=e.slice(c,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},x=n.length,g=0;for(let b=0;b<n.length;b++){let y=F(e,n[b].text,g);if(y!==-1){if(y>=f){x=b;break}g=y+n[b].text.length}}let p=[...n];return p.splice(x,0,S),{patch:{text:e,completedParams:p,newParamId:S.id,filterBase:h,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:h,activeDropdownIndex:-1},caretPos:h}}var Zo=6e4;function er(t){return typeof TextEncoder>"u"?t.length*3:new TextEncoder().encode(t).length}function tr(t){return(t??Ne).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function nr(t){return ve(t)?`Bearer ${await Fe(t).getToken()}`:Be(t)}async function ci(t){try{let e=tr(t.apiConfig?.endpoint),n=He(t.apiConfig),i=await nr(t.apiConfig);i&&(n.Authorization=i);let o=JSON.stringify({source:t.source,session_id:t.sessionId,...t.visitorId&&{visitor_id:t.visitorId},...t.requestId&&{request_id:t.requestId},type:t.type,at:new Date().toISOString(),query_data:t.queryData});await fetch(e,{method:"POST",headers:n,body:o,...t.keepalive&&er(o)<=Zo&&{keepalive:!0}})}catch{}}function ue(t,e){let n=t.findIndex(i=>i.text===e);return n>=0?n+1:null}function ui(t,e){let n=t.actionableSuggestions[0];if(!n)return null;let i=t.filterBase,o=t.text.slice(0,i),r=o.length===0&&t.text.length===0,s=o.length===0&&t.text.length>0&&t.placeholderText.length>0&&t.placeholderText.toLowerCase().startsWith(t.text.toLowerCase());(r||s)&&t.placeholderText&&(o=`${t.placeholderText} `);let a=Math.min(Qn(t.text,t.completedParams),o.length),l=Gn(o.slice(a),e.text);l>0&&(o=o.slice(0,o.length-l));let d=o.length>0&&o[o.length-1]!==" ",c=`${o}${d?" ":""}${e.text} `,u=(r||s)&&c.length>0?c[0].toUpperCase()+c.slice(1):c,m=u.toLowerCase().lastIndexOf(e.text.toLowerCase()),f=m>=0?u.slice(m,m+e.text.length):e.text,h={id:crypto.randomUUID(),placeholder:"",type:n.type,text:f,value:e.value,kind:e.kind,suggestionType:n.type,suggestionPlaceholder:n.text,options:n.options??[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url},S=t.actionableSuggestions.length-1;return{patch:{text:u,filterBase:u.length,completedParams:[...t.completedParams,h],newParamId:h.id,caretOffset:u.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:!0,inSelectionAnimation:!0,pendingSpan:null},telemetry:{selectedOption:e.text,otherOptions:t.filteredOptions.filter(x=>x.text!==e.text).map(x=>x.text),key:n.type,position:ue(n.options??[],e.text)},consumedSuggestion:n,remainingActionable:S}}function ft(t){let e=v(t.activeFormatType)||t.filteredOptions.length===0?null:t.filteredOptions,n=t.editingParam,i=n?{type:n.suggestionType,text:n.suggestionPlaceholder,required:!0,options:n.options}:t.actionableSuggestions[0]??null;return{skeletonOptions:e,skeletonSuggestion:e?i:null,skeletonRequested:!1}}function gt(t,e,n){let i=t.slice(0,e),o=t.slice(n),r=(i===""||i.endsWith(" "))&&o.startsWith(" ");return r&&(o=o.slice(1)),{text:i+o,removed:n-e+(r?1:0)}}var ht=class{constructor(e){this.deps=e}start(e){let n=this.deps.store.get();if(n.editingParam?.id===e)return;let i=n.completedParams.find(s=>s.id===e);if(!i)return;let o=0,r=-1;for(let s of n.completedParams){let a=F(n.text,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 n=this.deps.store.get(),i=n.editingParam,o=n.editingAnchor,r=n.editingTail;if(!i||o==null||r==null||!n.completedParams.some(l=>l.id===i.id))return!1;let{text:s}=e===""?gt(n.text,o,r):{text:n.text.slice(0,o)+e+n.text.slice(r)},a=o+e.length;return this.deps.store.set(l=>({text:s,completedParams:l.completedParams.filter(d=>d.id!==i.id),editingTail:a,caretOffset:a,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(a),this.promoteIfExact(),!0}caretAfterInput(e){let n=this.deps.store.get(),i={caretOffset:e};n.editingParam&&n.editingAnchor!=null&&e!=null&&(e<n.editingAnchor?(i.editingParam=null,i.editingAnchor=null,i.editingTail=null,i.activeDropdownIndex=-1):n.editingTail!=null&&(i.editingTail=Math.max(n.editingTail,e))),this.deps.store.set(i),this.promoteIfExact()}caretMove(e){let n=this.deps.store.get();if(n.editingParam&&n.editingAnchor!=null&&n.editingTail!=null&&e!=null&&(e<n.editingAnchor||e>n.editingTail)){this.deps.store.set({caretOffset:e,editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1});return}this.deps.store.set({caretOffset:e})}selectOption(e){let n=this.deps.store.get(),i=n.editingParam,o=n.editingAnchor,r=n.editingTail;if(!i||o==null||r==null)return;this.deps.fireTelemetry("option",{raw_query:A(n.text,n.completedParams).rawQuery,selected_option:e.text,other_options:i.options.filter(g=>g.text!==e.text).map(g=>g.text),key:i.suggestionType,position:ue(i.options,e.text)});let s=n.text.slice(0,o),a=n.text.slice(r),l=o===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,c=a.length===0||a[0]!==" "?`${l} `:l,u=s+c+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=n.completedParams.findIndex(g=>g.id===i.id),S=n.completedParams.filter(g=>g.id!==i.id),x=h>=0?Math.min(h,S.length):S.length;S.splice(x,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,...ft(n)}),this.deps.startSelectionAnimationTimer(),this.deps.scheduleSetCursor(m),this.deps.fetchNow()}promoteIfExact(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let n=mt({mode:"edit",text:e.text,completedParams:e.completedParams,editingParam:e.editingParam,editingAnchor:e.editingAnchor,editingTail:e.editingTail});n&&(this.deps.store.set(n.patch),this.deps.scheduleSetCursor(n.caretPos))}};var mi=33,fi=70,gi=120,hi=50,te="data-aia-placeholder-leaving",pe=new WeakMap;function bt(t){t.timer!==null&&(clearTimeout(t.timer),t.timer=null)}function ir(t){return t.closest('[data-animations="off"]')?!0:!!t.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function bi(t,e,n){e.shown=n,t.dataset.placeholder=e.target.slice(0,n)}function yi(t,e){if(e.timer=null,!t.isConnected||e.shown>=e.target.length||(bi(t,e,e.shown+1),e.shown>=e.target.length))return;let n=e.target[e.shown-1],i=n===" "||n==="-"?70:0;e.timer=setTimeout(()=>yi(t,e),33+i)}function pi(t,e){bi(t,e,0),e.timer=setTimeout(()=>yi(t,e),33)}function Si(t,e){let n=pe.get(t);if(e===""){n&&(bt(n),pe.delete(t)),t.removeAttribute(te),delete t.dataset.placeholder;return}if(n?.target===e)return;if(ir(t)){n&&bt(n),t.removeAttribute(te),pe.set(t,{target:e,shown:e.length,timer:null}),t.dataset.placeholder=e;return}let i={target:e,shown:0,timer:null},o=n&&n.shown>0?n:null;if(n&&bt(n),pe.set(t,i),o){t.setAttribute(te,""),i.timer=setTimeout(()=>{i.timer=null,t.removeAttribute(te),t.isConnected&&pi(t,i)},170);return}t.removeAttribute(te),pi(t,i)}function xi(t){let e=pe.get(t);e&&(bt(e),pe.delete(t))}var sn="https://ai-autocomplete.com";function yt(t=sn){try{if(typeof window>"u"||!window.location)return t;let e=window.location.hostname;if(!e)return t;let n=new URL(t);return n.searchParams.set("utm_source",e),n.toString()}catch{return t}}function St(t,e){return t?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}function xt(t){let e=s=>{s.ctrlKey||vi(s.target,t,s.deltaX,s.deltaY)||s.preventDefault()},n=0,i=0,o=s=>{let a=s.touches[0];a&&(n=a.clientX,i=a.clientY)},r=s=>{if(s.touches.length!==1)return;let a=s.touches[0],l=n-a.clientX,d=i-a.clientY;n=a.clientX,i=a.clientY,s.cancelable&&!vi(s.target,t,l,d)&&s.preventDefault()};return t.addEventListener("wheel",e,{passive:!1}),t.addEventListener("touchstart",o,{passive:!0}),t.addEventListener("touchmove",r,{passive:!1}),()=>{t.removeEventListener("wheel",e),t.removeEventListener("touchstart",o),t.removeEventListener("touchmove",r)}}function vi(t,e,n,i){let o=t instanceof Element?t:null;for(;o;){if(i!==0&&or(o,i)||n!==0&&rr(o,n))return!0;if(o===e)break;o=o.parentElement}return!1}var Ei=/^(auto|scroll|overlay)$/;function or(t,e){return t.scrollHeight<=t.clientHeight||!Ei.test(getComputedStyle(t).overflowY)?!1:e>0?t.scrollTop+t.clientHeight<t.scrollHeight-1:t.scrollTop>0}function rr(t,e){if(t.scrollWidth<=t.clientWidth)return!1;let n=getComputedStyle(t);if(!Ei.test(n.overflowX))return!1;let i=Math.abs(t.scrollLeft),o=t.scrollWidth-t.clientWidth;return(n.direction==="rtl"?e<0:e>0)?i<o-1:i>0}var wi=new WeakMap,Pi=new WeakSet;function U(t,e,n){if(wi.set(t,n),Pi.has(t))return;Pi.add(t);let i=()=>wi.get(t),o=r=>{if(!(r instanceof Element))return null;let s=r.closest(e.itemSelector);return s&&t.contains(s)?s:null};e.onClick&&t.addEventListener("click",r=>{let s=o(r.target);s&&e.onClick?.(s,i(),r)}),e.onEnter&&t.addEventListener("mouseenter",r=>{let s=r.target;s instanceof HTMLElement&&s.matches(e.itemSelector)&&e.onEnter?.(s,i())},!0),e.onLeave&&t.addEventListener("mouseleave",r=>{let s=r.target;s instanceof HTMLElement&&s.matches(e.itemSelector)&&e.onLeave?.(s,i())},!0),e.preventMousedown&&t.addEventListener("mousedown",r=>r.preventDefault())}function K(t){return Number.parseInt(t.dataset.aiaIndex??"-1",10)}function Y(t){t.offsetWidth}var sr={selectedIso:null,selectedRange:null,rangeStart:null};function me(t){if(!v(t.activeFormatType))return sr;let e=t.editingIdentified;if(e){let{iso:i,isoEnd:o}=e;return{selectedIso:o?null:i,selectedRange:i&&o?xe(i,o):null,rangeStart:t.dateRangeStart}}let n=se(t.editingParam);return{selectedIso:n?null:Ae(t.editingParam?.text),selectedRange:n,rangeStart:t.dateRangeStart}}function vt(t){return t.pendingStart?xe(t.pendingStart,t.highlightedIso??t.pendingStart):t.selected}function Et(t,e){if(t==null)return{selected:!1,inRange:!1};let{selectedIso:n,range:i}=e,o=t===n||i!=null&&(t===i.start||t===i.end),r=i!=null&&t>i.start&&t<i.end;return{selected:o,inRange:r}}var Ti="data-aia-key";function Q(t,e,n){let i=new Map;for(let s of Array.from(t.children)){let a=s.getAttribute(Ti);a!=null&&i.set(a,s)}let o=new Set,r=[];for(let s=0;s<e.length;s++){let a=e[s],l=n.keyOf(a,s);o.add(l);let d=i.get(l);d||(d=n.create(a,s),d.setAttribute(Ti,l)),n.update?.(d,a,s),t.children[s]!==d&&t.insertBefore(d,t.children[s]??null),r.push(d)}for(let[s,a]of i)o.has(s)||a.remove();return r}function Ci(t,e){if(!e.interactive)return null;let n=e.options[K(t)];return n?.is_tappable?n:null}var ar={itemSelector:"[data-aia-date-cell], [data-aia-date-prev], [data-aia-date-next]",onClick:(t,e)=>{if(t.hasAttribute("data-aia-date-prev")){e.callbacks.onPreviousMonth();return}if(t.hasAttribute("data-aia-date-next")){e.callbacks.onNextMonth();return}let n=Ci(t,e);n&&(t.classList.add("magicx-aia-date-cell--pressed"),e.callbacks.onSelect(n),setTimeout(()=>t.classList.remove("magicx-aia-date-cell--pressed"),170))},onEnter:(t,e)=>{t.hasAttribute("data-aia-date-cell")&&Ci(t,e)&&e.callbacks.onHighlight(K(t))},onLeave:(t,e)=>{t.hasAttribute("data-aia-date-cell")&&e.callbacks.onHighlight(-1,K(t))}};function Oi(t,e,n,i,o,r,s,a=!0){let l=t.querySelector(".magicx-aia-datepicker");if(!o||e.length===0){l?.remove();return}if(!l){l=cr(),t.appendChild(l),Y(l);for(let u of l.querySelectorAll(".magicx-aia-datepicker-nav"))u.disabled=!1}U(l,ar,{options:e,callbacks:s,interactive:a});let d=l.querySelector(".magicx-aia-datepicker-month");d&&(d.textContent=Ce(o));let c=l.querySelector(".magicx-aia-datepicker-grid");c&&lr(c,e,n,i,r)}function lr(t,e,n,i,o){let r=M(new Date),s=vt({pendingStart:o.rangeStart,highlightedIso:N(e[n]),selected:o.selectedRange});Q(t,e,{keyOf:(a,l)=>N(a)??`pad-${l}`,create:a=>dr(a),update:(a,l,d)=>{let c=N(l),u=Et(c,{selectedIso:o.selectedIso,range:s}),m=d===n&&l.is_tappable;a.id=`${i}-option-${d}`,a.dataset.aiaIndex=String(d),a.setAttribute("aria-selected",String(m)),a.classList.toggle("magicx-aia-date-cell--past",c!=null&&c<r),a.classList.toggle("magicx-aia-date-cell--highlighted",m),a.classList.toggle("magicx-aia-date-cell--today",c!=null&&c===r),a.classList.toggle("magicx-aia-date-cell--selected",u.selected),a.classList.toggle("magicx-aia-date-cell--in-range",u.inRange)}})}function dr(t){let e=document.createElement("div");e.setAttribute("role","option"),e.setAttribute("data-aia-option",""),e.setAttribute("data-aia-date-cell","");let n=Le(t);if(n==null)return e.className="magicx-aia-date-cell magicx-aia-date-cell--blank",e.setAttribute("aria-hidden","true"),e.tabIndex=-1,e;e.className="magicx-aia-date-cell magicx-aia-date-cell--day",e.tabIndex=0,e.setAttribute("aria-label",t.text);let i=document.createElement("span");return i.className="magicx-aia-date-cell-number",i.textContent=String(n),e.appendChild(i),e}function cr(){let t=document.createElement("div");t.className="magicx-aia-datepicker",t.setAttribute("data-aia-datepicker","");let e=document.createElement("div");e.className="magicx-aia-datepicker-header";let n=document.createElement("span");n.className="magicx-aia-datepicker-month",n.setAttribute("data-aia-date-month",""),n.setAttribute("aria-live","polite"),e.append(Ii("prev","Previous month","\u2039"),n,Ii("next","Next month","\u203A"));let i=document.createElement("div");i.className="magicx-aia-datepicker-weekdays",i.setAttribute("aria-hidden","true");for(let r of ye){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",""),t.append(e,i,o),t}function Ii(t,e,n){let i=document.createElement("button");return i.type="button",i.tabIndex=-1,i.className="magicx-aia-datepicker-nav",i.setAttribute(`data-aia-date-${t}`,""),i.setAttribute("aria-label",e),i.textContent=n,i.disabled=!0,i}var ur={itemSelector:"[data-aia-pill]",onClick:(t,e)=>{if(e.loading||t.disabled)return;let n=Number.parseInt(t.dataset.aiaPillIndex??"-1",10);n>=0&&e.onSelectPill(n)},preventMousedown:!0},Ai=[125,69];function Li(t,e){return e?1:t===0?.7:t===1?.4:.2}function wt(t,e,n,i,o=!1,r=!1,s=!1){let a=t.querySelector(".magicx-aia-pill-list");if(a||(a=document.createElement("span"),a.className="magicx-aia-pill-list",t.appendChild(a)),U(a,ur,{onSelectPill:i,loading:r}),r&&e.length===0){a.setAttribute("data-aia-pill-list-loading",""),a.innerHTML="";for(let l=0;l<Ai.length;l++){let d=Ai[l],c=document.createElement("span");c.setAttribute("data-aia-pill-skeleton",""),c.className=`magicx-aia-pill magicx-aia-pill--skeleton${o?" magicx-aia-pill--rounded":""}`,c.style.width=`${d}px`,c.style.opacity=String(Li(l,!1)),a.appendChild(c)}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();Q(a,e,{keyOf:l=>`${l.type}-${l.text}`,create:l=>{let d=document.createElement("button");return d.type="button",d.tabIndex=-1,d.setAttribute("data-aia-pill",""),d.setAttribute("contenteditable","false"),d.textContent=l.text,d.disabled=!0,d},update:(l,d,c)=>{let u=l,m=s&&c===n&&!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(Li(c,m)),u.dataset.aiaPillIndex=String(c),r?u.setAttribute("data-aia-loading",""):u.removeAttribute("data-aia-loading")}}),Y(a);for(let l of a.querySelectorAll("[data-aia-pill]"))l.disabled=r}function an(t){t.querySelector(".magicx-aia-pill-list")?.remove()}var Ri=32;function ln(t,e){if(e.ctrlKey)return null;let n=e.deltaY||0,i=e.deltaX||0;if(!n||Math.abs(i)>=Math.abs(n))return null;let o=t.scrollWidth-t.clientWidth;if(o<=1)return null;let r=t.scrollLeft,s=n;return e.deltaMode===1?s*=32:e.deltaMode===2&&(s*=t.clientWidth),Math.max(0,Math.min(o,r+s))}function Pt(t){let e=n=>{let i=ln(t,n);i!==null&&(n.preventDefault(),t.scrollLeft=i)};return t.addEventListener("wheel",e,{passive:!1}),()=>t.removeEventListener("wheel",e)}var Di=Intl.Segmenter,Mi=Di?new Di(void 0,{granularity:"grapheme"}):null;function Tt(t){let e=t.trim().normalize("NFC").toUpperCase();if(Mi)for(let n of Mi.segment(e))return n.segment;return Array.from(e)[0]??"?"}var dn=new WeakMap,ki=new WeakMap,pr="Products";function _i(t,e,n,i,o,r="row",s="image"){let a=t.querySelector(".magicx-aia-products");if(e.length===0){a?.remove();return}if(!a){a=document.createElement("section"),a.className="magicx-aia-products",a.setAttribute("data-aia-products",""),a.setAttribute("role","group"),a.setAttribute("aria-labelledby",`${n}-products-label`);let d=document.createElement("div");d.className="magicx-aia-products-label",d.id=`${n}-products-label`,d.setAttribute("data-aia-products-label",""),d.textContent=pr;let c=document.createElement("div");c.className="magicx-aia-products-row",c.setAttribute("data-aia-products-row",""),Pt(c),a.append(d,c),t.appendChild(a)}a.setAttribute("data-aia-products-layout",r);let l=a.querySelector(".magicx-aia-products-row");if(l){Q(l,e,{keyOf:d=>mr(d),create:d=>fr(d,i,o,s),update:(d,c,u)=>{d.id=`${n}-product-${u}`,d.dataset.aiaIndex=String(u),ki.get(d)?.(s)}}),Y(l);for(let d of l.querySelectorAll("[data-aia-product]")){let c=dn.get(d);c&&(dn.delete(d),c())}}}function cn(t,e){let n=t.querySelectorAll("[data-aia-product]");for(let i of n)i.tabIndex=e?0:-1}function mr(t){return[t.id,t.title,t.url,t.imageUrl,t.price,t.vendor].map(e=>e??"").join("\0")}function fr(t,e,n,i){let o=document.createElement("a");o.className="magicx-aia-product",o.setAttribute("data-aia-product",""),o.setAttribute("role","option"),o.setAttribute("aria-selected","false"),o.tabIndex=0;let r=document.createElement("span");r.className="magicx-aia-product-media",r.setAttribute("aria-hidden","true");let s=t.imageUrl?.trim(),a=!!s,l=()=>{r.replaceChildren(),r.toggleAttribute("data-aia-product-placeholder",i==="image"),r.toggleAttribute("data-aia-product-initial",i==="initial"),i==="initial"&&(r.textContent=Tt(t.title))};if(ki.set(o,u=>{u!==i&&(i=u,a||l())}),s){let u=document.createElement("img");u.onerror=()=>{a=!1,l()},u.className="magicx-aia-product-image",u.src=s,u.alt="",u.loading="lazy",u.decoding="async",r.appendChild(u)}else l();o.appendChild(r);let d=document.createElement("span");if(d.className="magicx-aia-product-body",t.vendor){let u=document.createElement("span");u.className="magicx-aia-product-vendor",u.textContent=t.vendor,d.appendChild(u)}let c=document.createElement("span");if(c.className="magicx-aia-product-title",c.textContent=t.title,d.appendChild(c),t.price){let u=document.createElement("span");u.className="magicx-aia-product-price",u.textContent=t.price,d.appendChild(u)}return o.appendChild(d),dn.set(o,()=>{t.url&&(o.href=t.url),o.addEventListener("click",u=>{u.metaKey||u.ctrlKey||u.shiftKey||u.altKey||u.button!==0||(u.preventDefault(),e(t))})}),o.addEventListener("keydown",u=>{u.key!=="Enter"&&u.key!==" "||(u.preventDefault(),e(t))}),o.addEventListener("focus",()=>n(!0)),o.addEventListener("blur",u=>{u.relatedTarget?.closest("[data-aia-dropdown]")||n(!1)}),o}var Ni=80,Fi=150,Hi=280,Bi=16,Ct="--aia-option-enter-delay";function It(t,e,n,i="below"){let o=Math.max(1,Math.floor(e)),r=Math.floor(Math.max(0,t)/o);if(i!=="above")return r*80;let s=Math.max(1,Math.ceil(Math.max(0,n)/o));return Math.max(0,s-1-r)*80}function Ot(t,e){let n=Math.max(1,Math.floor(e));return(Math.max(1,Math.ceil(Math.max(0,t)/n))-1)*80+280}function H(t){if(!t)return null;let e=t.trim();if(e==="")return null;let n;try{n=new URL(e,typeof document>"u"?void 0:document.baseURI)}catch{return null}return n.protocol!=="http:"&&n.protocol!=="https:"?null:n.href}function fe(t){return t===void 0||!Number.isInteger(t)||t<0?null:t.toLocaleString()}var un={one:"item",other:"items"};function Wi(t,e=un){let n=fe(t);if(n===null)return null;let i=typeof e=="string"?e:t===1?e.one:e.other;return i===""?n:`${n} ${i}`}function qi(t){return H(t.image_url)!==null}var Gi="http://www.w3.org/2000/svg",gr=new Set(["svg","g","path","circle","ellipse","line","polyline","polygon","rect"]);function hr(t,e){let n=t.toLowerCase();return n.startsWith("on")||n.includes("href")||n==="style"||n==="xml:base"||n==="id"||n==="name"||/^\s*javascript:/i.test(e)||/url\s*\(\s*['"]?\s*[^#'"\s)]/i.test(e)}var br=["fill","stroke","stroke-width","stroke-linecap","stroke-linejoin","fill-rule","clip-rule","opacity","fill-opacity","stroke-opacity"],yr=/^[a-zA-Z0-9#.,%\s()-]+$/;function Sr(t){let e=[];for(let n of br){let i=t.getAttribute(n);i===null||!yr.test(i)||/url\s*\(/i.test(i)||e.push(`${n}: ${i.trim()}`)}e.length>0&&t.setAttribute("style",e.join("; "))}function $i(t){for(let e of Array.from(t.attributes))hr(e.name,e.value)&&t.removeAttribute(e.name);Sr(t);for(let e of Array.from(t.childNodes))if(e.nodeType===Node.ELEMENT_NODE){let n=e;!gr.has(n.localName)||n.namespaceURI!==Gi?n.remove():$i(n)}else e.remove()}function ge(t){if(typeof DOMParser>"u"||typeof XMLSerializer>"u")return null;let e=new DOMParser().parseFromString(t,"image/svg+xml"),n=e.documentElement;return!n||n.localName!=="svg"||n.namespaceURI!==Gi||e.getElementsByTagName("parsererror").length>0?null:($i(n),n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false"),new XMLSerializer().serializeToString(n))}function At(t){return t.text}var Vi=new WeakMap;function xr(t,e,n){let i=e.length,o=ut(),r=Vi.get(t),s=n&&r&&pt(r.options,e)?r.plan:null,a=!s&&!n&<(i,o)?ct(t):null,l=s??dt(i,o,a?.rowWidths??null,a?.gridWidth??null);return n||Vi.set(t,{options:e,plan:l}),t.style.gridTemplateColumns=l.template,t.style.setProperty("--aia-grid-max-height",l.maxHeight),t.querySelectorAll("[data-aia-option]").forEach((d,c)=>{d.classList.toggle("magicx-aia-option--scroll-hint",!n&&l.scrollHintIndices.includes(c))}),l.cols}function Ui(t,e){if(e.loading||!e.interactive)return null;let n=e.options[K(t)];return n?.is_tappable?n:null}var vr={itemSelector:"[data-aia-option]",onClick:(t,e)=>{let n=Ui(t,e);n&&(t.classList.add("magicx-aia-option--pressed"),e.onSelect(n),setTimeout(()=>t.classList.remove("magicx-aia-option--pressed"),170))},onEnter:(t,e)=>{Ui(t,e)&&e.onHighlight(K(t))},onLeave:(t,e)=>e.onHighlight(-1,K(t))};function Ki(t,e,n,i,o,r,s,a="",l="below",d=!0,c=!0,u=!0,m=!0){let f=t.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"),t.appendChild(f)),U(f,vr,{options:e,onSelect:i,onHighlight:o,loading:s,interactive:m});let h=f.dataset.aiaGroup!==a;f.dataset.aiaGroup=a,Er(f,e,n,r,s,{showIcons:d,showImages:c,showCounts:u});let S=xr(f,e,s);wr(f,e.length,S,s,l),h&&(f.scrollTop=0)}function Er(t,e,n,i,o,r){let s=o?"1":"0",a=t.dataset.aiaGroup??"",{showIcons:l,showImages:d,showCounts:c}=r,u=l?h=>h.icon??h.icon_svg??"":()=>"",m=d?h=>H(h.image_url)??"":()=>"",f=c?h=>fe(h.item_count)??"":()=>"";Q(t,e,{keyOf:h=>`${h.text}\0${u(h)}\0${m(h)}\0${f(h)}\0${s}\0${a}`,create:(h,S)=>{let x=Pr(h,o,r);return o||(x.dataset.aiaEntering=""),x},update:(h,S,x)=>{let g=x===n&&!o;h.id=`${i}-option-${x}`,h.dataset.aiaIndex=String(x),h.setAttribute("aria-selected",String(g)),h.classList.toggle("magicx-aia-option--highlighted",g)}})}function wr(t,e,n,i,o){for(let r of t.querySelectorAll("[data-aia-entering]")){if(!i){let s=Number.parseInt(r.dataset.aiaIndex??"-1",10);s>=0&&r.style.setProperty(Ct,`${It(s,n,e,o)}ms`)}delete r.dataset.aiaEntering}}function Pr(t,e,{showIcons:n,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||!t.is_tappable?-1:0;let s=["magicx-aia-option"];t.is_tappable?s.push("magicx-aia-option--tappable"):s.push("magicx-aia-option--non-tappable"),r.className=s.join(" ");let a=document.createElement("span");a.className="magicx-aia-option-content";let l=i?H(t.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 d=!l&&n&&t.icon_svg?ge(t.icon_svg):null;if(d){let m=document.createElement("span");m.className="magicx-aia-option-icon",m.setAttribute("aria-hidden","true"),m.innerHTML=d,a.appendChild(m),t.icon&&(r.dataset.aiaIcon=t.icon)}let c=document.createElement("span");if(c.className="magicx-aia-option-text",c.textContent=At(t),a.appendChild(c),t.tag){let m=document.createElement("span");m.className="magicx-aia-option-tag",m.textContent=t.tag,a.appendChild(m)}let u=o?fe(t.item_count):null;if(u!==null){let m=document.createElement("span");m.className="magicx-aia-option-count",m.textContent=u,a.appendChild(m),r.dataset.aiaItemCount=String(t.item_count)}return r.appendChild(a),r}var mn="magicx-aia-scroll-arrow",fn="data-aia-scroll-arrow",ne="data-aia-visible",gn=1e3,hn=160,bn="--aia-scroll-arrow-bottom",yn="Scroll down for more options",Tr="[data-aia-products-label]",Cr=4,Ir=8,Or=240;function Ar(t,e,n,i){let o=t.scrollTop,r=n?.requestAnimationFrame,s=t.ownerDocument?.visibilityState==="hidden";if(!r||s||pn(t)){t.scrollTop=o+e,i();return}let a=n.performance?.now?.()??Date.now(),l=()=>n.performance?.now?.()??Date.now(),d=()=>{let c=Math.min(1,(l()-a)/Or),u=1-(1-c)*(1-c);t.scrollTop=o+e*u,c<1?r.call(n,d):i()};r.call(n,d)}function Lr(t=document){let e="http://www.w3.org/2000/svg",n=t.createElementNS(e,"svg");n.setAttribute("viewBox","0 0 16 16"),n.setAttribute("width","18"),n.setAttribute("height","18"),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","1.75"),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false");let i=t.createElementNS(e,"path");return i.setAttribute("d","M4 6.5 8 10.5l4-4"),n.appendChild(i),n}function Yi(t=document){let e=t.createElement("button");return e.type="button",e.tabIndex=-1,e.className=mn,e.setAttribute(fn,""),e.setAttribute("aria-label",yn),e.setAttribute("aria-hidden","true"),e.disabled=!0,e.appendChild(Lr(t)),e}function Rr(t){let e=t.style.gridTemplateColumns.trim();return e?Math.max(1,e.split(/\s+/).length):1}function pn(t){return t.closest('[data-animations="off"]')?!0:!!t.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function Lt({dropdown:t,grid:e,button:n}){let i=e.ownerDocument?.defaultView??(typeof window<"u"?window:null),o=!1;n.disabled=!0;let r=null,s=null,a=null,l=null,d=p=>{if(p){if(n.hasAttribute(ne))return;if(n.setAttribute(ne,""),n.setAttribute("aria-hidden","false"),l!==null&&clearTimeout(l),pn(e)){n.disabled=!1;return}l=setTimeout(()=>{l=null,!o&&n.hasAttribute(ne)&&(n.disabled=!1)},gn)}else n.removeAttribute(ne),n.setAttribute("aria-hidden","true"),l!==null&&clearTimeout(l),l=null,n.disabled=!0},c=p=>{let b=0,y=p;for(;y&&y!==t;)b+=y.offsetTop,y=y.offsetParent instanceof HTMLElement?y.offsetParent:null;return b},u=()=>{let p=t.querySelector(Tr),b;if(p){let y=c(p)+p.offsetHeight/2;b=t.clientHeight-y-n.offsetHeight/2}else{let y=c(e),E=i&&Number.parseFloat(i.getComputedStyle(e).paddingBottom)||0;b=t.clientHeight-(y+e.offsetHeight)+(E>0?0:Ir)}n.style.setProperty(bn,`${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;d(!p&&b>Cr)},f=()=>{if(o)return;u();let p=e.getAttribute("data-aia-group")??"";if(p!==r){r=p,d(!1),s!==null&&clearTimeout(s);let b=e.querySelectorAll("[data-aia-option]").length,y=pn(e)?0:Ot(b,Rr(e));s=setTimeout(()=>{s=null,m()},y);return}m()},h=()=>{o||s!==null||(d(!1),a!==null&&clearTimeout(a),a=setTimeout(()=>{a=null,m()},hn))};e.addEventListener("scroll",h,{passive:!0});let S=p=>p.preventDefault(),x=()=>{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);Ar(e,b,i,h)};n.addEventListener("mousedown",S),n.addEventListener("click",x);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,n.disabled=!0,e.removeEventListener("scroll",h),n.removeEventListener("mousedown",S),n.removeEventListener("click",x),g?.disconnect(),n.removeAttribute(ne),n.setAttribute("aria-hidden","true"))}}}var Dr=[159,119,164];function Dt(t){let e=document.createElement("div");return e.id=t,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",n=>n.preventDefault()),xt(e),e}var Rt=new WeakMap;function Mr(t,e){let n=Rt.get(t);if(n||(n={button:Yi(t.ownerDocument),grid:null,controller:null},t.appendChild(n.button),Rt.set(t,n)),n.grid!==e&&(n.controller?.destroy(),n.controller=null,n.grid=e,e)){n.controller=Lt({dropdown:t,grid:e,button:n.button});return}n.controller?.update()}function Sn(t){let e=Rt.get(t);e&&(e.controller?.destroy(),Rt.delete(t))}function Mt(t,e){let{filteredOptions:n,activeIndex:i,isOpen:o,isLoading:r,pills:s,showPills:a,isActivePillSelected:l,onSelect:d,onHighlight:c,onPillClick:u,onSkip:m}=e,f=s.length>0,h=a&&f,S=n.length>0,x=e.products.length>0,g=o&&(S||h||r||x);if(g?t.classList.add("magicx-aia-dropdown--visible"):t.classList.remove("magicx-aia-dropdown--visible"),r?t.setAttribute("data-aia-loading",""):t.removeAttribute("data-aia-loading"),!g){cn(t,!1);return}x?t.setAttribute("data-aia-has-products",""):t.removeAttribute("data-aia-has-products"),t.toggleAttribute("data-aia-skeleton-exiting",!!e.skeletonExiting);let p=t.querySelector(".aia-stack");p||(p=document.createElement("div"),p.className="aia-stack",p.style.setProperty("--aia-stack-space","8px"),t.appendChild(p));let b=e.showSkipButton&&f&&!e.isInputEmpty,y=h||r&&a||b,E=p.querySelector(".magicx-aia-pill-bar");if(y){E||(E=document.createElement("div"),E.className="magicx-aia-pill-bar aia-cluster",E.setAttribute("data-nowrap",""),E.setAttribute("data-aia-pillbar",""),p.insertBefore(E,p.firstChild));let _=E.querySelector(".magicx-aia-pill-scroll");_||(_=document.createElement("span"),_.className="magicx-aia-pill-scroll",_.setAttribute("data-aia-pill-scroll",""),E.insertBefore(_,E.firstChild)),wt(_,a?s:[],0,u,!0,r&&a,l),Nr(E,b,r||e.skipDisabled,s[0],m)}else E&&E.remove();let w=e.suggestions[0],P=w?`${w.type} ${w.text}`:"",R=v(e.formatType),T=R&&!r;Ki(p,R?[]:n,i,d,c,e.listboxId,r,P,e.optionsPosition??"below",e.showOptionIcons??!0,e.showOptionImages??!0,e.showOptionCounts??!0,!e.skipDisabled),Mr(t,p.querySelector(".aia-grid")),Oi(p,T?n:[],i,e.listboxId,T?e.dateView:null,{selectedIso:e.selectedDateIso,selectedRange:e.selectedDateRange,rangeStart:e.dateRangeStart},{onSelect:d,onHighlight:c,onPreviousMonth:e.onPreviousMonth,onNextMonth:e.onNextMonth},!e.skipDisabled);let I=p.querySelector(".magicx-aia-skeleton-bars");if(r&&(!S||R)){if(!I){I=document.createElement("div"),I.className="magicx-aia-skeleton-bars",I.setAttribute("data-aia-skeleton-bars","");for(let _ of Dr){let ie=document.createElement("span");ie.className="magicx-aia-skeleton-bar",ie.style.width=`${_}px`,I.appendChild(ie)}p.appendChild(I)}}else I&&I.remove();_i(p,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange,e.productsLayout??"row",e.productImageFallback??"image"),cn(t,!0);let X=p.querySelector(".magicx-aia-footer")??Hr(),D=i>=0&&!!n[i]?.is_tappable;Fr(X,St(D,e.isInputEmpty)),X.isConnected||p.appendChild(X),kr(p,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-datepicker",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"])}function kr(t,e){let n=e.map(i=>t.querySelector(`:scope > ${i}`)).filter(i=>i!==null);for(let i=0;i<n.length;i++)t.children[i]!==n[i]&&t.insertBefore(n[i],t.children[i]??null)}var _r={itemSelector:".magicx-aia-skip",onClick:(t,e)=>{e.loading||e.onSkip()}};function Nr(t,e,n,i,o){U(t,_r,{onSkip:o,loading:n});let r=t.querySelector(".magicx-aia-skip");if(!e){r?.remove();return}r||(r=document.createElement("button"),r.type="button",r.tabIndex=-1,r.className="magicx-aia-skip",r.setAttribute("data-aia-skip",""),r.textContent="skip",r.disabled=!0,t.appendChild(r),Y(r)),r.setAttribute("aria-label",i?`Skip ${i.text}`:"Skip"),r.disabled=n}function Fr(t,{key:e,hint:n}){let i=t.querySelector(".magicx-aia-footer-key"),o=t.querySelector(".magicx-aia-footer-hint");!i||!o||(i.textContent!==e&&(i.textContent=e),o.textContent!==n&&(o.textContent=n))}function Hr(){let t=document.createElement("footer");t.className="magicx-aia-footer",t.setAttribute("data-aia-footer","");let e=document.createElement("div");e.className="aia-cluster magicx-aia-footer-row",e.setAttribute("data-align","center"),e.setAttribute("data-justify","between"),e.setAttribute("data-nowrap","");let n=document.createElement("div");n.className="aia-cluster magicx-aia-footer-hint-group",n.setAttribute("data-align","center"),n.style.setProperty("--aia-cluster-gap","5px");let 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",n.append(i,o);let r=document.createElement("a");r.className="aia-cluster magicx-aia-footer-brand-link",r.setAttribute("data-align","center"),r.href=yt(),r.target="_blank",r.rel="noopener noreferrer",r.style.setProperty("--aia-cluster-gap","2px");let s=document.createElement("span");s.className="magicx-aia-footer-brand",s.textContent="AI";let a=document.createElement("span");return a.className="magicx-aia-footer-badge",a.textContent="Autocomplete",r.append(s,a),e.append(n,r),t.append(e),t}function Qi(t,e){let n=Dt(e.listboxId);return t.appendChild(n),{dropdown:n}}function xn(t,e,n){let i=me(e);Mt(t.dropdown,{suggestions:e.editingIdentified?[{type:e.editingIdentified.type,text:B(e.editingIdentified.type),required:!0,options:e.filteredOptions}]:e.dropdownSuggestion??e.actionableSuggestions[0]?[{...e.dropdownSuggestion??e.actionableSuggestions[0],options:e.dropdownOptions}]:[],filteredOptions:e.dropdownOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.dropdownLoading,skeletonExiting:e.skeletonExiting,listboxId:n.listboxId,pills:e.actionableSuggestions,showPills:!0,showSkipButton:n.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:n.showOptionIcons??!0,showOptionImages:n.showOptionImages??!0,showOptionCounts:n.showOptionCounts??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,productsLayout:n.productsLayout??"row",productImageFallback:n.productImageFallback??"image",formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:i.selectedIso,selectedDateRange:i.selectedRange,dateRangeStart:i.rangeStart,optionsPosition:n.optionsPosition??"below",onSelect:n.selectOption,onHighlight:(o,r)=>{r!==void 0&&n.store.get().activeDropdownIndex!==r||n.store.set({activeDropdownIndex:o})},onPillClick:n.setActivePill,onSkip:n.skipActivePill,onPreviousMonth:n.showPreviousMonth,onNextMonth:n.showNextMonth,onProductSelect:n.selectProduct,onProductFocusChange:o=>n.store.set({isFocused:o})})}var Br=6,Wr=.3;function Xi(t){return t<=0?"0px":`${(-Math.min(Wr,2*Br/t)).toFixed(3)}px`}function kt(t){let{input:e,segments:n,newParamId:i,editingParamId:o,placeholderText:r,isFocused:s}=t,a=t.showChipIcons??!0,l=t.showChipImages??!0,d=n.length===0;e.dataset.aiaEmpty=d?"true":"false",Si(e,d?r:"");let c=n.map(p=>p.type==="completed"?`${p.type}:${p.value}${a?p.param.icon??p.param.icon_svg??"":""}${l?H(p.param.image_url)??"":""}`:`${p.type}:${p.value}`).join("\0"),u=e.dataset.segKey??"",m=e.dataset.newParamId??"",f=e.dataset.editingParamId??"";if(c===u&&(i??"")===m&&(o??"")===f)return;if(c===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?k(e):null;e.dataset.segKey=c,e.dataset.newParamId=i??"",e.dataset.editingParamId=o??"";let S=L(e),x=S.createDocumentFragment(),g=0;for(let p of n)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,E=p.param.id===o,w=["magicx-aia-segment","magicx-aia-segment--completed"];y&&w.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),E&&w.push("magicx-aia-segment--editing"),b.className=w.join(" "),b.style.letterSpacing=Xi(p.value.length);let P=l?H(p.param.image_url):null;if(P){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("${P}")`),b.appendChild(T),b.dataset.aiaImage=""}let R=!P&&a&&p.param.icon_svg?ge(p.param.icon_svg):null;if(R){let T=S.createElement("span");T.className="magicx-aia-segment-icon",T.setAttribute("contenteditable","false"),T.setAttribute("aria-hidden","true"),T.innerHTML=R,b.appendChild(T),p.param.icon&&(b.dataset.aiaIcon=p.param.icon)}b.appendChild(S.createTextNode(p.value)),x.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=Xi(p.value.length),b.textContent=p.value,x.appendChild(b)}else x.appendChild(S.createTextNode(p.value));e.replaceChildren(x),e.dataset.aiaTextLength=String(g),h!=null?O(e,Math.max(0,Math.min(h,g))):s&&ri(e)&&O(e,g)}var qr='<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 ji(){let t=document.createElement("button");return t.type="button",t.className="magicx-aia-submit",t.setAttribute("aria-label","Submit"),t.setAttribute("data-aia-submit",""),t.innerHTML=qr,t}function Gr(){let t=document.createElement("div");return t.setAttribute("contenteditable","plaintext-only"),t.contentEditable==="plaintext-only"}function zi(t,e){let n=e.firstElementChild;if(!n){e.removeAttribute("data-aia-pill-wrapped");return}let i=n.getBoundingClientRect(),o=t.getBoundingClientRect();i.top>=o.bottom-2?e.setAttribute("data-aia-pill-wrapped",""):e.removeAttribute("data-aia-pill-wrapped")}function Ji(t,e){let{listboxId:n}=e,i=Dt(n);t.appendChild(i);let o=document.createElement("div");o.className="magicx-aia-input-wrapper",o.setAttribute("data-aia-input-wrapper",""),t.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",Gr()?"plaintext-only":"true"),s.setAttribute("role","combobox"),s.setAttribute("aria-autocomplete","list"),s.setAttribute("aria-haspopup","listbox"),s.setAttribute("aria-controls",n),s.setAttribute("aria-expanded","false"),s.setAttribute("spellcheck","true"),s.setAttribute("enterkeyhint","send"),r.appendChild(s);let a=document.createElement("span");a.className="magicx-aia-pill-list-container",a.setAttribute("data-aia-pill-list-container",""),r.appendChild(a);let l=null,d=null;e.submitButton===void 0?(l=ji(),o.appendChild(l),d=l):e.submitButton!==null&&(d=e.submitButton,d.hasAttribute("data-aia-submit")||d.setAttribute("data-aia-submit",""),d.setAttribute("data-aia-submit-slot",""),o.appendChild(d));let c=new AbortController,{signal:u}=c,m=!1,f=0,h=()=>{let g=we(s),b=g.length>0&&g[0]!==g[0].toUpperCase()?g[0].toUpperCase()+g.slice(1):g;e.handleChange(b)},S=()=>{let g=$(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&&oi(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(k(s)))},{signal:u}),L(s).addEventListener("selectionchange",()=>{let g=$(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(k(s))},{signal:u}),s.addEventListener("click",g=>{let p=Je(s,g.target);p&&(e.startEditingParam(p),Ze(s,p))},{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=L(s),y=Ue(s);if(!y||!s.contains(y.startContainer))return;y.deleteContents();let E=b.createTextNode(p);y.insertNode(E),y.setStartAfter(E),Ee(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}),d&&d.addEventListener("click",g=>{let p=e.store.get();if(!(!!p.text||p.completedParams.length>0)||!e.onSubmit)return;g.stopPropagation(),e.onSubmit(V(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=$(s);(!g||!s.contains(g.node))&&Ee(s,s,0)}if(typeof ResizeObserver<"u"){let g=new ResizeObserver(()=>zi(s,a));g.observe(s),c.signal.addEventListener("abort",()=>g.disconnect(),{once:!0})}return{input:s,inlinePillContainer:a,dropdown:i,submitButton:l,abort:c}}function vn(t,e,n){let{input:i,inlinePillContainer:o,dropdown:r,submitButton:s}=t,{pillPlacement:a,setActivePill:l,selectOption:d,store:c}=n;i.setAttribute("aria-expanded",String(e.isDropdownOpen));let u=e.activeDropdownIndex>=0?`${n.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(kt({input:i,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused,showChipIcons:n.showChipIcons??!0,showChipImages:n.showChipImages??!0}),a==="inline"){let g=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;g||e.actionableSuggestions.length>0?wt(o,e.actionableSuggestions,0,l,!1,g,e.isActivePillSelected):an(o)}else an(o);zi(i,o),f?(i.focus(),O(i,e.caretOffset??e.text.length)):e.isFocused&&we(i)!==e.text&&O(i,e.text.length);let h=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:e.editingIdentified?{type:e.editingIdentified.type,text:B(e.editingIdentified.type),required:!0,options:[]}:null,S=e.dropdownSuggestion??h??e.actionableSuggestions[0],x=me(e);Mt(r,{suggestions:S?[{...S,options:e.dropdownOptions}]:[],filteredOptions:e.dropdownOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.dropdownLoading,skeletonExiting:e.skeletonExiting,listboxId:n.listboxId,pills:h?[h]:e.actionableSuggestions,showPills:a==="dropdown",showSkipButton:n.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:n.showOptionIcons??!0,showOptionImages:n.showOptionImages??!0,showOptionCounts:n.showOptionCounts??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,productsLayout:n.productsLayout??"row",productImageFallback:n.productImageFallback??"image",formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:x.selectedIso,selectedDateRange:x.selectedRange,dateRangeStart:x.rangeStart,optionsPosition:n.optionsPosition??"below",onSelect:d,onHighlight:(g,p)=>{p!==void 0&&c.get().activeDropdownIndex!==p||c.set({activeDropdownIndex:g})},onPillClick:l,onSkip:n.skipActivePill,onPreviousMonth:n.showPreviousMonth,onNextMonth:n.showNextMonth,onProductSelect:n.selectProduct,onProductFocusChange:g=>c.set({isFocused:g})})}function _t(t){let e=t,n=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 d=i.shift();d;d=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[c,u]=d;for(let m of n)m(c,u)}}catch(l){throw i.length=0,l}finally{o=!1}}},subscribe:r=>(n.add(r),()=>{n.delete(r)})}}function Zi(t,e){let n,i,o=r=>(r!==n&&(n=r,i=e(r)),i);return{get:()=>{let r=t.get();return{...r,...o(r)}},set:r=>{typeof r=="function"?t.set(s=>{let a={...s,...o(s)};return r(a)}):t.set(r)},peek:r=>{let s={...t.get(),...r};return{...s,...e(s)}},subscribe:r=>t.subscribe((s,a)=>{let l={...a,...o(a)},d={...s,...o(s)};r(d,l)})}}var En=new WeakSet,eo=new WeakMap;function no(t){return t.nodeType===Node.DOCUMENT_NODE}function $r(t){return no(t)?t:t.ownerDocument}function Vr(t){let e=eo.get(t);if(e)return e;let n=t.defaultView?.CSSStyleSheet;if(typeof n!="function")return null;try{let i=new n;return typeof i.replaceSync!="function"?null:(i.replaceSync(oo),eo.set(t,i),i)}catch{return null}}function to(t,e){if(e.querySelector("style[data-magicx-aia]"))return;let n=t.createElement("style");n.setAttribute("data-magicx-aia",""),n.textContent=oo,e.appendChild(n)}function io(t){if(typeof document>"u")return;let e=t??document;if(En.has(e))return;let n=$r(e);if(no(e)){let r=e.head??e.documentElement;if(!r)return;to(n,r),En.add(e);return}let i=Vr(n),o=e.adoptedStyleSheets;i&&Array.isArray(o)?o.includes(i)||(e.adoptedStyleSheets=[...o,i]):to(n,e),En.add(e)}var oo=`.aia-stack {
|
|
1
|
+
"use strict";var Wt=Object.defineProperty;var po=Object.getOwnPropertyDescriptor;var mo=Object.getOwnPropertyNames;var fo=Object.prototype.hasOwnProperty;var go=(t,e)=>{for(var n in e)Wt(t,n,{get:e[n],enumerable:!0})},ho=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of mo(e))!fo.call(t,o)&&o!==n&&Wt(t,o,{get:()=>e[o],enumerable:!(i=po(e,o))||i.enumerable});return t};var bo=t=>ho(Wt({},"__esModule",{value:!0}),t);var ts={};go(ts,{AIAutocomplete:()=>Bt,ATTRIBUTION_URL:()=>sn,DATE_RANGE_META_END:()=>ke,DATE_RANGE_META_START:()=>Me,DEFAULT_OPTION_COUNT_UNIT:()=>un,ModeController:()=>he,OPTIONS_GRID_MOBILE_QUERY:()=>Pe,OPTION_ENTER_DELAY_VAR:()=>Ct,OPTION_ENTER_FADE_MS:()=>Fi,OPTION_ENTER_RISE_MS:()=>Hi,OPTION_ENTER_RISE_PX:()=>Bi,OPTION_ENTER_STAGGER_MS:()=>Ni,PLACEHOLDER_FADE_OUT_MS:()=>gi,PLACEHOLDER_LEAVING_ATTR:()=>te,PLACEHOLDER_SWAP_GAP_MS:()=>hi,PLACEHOLDER_TYPE_MS:()=>mi,PLACEHOLDER_WORD_PAUSE_MS:()=>fi,PRODUCT_PATH_PREFIX:()=>tn,PRODUCT_ROW_PX_PER_LINE:()=>Ri,RANGE_SEPARATOR:()=>Kt,SCROLL_ARROW_ATTR:()=>fn,SCROLL_ARROW_BOTTOM_VAR:()=>bn,SCROLL_ARROW_CLASS:()=>mn,SCROLL_ARROW_FADE_MS:()=>gn,SCROLL_ARROW_LABEL:()=>yn,SCROLL_ARROW_SCROLL_IDLE_MS:()=>hn,SCROLL_ARROW_VISIBLE_ATTR:()=>ne,SKIPPED_PARAM_TEXT:()=>Qt,WEEKDAY_LABELS:()=>ye,addMonths:()=>Ie,attachProductRowWheel:()=>Pt,attachScrollArrow:()=>Lt,buildAttributionUrl:()=>yt,buildDateOptions:()=>Oe,buildQuery:()=>A,buildSubmitResult:()=>U,cellDay:()=>Le,cellIso:()=>N,chipIdFromTap:()=>Je,computeOptionsGridLayout:()=>rn,containScroll:()=>xt,createStore:()=>_t,cursorIsAtEnd:()=>et,dateCellMarks:()=>Et,dateSelectionFor:()=>me,extractPlainText:()=>we,formatAbsoluteDate:()=>j,formatDate:()=>Gt,formatDateRange:()=>Yt,formatOptionCount:()=>fe,getCursorOffset:()=>k,getFooterHint:()=>St,identifiedParamLabel:()=>B,isCalendarFormat:()=>v,isOptionsGridMobileViewport:()=>ut,isoDate:()=>M,keepCaretOnChip:()=>Ze,measureOptionsGrid:()=>ct,monthLabel:()=>Ce,needsOptionsGridMeasurement:()=>lt,optionCountLabel:()=>Wi,optionEnterDelayMs:()=>It,optionHasImage:()=>qi,optionImageSrc:()=>H,optionLabel:()=>At,optionsEntranceDurationMs:()=>Ot,optionsGridTemplateColumns:()=>at,parseDate:()=>Se,parseLooseDate:()=>W,parseLooseDateRange:()=>z,plainTextLength:()=>ze,planOptionsGrid:()=>dt,previousGraphemeBoundary:()=>tt,productFromMatchedItem:()=>nn,productInitial:()=>Tt,productRowWheelTarget:()=>ln,productsFromCustomFields:()=>rt,renderEditableContent:()=>kt,resolveFormatType:()=>q,resolveIdentifiedDate:()=>De,sameOptionRows:()=>pt,sanitizeOptionIconSvg:()=>ge,scrollCaretIntoView:()=>Qe,selectedIsoFromText:()=>Ae,selectedRangeFor:()=>se,setCursorOffset:()=>O,toWireIdentifiedParams:()=>ae,visibleDateRange:()=>vt,withSkippedParams:()=>le});module.exports=bo(ts);function qt(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9]+/).filter(Boolean).map(e=>e.toLowerCase())}function B(t){let e=qt(t);return e.length>0?e.join(" "):t}var re=["January","February","March","April","May","June","July","August","September","October","November","December"],ye=["S","M","T","W","T","F","S"],On=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],An="aiaDate",Ln="aiaDay",Cn=t=>String(t).padStart(2,"0");function M(t){return`${t.getFullYear()}-${Cn(t.getMonth()+1)}-${Cn(t.getDate())}`}function $t(t){return new Date(t.getFullYear(),t.getMonth(),t.getDate())}function yo(t){let e=$t(t).getTime()-$t(new Date).getTime();return Math.round(e/864e5)}function Gt(t){let e=yo(t);return e>=0&&e<7?On[t.getDay()]:j(t)}function j(t){return t.getFullYear()===new Date().getFullYear()?`${re[t.getMonth()]} ${t.getDate()}`:`${re[t.getMonth()]} ${t.getDate()} ${t.getFullYear()}`}function Se(t){if(!t)return null;let e=On.findIndex(a=>a.toLowerCase()===t.trim().toLowerCase());if(e>=0){let a=$t(new Date),l=(e-a.getDay()+7)%7;return new Date(a.getFullYear(),a.getMonth(),a.getDate()+l)}let n=/^\s*([A-Za-z]+)\s+(\d{1,2})(?:\s+(\d{4}))?\s*$/.exec(t);if(!n)return null;let i=re.findIndex(a=>a.toLowerCase()===n[1].toLowerCase());if(i<0)return null;let o=Number(n[2]),r=n[3]?Number(n[3]):new Date().getFullYear(),s=new Date(r,i,o);return s.getMonth()!==i||s.getDate()!==o?null:s}function Ce(t){return`${re[t.month]} ${t.year}`}function Ut(){let t=new Date;return{year:t.getFullYear(),month:t.getMonth()}}function Rn(t){return{year:t.getFullYear(),month:t.getMonth()}}function Ie(t,e){let n=new Date(t.year,t.month+e,1);return{year:n.getFullYear(),month:n.getMonth()}}function In(){return{text:"",is_tappable:!1,kind:null}}function Oe(t){let e=new Date(t.year,t.month,1).getDay(),n=new Date(t.year,t.month+1,0).getDate(),i=[];for(let o=0;o<e;o++)i.push(In());for(let o=1;o<=n;o++){let r=new Date(t.year,t.month,o);i.push({text:Gt(r),is_tappable:!0,kind:null,metadata:{[An]:M(r),[Ln]:o}})}for(;i.length%ye.length!==0;)i.push(In());return i}function Ae(t){let e=Se(t);return e?M(e):null}function N(t){let e=t?.metadata?.[An];return typeof e=="string"?e:null}function Le(t){let e=t?.metadata?.[Ln];return typeof e=="number"?e:null}function So(t){return t.replace(/(\d+)(?:st|nd|rd|th)\b/g,"$1")}function Dn(t){let e=t.toLowerCase().replace(/\.$/,"");return e.length<3?-1:re.findIndex(n=>n.toLowerCase().startsWith(e))}function xo(t,e,n){let i=new Date(n.getFullYear(),t,e);if(i.getMonth()!==t||i.getDate()!==e)return null;let o=new Date(n.getFullYear(),n.getMonth(),n.getDate());if(i>=o)return i;let r=new Date(n.getFullYear()+1,t,e);return r.getMonth()===t&&r.getDate()===e?r:null}function Mn(t,e,n){let i=new Date(t,e,n);return i.getMonth()===e&&i.getDate()===n?i:null}function W(t,e={}){if(!t)return null;let n=e.today??new Date,i=So(t.trim().toLowerCase()).replace(/\s+/g," "),o=/^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(i);if(o){let l=Mn(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=Dn(r[1]);if(l>=0)return Re(l,Number(r[2]),r[3],n)}let s=/^(\d{1,2}) (?:of )?([a-z]+)\.?(?:,? (\d{4}))?$/.exec(i);if(s){let l=Dn(s[2]);if(l>=0)return Re(l,Number(s[1]),s[3],n)}let a=/^(\d{1,2})[/\-.](\d{1,2})(?:[/\-.](\d{2,4}))?$/.exec(i);if(a){let l=Number(a[1]),d=Number(a[2]);return l>12&&d<=12?Re(d-1,l,a[3],n):d>12&&l<=12?Re(l-1,d,a[3],n):null}return null}function Re(t,e,n,i){if(n){if(n.length!==4)return null;let r=Mn(Number(n),t,e);return r?M(r):null}let o=xo(t,e,i);return o?M(o):null}function De(t,e={}){let n=t.isoDate;return typeof n=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(n)?n:W(t.text,e)}var Kt=" - ",Me="aiaDateRangeStart",ke="aiaDateRangeEnd";function xe(t,e){return t<=e?{start:t,end:e}:{start:e,end:t}}var Vt=/^\d{4}-\d{2}-\d{2}$/;function kn(t){if(!Vt.test(t))return null;let[e,n,i]=t.split("-").map(Number),o=new Date(e,n-1,i);return o.getMonth()===n-1&&o.getDate()===i?o:null}var vo=/\s+(?:to|through|thru|until|til|till)\s+/g,Eo=/[-–—]/g;function wo(t){let e=[];for(let n of[vo,Eo]){n.lastIndex=0;let i=n.exec(t);for(;i!==null;)e.push([t.slice(0,i.index),t.slice(i.index+i[0].length)]),i=n.exec(t)}return e}function z(t,e={}){if(!t)return null;let n=new Set,i=null;for(let[o,r]of wo(t.trim())){let s=W(o.trim(),e);if(!s)continue;let a=W(r.trim(),e);!a||a<s||(n.add(`${s}|${a}`),i={start:s,end:a})}return n.size===1?i:null}function Yt(t){let e=kn(t.start),n=kn(t.end);return!e||!n?"":t.start===t.end?j(e):`${j(e)}${Kt}${j(n)}`}function _n(t,e){let n=xe(t,e);return{text:Yt(n),is_tappable:!0,kind:null,metadata:{[Me]:n.start,[ke]:n.end}}}function se(t,e={}){let n=t?.metadata?.[Me],i=t?.metadata?.[ke];return typeof n=="string"&&typeof i=="string"&&Vt.test(n)&&Vt.test(i)?xe(n,i):z(t?.text,e)}function v(t){return t==="date"||t==="date-range"}var Po=new Set(["date","dates"]),To=new Set(["range","ranges","span","period","window"]),Nn=3;function Co(t){let e={single:0,range:0};if(!t)return e;for(let n of t)n.is_tappable&&(z(n.text)!==null?e.range+=1:W(n.text)!==null&&(e.single+=1));return e}function q(t){if(!t)return"options";let e=t.formatType;if(e==="date"||e==="options"||e==="date-range")return e;let n=Co(t.options);if(n.single+n.range>=Nn&&n.range>n.single)return"date-range";let i=qt(t.type);return i.some(o=>Po.has(o))?i.some(o=>To.has(o))?"date-range":"date":n.single>=Nn?"date":"options"}var _e=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 Io="https://api.ai-autocomplete.com",Ne=`${Io}/api/suggest`,Fn=new WeakMap;function ve(t){return t?.type==="accessToken"}function Oo(t){if(!(!t||ve(t)))return t}function Fe(t){let e=Fn.get(t.getAccessToken);return e||(e=new _e(t),Fn.set(t.getAccessToken,e)),e}function He(t){return{"Content-Type":"application/json",...t?.appIdentifier&&{"X-App-Identifier":t.appIdentifier},...t?.headers}}function Be(t){let e=Oo(t),n=e?.apiKey;return n?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(n)}`:`Bearer ${n}`:null}function ae(t){return t.map(e=>({type:e.type,value:e.text}))}var Qt="skipped";function le(t,e){if(e.length===0)return t;let n=new Set(t.map(o=>o.type)),i=e.filter(o=>!n.has(o.type)).map(o=>({placeholder:"",type:o.type,text:Qt,kind:null}));return i.length>0?[...t,...i]:t}var Ao="0.35.0",Hn=!1;function Lo(t,e){return{placeholder:t.placeholder,type:t.type,...e&&{text:t.value??t.text},kind:t.kind}}function Ro(t,e,n,i,o,r,s,a,l,d){let c=e.find(m=>m.type==="contact"&&m.metadata?.contact_account_count)?.metadata?.contact_account_count,u=typeof c=="number"?c:void 0;return{data:{raw_query:t,completed_params:le(e.map(m=>Lo(m,n)),l??[]),...s&&s.length>0&&{identified_params:ae(s)},...a&&a.length>0&&{recently_suggested:a},...u!=null&&{contact_account_count:u},...d!==void 0&&{additional_context:d}},meta:{request_id:o,request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:Ao,session_id:i,source:r}}}async function Bn(t,e,n,i,o){return fetch(t,{method:"POST",headers:{...e,Authorization:`Bearer ${n}`},body:i,signal:o})}async function Wn(t,e,n){let i=n.apiConfig,o=!n.maskCompletedText,r=Ro(t,e,o,n.sessionId,n.requestId??crypto.randomUUID(),n.source,n.identifiedParams,n.recentlySuggested,n.skippedParams,n.additionalContext),s=He(i),a=i?.endpoint??Ne,l=JSON.stringify(r);if(ve(i)){let u=Fe(i),m=await u.getToken(),f=await Bn(a,s,m,l,n.signal);if(f.status===401){let h=await u.getToken(!0);f=await Bn(a,s,h,l,n.signal)}if(!f.ok)throw new Error(`API error: ${f.status} ${f.statusText}`);return f.json()}let d=Be(i);!d&&!Hn&&(Hn=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),d&&(s.Authorization=d);let c=await fetch(a,{method:"POST",headers:s,body:l,signal:n.signal});if(!c.ok)throw new Error(`API error: ${c.status} ${c.statusText}`);return c.json()}var We=/[\p{L}\p{N}]/u,Do=/['\u2019-]/;function qn(t,e,n){let i=t[e];if(i===void 0)return!1;if(We.test(i))return!0;let o=t[e+n];return Do.test(i)&&o!==void 0&&We.test(o)}function Mo(t,e,n){let i=e+n.length;return!(We.test(n[0])&&qn(t,e-1,-1)||We.test(n[n.length-1])&&qn(t,i,1))}function F(t,e,n=0,i=()=>!0){if(e.length===0)return t.indexOf(e,n);let o=-1,r=t.indexOf(e,n);for(;r!==-1;){if(i(r)){if(Mo(t,r,e))return r;o===-1&&(o=r)}r=t.indexOf(e,r+1)}return o}function A(t,e){let n=t,i={},o=[],r=[],s=0;for(let a of e){let l=(i[a.type]??0)+1;i[a.type]=l;let c=`{{${a.type.toUpperCase().replace(/\s+/g,"_")}_${l}}}`,u=f=>F(n,a.text,f,h=>!r.some(S=>h<S.end&&h+a.text.length>S.start)),m=u(s);if(m===-1&&(m=u(0)),m!==-1){n=n.slice(0,m)+c+n.slice(m+a.text.length);let f=c.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+c.length}),s=m>=s?m+c.length:s+f}o.push({...a,placeholder:c})}return{rawQuery:n,completedParams:o}}function $(t,e,n){return e>0||!n?e:t.toLowerCase().startsWith(n.toLowerCase())?n.length:e}function qe(t,e,n){return e===0&&t.length>0&&n.length>0&&n.toLowerCase().startsWith(t.toLowerCase())}function J(t,e,n){let i=t.slice(e);if(n||e===0||t[e-1]===" ")return i;let o=i.indexOf(" ");return o===-1?"":i.slice(o+1)}function $n(t,e){let n=t.trimEnd().replace(/\s+/g," ");if(n.length===0||e.length===0)return 0;let i=n.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=n.length-s.length;return t.length-a}}return 0}function Z(t,e){if(!t)return[];let n=e.trimStart();if(!n)return t;let i=n.toLowerCase();return t.filter(o=>!o.is_tappable||o.text.toLowerCase().includes(i))}function de(t,e){if(!t)return null;let n=e.trim();if(!n)return null;let i=n.toLowerCase();return t.find(o=>o.is_tappable&&o.text.toLowerCase()===i)??null}function Gn(t,e){return e?t.map(n=>e[n.type]?{...n,options:[]}:n):t}function Un(t,e){let n=0,i=e;for(let o of t)n+=o.value.length,o.type!=="text"&&(i=Math.max(i,n));return i}function Vn(t,e){let n=0;for(let i of t){let o=n+i.value.length;if(i.type==="text"&&o>e&&i.value.slice(Math.max(e-n,0)).trim().length>0)return!1;n=o}return!0}function Kn(t,e){let n=[],i=new Set;for(let o of[...t,...e])o.type==="placeholder"||i.has(o.type)||(i.add(o.type),n.push({type:o.type,text:o.text}));return n}function Yn(t,e,n){if(t===e)return n;let i=Math.min(t.length,e.length),o=0;for(;o<i&&t[o]===e[o];)o++;if(o>=n)return n;let r=0;for(;r<i-o&&t[t.length-1-r]===e[e.length-1-r];)r++;return t.length-r<=n?n+(e.length-t.length):null}function $e(t,e){let n=[],i=[],o=0;for(let r of e){let s=F(t,r.text,o);if(s===-1){i.push(r);continue}n.push({start:s,end:s+r.text.length,param:r}),o=s+r.text.length}return{located:n,missing:i}}function Qn(t,e){let{located:n}=$e(t,e);return n.length>0?n[n.length-1].end:0}function Xn(t,e,n){let i=[],o=[],r=0;for(let s of n){let a=F(t,s.text,r,l=>!e.some(d=>l<d.end&&l+s.text.length>d.start));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 jn(t,e,n=[]){let i=$e(t,e).located,o=Xn(t,i,n).located,r=[...i.map(d=>({start:d.start,end:d.end,segment:{type:"completed",value:d.param.text,param:d.param}})),...o.map(d=>({start:d.start,end:d.end,segment:{type:"identified",value:d.param.text,param:d.param}}))].sort((d,c)=>d.start-c.start),s=[],a=0;for(let d of r)d.start>a&&s.push({type:"text",value:t.slice(a,d.start)}),s.push(d.segment),a=d.end;let l=t.slice(a);return l&&s.push({type:"text",value:l}),s}function zn(t,e){let{located:n,missing:i}=$e(t,e);return{valid:n.map(o=>o.param),invalid:i}}function Ge(t,e,n){let i=$e(t,e).located,{located:o,missing:r}=Xn(t,i,n);return{valid:o.map(s=>s.param),invalid:r}}function ko(t){if(t instanceof Error)return t;try{return new Error(String(t))}catch{return new Error("Unknown error")}}var _o=100,No=300,Fo=2,Ue=class{constructor(e,n,i,o,r,s,a,l,d={}){this.store=e;this.getApiConfig=n;this.getOptionOverrides=i;this.getMaskCompletedText=o;this.getOnError=r;this.getSessionId=s;this.getSource=a;this.getAdditionalContext=l;this.callbacks=d;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null}start(){this.doFetch("",[]);let e=this.store.get().text,n=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(i=>{(i.text!==e||i.completedParams!==n)&&(e=i.text,n=i.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,n){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?Kn(s.pendingSpan.snapshot,s.actionableSuggestions):void 0,l=crypto.randomUUID(),d=await Wn(e,n,{sessionId:this.getSessionId(),requestId:l,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=(d.data.input??[]).filter(w=>w.source==="identified").map(w=>({id:crypto.randomUUID(),type:w.type,text:w.text})),u=Gn(d.data.suggestions??[],this.getOptionOverrides()),m=d.data.input??[],f=m[m.length-1],h=this.store.get().text,S,x;if(f?.state==="in_progress"){x=!0;let w=h.toLowerCase().lastIndexOf(f.text.toLowerCase());S=w!==-1?w:r}else x=!1,S=r;let p=u.filter(w=>w.type!=="placeholder")[0],b=null;if(p&&!v(q(p))){let w=J(h,S,x),P=de(p.options,w);P&&(b={id:crypto.randomUUID(),placeholder:"",type:p.type,text:P.text,value:P.value,kind:P.kind,suggestionType:p.type,suggestionPlaceholder:p.text,options:p.options??[],metadata:P.metadata,icon:P.icon,icon_svg:P.icon_svg,image_url:P.image_url},u=u.filter(R=>R!==p),this.callbacks.onAutoMatch?.({active:p,matched:P,rawQuery:e}))}let y=d.data.custom_fields??null,E=this.callbacks.productsForResponse?.(y);this.store.set(w=>{let P=b?[...w.completedParams,b]:w.completedParams,R=Ge(w.text,P,c).valid,T=new Set(s.skippedParams.map(D=>D.id)),I=new Set(w.skippedParams.filter(D=>!T.has(D.id)).map(D=>D.type));return{suggestions:I.size>0?u.filter(D=>D.type==="placeholder"||!I.has(D.type)):u,isLoading:!1,isReady:d.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:S,filterInProgress:x,identifiedParams:R,customFields:y,...E!==void 0?{products:E}:{},...b?{completedParams:P}:{}}}),this.callbacks.onResponse?.({requestId:l,funnelTelemetry:d.meta?.funnel_telemetry===!0})}catch(s){let a=ko(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(Fo)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},_o),this.slowDebounceTimer=setTimeout(()=>this.attemptFetch(1),No)}attemptFetch(e,n=!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=$(i.text,i.filterBase,r),a=J(i.text,s,i.filterInProgress),d=i.suggestions.filter(y=>y.type!=="placeholder")[0],c=v(i.activeFormatType),m=(d&&!c?Z(d.options,a):[]).filter(y=>y.is_tappable),f=d&&!c?de(d.options,a)!==null:!1,h=a.trim().length>0;if(m.length>0&&!f&&h||qe(i.text,i.completedParams.length,r))return!1;let{rawQuery:S,completedParams:x}=A(i.text,i.completedParams),g=S.length<i.lastRawQuery.length,p=Math.abs(S.length-i.lastRawQuery.length),b=n&&S!==i.lastRawQuery;return g||p>=e||b?(this.doFetch(S,x),!0):!1}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};function Ho(t){return t.nodeType===Node.DOCUMENT_NODE?!0:t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t}function ee(t){let e=typeof t.getRootNode=="function"?t.getRootNode():null;return e&&Ho(e)?e:t.ownerDocument??t}function L(t){return t.ownerDocument??t}function Bo(t){return t.nodeType===Node.DOCUMENT_FRAGMENT_NODE}function Jn(t){let e=ee(t);return!Bo(e)||typeof e.getSelection=="function"?null:e}function Zn(t){let e=Jn(t);if(!e)return null;let n=L(t).getSelection?.();return!n||typeof n.getComposedRanges!="function"?null:e}function ei(t,e){let n=t,i;try{i=n.getComposedRanges({shadowRoots:[e]})}catch{i=n.getComposedRanges(e)}return i.length>0?i[0]:null}function Xt(t){let n=ee(t).getSelection?.();return n||(L(t).getSelection?.()??null)}function G(t){let e=Xt(t);if(!e||e.rangeCount===0)return null;let n=Zn(t);if(n){let i=ei(e,n);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 Ve(t){let e=Xt(t);if(!e||e.rangeCount===0)return null;let n=Zn(t);if(!n)return e.getRangeAt(0);let i=ei(e,n);if(!i)return null;let o=L(t).createRange();return o.setStart(i.startContainer,i.startOffset),o.setEnd(i.endContainer,i.endOffset),o}function Ee(t,e,n){let i=Xt(t);if(!i)return null;if(Jn(t))return i.collapse(e,n),i;let o=L(t).createRange();return o.setStart(e,n),o.collapse(!0),i.removeAllRanges(),i.addRange(o),i}function Ke(t,e){let n=t?ee(t):typeof document<"u"?document:null;return n?typeof n.getElementById=="function"?n.getElementById(e):typeof document<"u"?document.getElementById(e):null:null}var Ye=2,Wo="magicx-aia";function ti(t){return t==="auto"||t==="scroll"||t==="hidden"||t==="overlay"}function qo(t){let e=L(t),n=e.defaultView;if(!n?.getComputedStyle)return null;let i=t;for(;i&&i!==e.body&&i!==e.documentElement;){let o=i.scrollWidth>i.clientWidth,r=i.scrollHeight>i.clientHeight;if(o||r){let s=n.getComputedStyle(i);if(o&&ti(s.overflowX)||r&&ti(s.overflowY))return i}if(i.classList.contains(Wo))return null;i=i.parentElement}return null}function Qe(t){let e=Ve(t);if(!e||!e.collapsed||!t.contains(e.startContainer))return;let n=qo(t);if(!n||typeof e.getBoundingClientRect!="function")return;let i=e.getBoundingClientRect();if(i.height===0)return;let o=n.getBoundingClientRect();if(n.scrollWidth>n.clientWidth){let r=o.left+n.clientLeft,s=r+n.clientWidth;i.right>s?n.scrollLeft+=i.right-s+Ye:i.left<r&&(n.scrollLeft-=r-i.left+Ye)}if(n.scrollHeight>n.clientHeight){let r=o.top+n.clientTop,s=r+n.clientHeight;i.bottom>s?n.scrollTop+=i.bottom-s+Ye:i.top<r&&(n.scrollTop-=r-i.top+Ye)}}var ii='[contenteditable="false"]',zt="strong[data-param-id]",ce;function $o(){if(ce!==void 0)return ce;let t=globalThis.Intl.Segmenter;if(!t)return ce=null,null;try{ce=new t(void 0,{granularity:"grapheme"})}catch{ce=null}return ce??null}function Xe(t,e){let n=t;for(;n&&n!==e;){if(n.nodeType===Node.ELEMENT_NODE&&n.matches(ii))return!0;n=n.parentNode}return!1}function je(t){return L(t).createTreeWalker(t,NodeFilter.SHOW_TEXT,{acceptNode(e){return Xe(e,t)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function we(t){let e=je(t),n="",i=e.nextNode();for(;i;)n+=i.data,i=e.nextNode();return n}function ze(t){let e=je(t),n=0,i=e.nextNode();for(;i;)n+=i.data.length,i=e.nextNode();return n}function k(t){let e=G(t);if(!e)return null;let n=e.node,i=e.offset;if(!t.contains(n))return null;if(n.nodeType===Node.ELEMENT_NODE){let o=n;if(Xe(o,t)&&o!==t)return null;let r=0;for(let s=0;s<i&&s<o.childNodes.length;s++)r+=Jt(o.childNodes[s],t);return r+jt(o,t)}return n.nodeType!==Node.TEXT_NODE||Xe(n,t)?null:jt(n,t)+i}function Jt(t,e){if(t.nodeType===Node.TEXT_NODE)return Xe(t,e)?0:t.data.length;if(t.nodeType!==Node.ELEMENT_NODE)return 0;let n=t;if(n.matches(ii))return 0;let i=0;for(let o of Array.from(n.childNodes))i+=Jt(o,e);return i}function jt(t,e){let n=je(e),i=0,o=n.nextNode();for(;o;){if(o===t||t.nodeType===Node.ELEMENT_NODE&&t.contains(o))return i;i+=o.data.length,o=n.nextNode()}return i}function O(t,e){let n=L(t),i=Math.max(0,Math.min(e,ze(t))),o=je(t),r=0,s=null,a=0,l=o.nextNode(),d=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,d=l,l=o.nextNode()}let c=n.createRange();if(s){let u=s.parentElement?.closest('strong[data-seg="completed"]');u&&u!==t&&t.contains(u)?a===0?c.setStartBefore(u):a===s.data.length?c.setStartAfter(u):c.setStart(s,a):c.setStart(s,a)}else d?c.setStart(d,d.data.length):c.setStart(t,0);c.collapse(!0),Ee(t,c.startContainer,c.startOffset)&&(Go(t,c,i),Qe(t))}function ni(t,e){if(!t||!e.contains(t))return null;let i=(t.nodeType===Node.ELEMENT_NODE?t:t.parentElement)?.closest(zt)??null;return i&&e.contains(i)?i:null}function Go(t,e,n){let i=ni(G(t)?.node??null,t);if(i&&i!==ni(e.startContainer,t)){t.dataset.aiaCaretEscapedChip=`${n}:${i.dataset.paramId}`;return}delete t.dataset.aiaCaretEscapedChip}function oi(t,e){let n=t.dataset.aiaCaretEscapedChip;if(!n)return!1;let i=k(t);return i!==null&&n===`${i}:${e}`}function ri(t){return ee(t).activeElement===t}function Je(t,e){if(!e||e.nodeType===void 0)return null;let n=e,o=(n.nodeType===Node.ELEMENT_NODE?n:n.parentElement)?.closest(zt);if(!o||!t.contains(o))return null;let r=G(t);return r&&!r.collapsed?null:o.dataset.paramId??null}function Ze(t,e){let n=null;for(let s of t.querySelectorAll(zt))if(s.dataset.paramId===e){n=s;break}if(!n)return;let i=jt(n,t),o=i+Jt(n,t),r=k(t);r!=null&&r>=i&&r<=o||O(t,i)}function et(t){let e=k(t);return e==null?!1:e>=ze(t)}function tt(t,e){if(e<=0)return 0;let n=$o();if(!n)return e-1;let i=t.slice(0,e),o=0;for(let{index:r}of n.segment(i))r<e&&(o=r);return o}function U(t,e,n=[],i={}){let{rawQuery:o,completedParams:r}=A(t,e);return{query:t.trim(),raw_query:o,completed_params:le(r,n),identified_params:ae(i.identifiedParams??[]),is_ready:i.isReady??!1,...i.customFields?{custom_fields:i.customFields}:{}}}function Zt(t,e){return t instanceof HTMLTextAreaElement||t instanceof HTMLInputElement?t.selectionStart!=null&&t.selectionStart===t.value.length:t instanceof HTMLElement&&t.hasAttribute("data-aia-input")?et(t):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function en(t){return t instanceof HTMLElement&&t.hasAttribute("data-aia-input")?k(t):null}var nt=class{constructor(e,n){this.store=e;this.ctx=n}handleKeyDown(e){let n=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 d=this.ctx.getOptionsPosition()==="above";switch(e.key){case"ArrowDown":{let c=Zt(e.target,n),u=!!n.editingParam;if(!c&&!u&&n.activeDropdownIndex<0)break;if(n.activeDropdownIndex<0){if(d)break;e.preventDefault();let h=v(n.activeFormatType)?this.dateEntryIndex(n,!1):l[0]??0;if(!n.isDropdownOpen&&n.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:h});break}if(l.length===0)return;this.store.set({activeDropdownIndex:h});break}if(e.preventDefault(),l.length===0)return;if(v(n.activeFormatType)){this.stepDateWeek(n,7);break}if(n.filteredOptions.length>0){let h=Math.floor((n.filteredOptions.length-1)/s);if(Math.floor(n.activeDropdownIndex/s)===h){this.store.set({activeDropdownIndex:-1});break}}let m=l.indexOf(n.activeDropdownIndex),f=m<l.length-1?m+1:0;this.store.set({activeDropdownIndex:l[f]});break}case"ArrowUp":{if(n.activeDropdownIndex<0){if(!d)break;let m=Zt(e.target,n),f=!!n.editingParam;if(!m&&!f)break;e.preventDefault();let h=v(n.activeFormatType)?this.dateEntryIndex(n,!0):this.firstTappableInBottomRow(s)??l[0]??0;if(!n.isDropdownOpen&&n.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:h});break}if(l.length===0)return;this.store.set({activeDropdownIndex:h});break}if(l.length===0)break;if(e.preventDefault(),v(n.activeFormatType)){this.stepDateWeek(n,-7);break}if(n.activeDropdownIndex<s){this.store.set({activeDropdownIndex:-1});break}let c=l.indexOf(n.activeDropdownIndex),u=c>0?c-1:l.length-1;this.store.set({activeDropdownIndex:l[u]});break}case"ArrowRight":{if(n.activeDropdownIndex>=0){if(e.preventDefault(),v(n.activeFormatType)){this.stepDateDay(n,1);break}if(n.activeDropdownIndex%s<s-1){let m=n.activeDropdownIndex+1;m<n.filteredOptions.length&&n.filteredOptions[m]?.is_tappable&&this.store.set({activeDropdownIndex:m})}break}if(n.editingParam&&e.target instanceof HTMLElement&&n.editingTail!=null){e.preventDefault();let u=e.target.closest("[data-aia-input]")??e.target,m=n.editingTail;this.ctx.exitEditMode?.(),O(u,m);break}Zt(e.target,n)&&n.actionableSuggestions.length>=1&&(e.preventDefault(),this.ctx.skipActivePill());break}case"ArrowLeft":{if(n.activeDropdownIndex>=0){if(e.preventDefault(),v(n.activeFormatType)){this.stepDateDay(n,-1);break}if(n.activeDropdownIndex%s>0){let c=n.activeDropdownIndex-1;c>=0&&n.filteredOptions[c]?.is_tappable&&this.store.set({activeDropdownIndex:c});break}if(!n.editingParam&&this.ctx.startEditingParamAtCaret){let c=en(e.target);c!=null&&this.ctx.startEditingParamAtCaret(c)}break}if(n.editingParam&&e.target instanceof HTMLElement&&n.editingAnchor!=null){e.preventDefault();let c=e.target.closest("[data-aia-input]")??e.target,u=n.editingAnchor;this.ctx.exitEditMode?.(),O(c,u);break}if(this.ctx.startEditingParamAtCaret){let c=en(e.target);c!=null&&this.ctx.startEditingParamAtCaret(c)&&e.preventDefault()}break}case"Backspace":{if(n.editingParam||!this.ctx.removeParamAtCaret)break;let c=en(e.target);if(c==null)break;this.ctx.removeParamAtCaret(c)&&e.preventDefault();break}case"Enter":{e.preventDefault(),n.activeDropdownIndex>=0&&n.filteredOptions[n.activeDropdownIndex]?.is_tappable?this.clickOrSelect(n.activeDropdownIndex,n.filteredOptions,i,r):a&&a(U(n.text,n.completedParams,n.skippedParams,{identifiedParams:n.identifiedParams,isReady:n.isReady,customFields:n.customFields}))&&this.ctx.afterSubmit?.();break}case"Tab":{let c=n.filteredOptions.map((f,h)=>f.is_tappable?h:-1).filter(f=>f!==-1);if(c.length===0)break;if(!n.isDropdownOpen){if(n.actionableSuggestions.length===0)break;e.preventDefault();let f=e.shiftKey?c[c.length-1]:c[0];this.store.set({pillTapped:!0,activeDropdownIndex:f});break}e.preventDefault();let u=c.indexOf(n.activeDropdownIndex),m;if(u<0)m=e.shiftKey?c.length-1:0;else{let f=e.shiftKey?-1:1;m=(u+f+c.length)%c.length}this.store.set({activeDropdownIndex:c[m]});break}case"Escape":{if(n.dateRangeStart){this.store.set({pendingRangeStart:null});break}if(n.editingIdentified){this.ctx.exitEditingIdentified?.(),this.store.set({activeDropdownIndex:-1});break}if(n.editingParam&&e.target instanceof HTMLElement&&n.editingTail!=null){let c=e.target.closest("[data-aia-input]")??e.target,u=n.editingTail;this.ctx.exitEditMode?.(),O(c,u)}this.store.set({activeDropdownIndex:-1});break}}}firstTappableInBottomRow(e){let n=this.store.get();if(n.filteredOptions.length===0)return null;let o=Math.floor((n.filteredOptions.length-1)/e)*e;for(let r=o;r<n.filteredOptions.length;r++)if(n.filteredOptions[r]?.is_tappable)return r;return null}dateEntryIndex(e,n){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(n?r[r.length-1]:r[0])??0}stepDateDay(e,n){for(let i=e.activeDropdownIndex+n;i>=0&&i<e.filteredOptions.length;i+=n)if(e.filteredOptions[i]?.is_tappable){this.store.set({activeDropdownIndex:i});return}}stepDateWeek(e,n){let i=e.activeDropdownIndex+n;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 n=Ke(e,this.ctx.listboxId);if(!n)return this.ctx.columns;let o=Ke(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===n)break;o=o.parentElement}return this.ctx.columns}clickOrSelect(e,n,i,o){let r=Ke(o,`${i}-option-${e}`);r?r.click():this.ctx.selectOption(n[e])}};var it=class{constructor(e,n,i={}){this.store=e;this.getOverrides=n;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,n){return this.hasOverride(e)&&!this.missCovers(e,n)}tick(e,n){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(n>1&&!s&&r<n)return"owns"}return this.ask(i),"asked"}sync(e){let n=this.resolveTarget(e);if(!n){this.current&&(this.cancel(),this.current=null),e.optionSearch&&this.store.set({optionSearch:null});return}this.current&&this.current.key===n.key||this.ask(n)}resolveTarget(e){if(v(e.activeFormatType)||e.editingIdentified)return null;let n=e.editingParam;if(n&&e.editingAnchor!=null)return this.hasOverride(n.suggestionType)?{mode:"edit",key:n.id,type:n.suggestionType,suggestion:{type:n.suggestionType,text:n.suggestionPlaceholder,required:!0,options:n.options},query:e.optionQuery}:null;let 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,n){return this.lastMiss!=null&&this.lastMiss.type===e&&this.lastMiss.query===n}ask(e){this.cancel();let n=this.getOverrides()?.[e.type],i=++this.version;if(!n||this.missCovers(e.type,e.query)){this.current={key:e.key,type:e.type,query:e.query,abort:null},this.setSearch(e,"done");return}let o=new AbortController;this.current={key:e.key,type:e.type,query:e.query,abort:o};let r;try{r=n(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,n,i,o){let r;try{let s=await n;if(i.aborted||o!==this.version)return;r=Array.isArray(s)?s:[]}catch(s){if(i.aborted||o!==this.version||Uo(s))return;this.logOnce(s),r=[]}this.commit(e,r,o)}commit(e,n,i){if(i!==this.version)return;let o=this.resolveTarget(this.store.get());if(!o||o.key!==e.key)return;n.length===0?this.lastMiss={type:e.type,query:e.query}:this.lastMiss?.type===e.type&&(this.lastMiss=null);let r={type:e.type,query:e.query,status:"done"};if(e.mode==="edit")this.store.set(s=>({editingParam:s.editingParam&&s.editingParam.id===e.key?{...s.editingParam,options:n}:s.editingParam,optionSearch:r}));else{let s={...e.suggestion,options:n};this.current&&this.current.key===e.key&&(this.current.key=s),this.store.set(a=>({suggestions:a.suggestions.map(l=>l===e.suggestion?s:l),optionSearch:r}))}n.length===0?this.callbacks.onMiss?.(e.mode,e.query):this.callbacks.onAnswer?.(e.mode,e.query)}setSearch(e,n){let i=this.store.get().optionSearch;i&&i.type===e.type&&i.query===e.query&&i.status===n||this.store.set({optionSearch:{type:e.type,query:e.query,status:n}})}cancel(){this.current?.abort?.abort(),this.version++}logOnce(e){this.hasLoggedError||(this.hasLoggedError=!0,console.warn("[AIAutocomplete] an optionOverrides entry threw or rejected \u2014 treated as no options. Later failures on this instance are not logged.",e))}};function Uo(t){return t instanceof Error&&t.name==="AbortError"}var ot=class{constructor(e,n={}){this.store=e;this.callbacks=n}setActivePill(e){let n=this.store.get(),i=n.suggestions.filter(d=>d.type!=="placeholder");if(e<0||e>=i.length)return;let o=i[e],r=i.filter((d,c)=>c!==e),s=n.suggestions.filter(d=>d.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:d}=A(n.text,n.completedParams);this.callbacks.onPillSelected({rawQuery:d,selectedPill:o.text,otherPills:r.map(c=>c.text)})}let a=[...s,o,...r],l=this.store.peek({suggestions:a}).filteredOptions.findIndex(d=>d.is_tappable);this.store.set({suggestions:a,pillTapped:!0,activeDropdownIndex:l})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(n=>({completedParams:n.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};var tn="/products/",si="https://relative.invalid";function Vo(t){if(!t)return;let e;try{e=new URL(t,`${si}/`)}catch{return}if(!(e.protocol!=="http:"&&e.protocol!=="https:"))return t.startsWith("/")?e.origin===si?t:void 0:/^https?:\/\//i.test(t)?t:void 0}function nn(t){let e=Vo(t.item_url)??Ko(t);return{id:t.source_id,title:t.title,...e&&{url:e},imageUrl:t.image_url||null,...t.price&&{price:t.price},...t.vendor&&{vendor:t.vendor},...typeof t.available=="boolean"&&{available:t.available}}}function Ko(t){if(!t.handle)return;let e=`${tn}${encodeURIComponent(t.handle)}`;return t.variant_id?`${e}?variant=${encodeURIComponent(t.variant_id)}`:e}function rt(t){return(t?.items.matched??[]).map(nn)}var st=class{constructor(e,n,i=()=>!0){this.store=e;this.getConfig=n;this.isEnabled=i;this.hasLoggedError=!1}forResponse(e){if(!this.isEnabled())return[];if(!this.getConfig())return rt(e)}async run(e,n,i){if(!this.isEnabled())return;let o=this.getConfig();if(!o)return;if(e.trim().length===0){this.clear(i);return}let r=()=>n.aborted||!i()||!this.owns(o);try{let s=await o.fetch(e,n);if(r())return;let a=o.transform(s),l=Array.isArray(a)?a:[],d=o.limit!=null?l.slice(0,o.limit):l;if(r())return;this.commit(d)}catch(s){if(n.aborted||Yo(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 Yo(t){return t instanceof Error&&t.name==="AbortError"}var Pe="(max-width: 768px)";var Qo="var(--aia-option-row-height, 37px)",Xo="var(--aia-grid-scroll-top, 0px) + var(--aia-grid-scroll-bottom, 0px)";function rn(t,e){return e?on(1,Math.min(t,5)):on(1,Math.min(t,4))}function on(t,e){return{cols:t,rows:e,maxHeight:`calc(${e} * ${Qo} + ${Xo})`}}function lt(t,e){return!e&&t>=5}function dt(t,e,n,i){if(!(!e&&t>=5&&jo(n,i))){let s=rn(t,e);return{...s,template:at(s.cols),scrollHintIndices:!e&&t>s.rows?[s.rows-1]:[]}}let r=6;return{...on(2,3),template:at(2),scrollHintIndices:t>r?[r-2,r-1]:[]}}function jo(t,e){return!t||t.length===0||e==null||e<=0||t.some(i=>i<=0)?!1:Math.ceil(Math.max(...t))*2<=e}function ct(t){if(typeof document>"u")return null;let e=Array.from(t.querySelectorAll("[data-aia-option]"));if(e.length===0)return null;let n=document.createElement("div");n.style.cssText="position:absolute;visibility:hidden;left:-9999px;top:0;";for(let s of e){let a=s.cloneNode(!0);a.removeAttribute("id"),a.removeAttribute("role"),a.removeAttribute("aria-selected"),a.style.whiteSpace="nowrap",a.style.width="max-content",n.appendChild(a)}t.appendChild(n);let i=Array.from(n.children).map(s=>s.offsetWidth);n.remove();let o=getComputedStyle(t),r=t.clientWidth-(Number.parseFloat(o.paddingLeft)||0)-(Number.parseFloat(o.paddingRight)||0)-(Number.parseFloat(o.columnGap)||0);return{rowWidths:i,gridWidth:r}}function at(t){return Array.from({length:t},()=>"minmax(0,1fr)").join(" ")}function ut(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(Pe).matches}function pt(t,e){return!t||t.length!==e.length?!1:t.every((n,i)=>n.text===e[i].text)}function ai(t,e){let n=e.dropdownTrigger??"auto",i=e.closeDropdownOnBlur??!0,s=t.filteredOptionsLength>0||t.activePillHasNoOptions||t.hasProducts;if(t.inEditMode){let a=i?t.isFocused:!0;return s&&a}if(n==="auto"){let a=i?t.isFocused:!0,l=t.text.replace(/\s+$/,"").length,d=t.caretOffset==null||t.caretOffset>=l;return(s||t.isLoading)&&a&&d}return n==="manual"?(s||t.isLoading)&&t.pillTapped:!1}function Te(t){if(t.editingIdentified){let{type:n,anchor:i}=t.editingIdentified;return`identified:${n}@${i}`}return t.editingParam!=null&&t.editingAnchor!=null?`edit:${t.editingParam?.id}`:`pill:${t.actionableSuggestions[0]?.type??""}`}function li(t){if(!t)return Ut();let[e,n]=t.split("-").map(Number);return{year:e,month:n-1}}function zo(t){let e=Se(t);return e?Rn(e):Ut()}function di(t,e){let n=jn(t.text,t.completedParams,t.identifiedParams),i=t.suggestions.filter(C=>C.type!=="placeholder"),o=i[0],r=t.suggestions.filter(C=>C.type==="placeholder").map(C=>C.text).join(" "),s=$(t.text,Math.min(t.filterBase,t.text.length),r),l=s===0&&qe(t.text,t.completedParams.length,r)?"":J(t.text,s,t.filterInProgress),d=o?.options??[],c=t.editingParam!=null&&t.editingAnchor!=null,u,m,f,h;if(c&&t.editingParam&&t.editingAnchor!=null){let C=t.editingParam.id,oe=t.completedParams.some(uo=>uo.id===C),be=t.caretOffset??t.editingAnchor,Tn=oe?"":t.text.slice(t.editingAnchor,be);m=Tn.trim(),f=t.editingParam.options,h=t.editingParam.suggestionType,u=Z(t.editingParam.options,Tn)}else m=l.trim(),f=d,h=o?.type,u=Z(d,l);let S=t.optionSearch,x=S!=null&&h!=null&&S.type===h;x&&S.status==="done"&&S.query===m&&(u=f);let g=x&&S.status==="loading",p=e.showNonTappableOptions===!1;p&&(u=u.filter(C=>C.is_tappable));let b=t.editingIdentified,y=c?t.editingParam&&{type:t.editingParam.suggestionType,options:t.editingParam.options}:o,E=b?b.format:q(y),w=c&&v(E)?se(t.editingParam):null;w&&(E="date-range");let P=null,R=null;if(v(E)){let C=Te({...t,actionableSuggestions:i}),oe=t.dateViewMonth;P=oe&&oe.key===C?{year:oe.year,month:oe.month}:b?li(b.iso):w?li(w.start):zo(t.editingParam?.text),u=Oe(P);let be=t.pendingRangeStart;E==="date-range"&&be&&be.key===C&&(R=be.iso)}let T=C=>p?C.is_tappable:!0,I;if(c){let C=t.editingParam?.options??[];I=t.editingParam!=null&&C.filter(T).length===0}else I=o!=null&&d.filter(T).length===0;let X=ai({inEditMode:c||b!=null,filteredOptionsLength:u.length,isFocused:t.isFocused,text:t.text,caretOffset:t.caretOffset,isLoading:t.isLoading||g,pillTapped:t.pillTapped,activePillHasNoOptions:I,hasProducts:t.products.length>0},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),D=X&&t.activeDropdownIndex>=0&&!!u[t.activeDropdownIndex]?.is_tappable,_=t.skeletonOptions!==null&&t.skeletonRequested&&!t.isLoading&&!t.editingParam&&!t.inSelectionAnimation,ie=t.isLoading&&!t.editingParam&&!t.inSelectionAnimation||g||_,Pn=ie&&t.skeletonOptions!==null,lo=Pn&&t.skeletonOptions?t.skeletonOptions:u,co=Pn?t.skeletonSuggestion:null;return{segments:n,actionableSuggestions:i,filteredOptions:u,dropdownLoading:ie,dropdownOptions:lo,dropdownSuggestion:co,skeletonExiting:_,activeFormatType:E,dateView:P,dateRangeStart:R,placeholderText:r,optionQuery:m,isSearchingOptions:g,isDropdownOpen:X,isActivePillSelected:D}}function mt(t){return t.mode==="fresh"?Jo(t):Zo(t)}function Jo(t){let{text:e,completedParams:n,suggestions:i,filterBase:o,filterInProgress:r}=t,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(" "),d=$(e,o,l),c=J(e,d,r),u=de(a.options,c);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,x=e.slice(h,S),p=S<e.length&&e[S]===" "?S+1:S,b={id:crypto.randomUUID(),placeholder:"",type:a.type,text:x,value:u.value,kind:u.kind,suggestionType:a.type,suggestionPlaceholder:a.text,options:a.options??[],metadata:u.metadata,icon:u.icon,icon_svg:u.icon_svg,image_url:u.image_url};return{patch:{text:e,completedParams:[...n,b],suggestions:i.filter(y=>y!==a),filterBase:p,newParamId:b.id,caretOffset:p,activeDropdownIndex:-1},caretPos:p}}function Zo(t){let{text:e,completedParams:n,editingParam:i,editingAnchor:o,editingTail:r}=t;if(n.some(b=>b.id===i.id))return null;let s=e.slice(o,r),a=de(i.options,s);if(!a)return null;let l=a.text.toLowerCase(),d=s.toLowerCase().lastIndexOf(l),c=o+Math.max(0,d),u=c+a.text.length,m=e.slice(c,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},x=n.length,g=0;for(let b=0;b<n.length;b++){let y=F(e,n[b].text,g);if(y!==-1){if(y>=f){x=b;break}g=y+n[b].text.length}}let p=[...n];return p.splice(x,0,S),{patch:{text:e,completedParams:p,newParamId:S.id,filterBase:h,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:h,activeDropdownIndex:-1},caretPos:h}}var er=6e4;function tr(t){return typeof TextEncoder>"u"?t.length*3:new TextEncoder().encode(t).length}function nr(t){return(t??Ne).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function ir(t){return ve(t)?`Bearer ${await Fe(t).getToken()}`:Be(t)}async function ci(t){try{let e=nr(t.apiConfig?.endpoint),n=He(t.apiConfig),i=await ir(t.apiConfig);i&&(n.Authorization=i);let o=JSON.stringify({source:t.source,session_id:t.sessionId,...t.visitorId&&{visitor_id:t.visitorId},...t.requestId&&{request_id:t.requestId},type:t.type,at:new Date().toISOString(),query_data:t.queryData});await fetch(e,{method:"POST",headers:n,body:o,...t.keepalive&&tr(o)<=er&&{keepalive:!0}})}catch{}}function ue(t,e){let n=t.findIndex(i=>i.text===e);return n>=0?n+1:null}function ui(t,e){let n=t.actionableSuggestions[0];if(!n)return null;let i=t.filterBase,o=t.text.slice(0,i),r=o.length===0&&t.text.length===0,s=o.length===0&&t.text.length>0&&t.placeholderText.length>0&&t.placeholderText.toLowerCase().startsWith(t.text.toLowerCase());(r||s)&&t.placeholderText&&(o=`${t.placeholderText} `);let a=Math.min(Qn(t.text,t.completedParams),o.length),l=$n(o.slice(a),e.text);l>0&&(o=o.slice(0,o.length-l));let d=o.length>0&&o[o.length-1]!==" ",c=`${o}${d?" ":""}${e.text} `,u=(r||s)&&c.length>0?c[0].toUpperCase()+c.slice(1):c,m=u.toLowerCase().lastIndexOf(e.text.toLowerCase()),f=m>=0?u.slice(m,m+e.text.length):e.text,h={id:crypto.randomUUID(),placeholder:"",type:n.type,text:f,value:e.value,kind:e.kind,suggestionType:n.type,suggestionPlaceholder:n.text,options:n.options??[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url},S=t.actionableSuggestions.length-1;return{patch:{text:u,filterBase:u.length,completedParams:[...t.completedParams,h],newParamId:h.id,caretOffset:u.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:!0,inSelectionAnimation:!0,pendingSpan:null},telemetry:{selectedOption:e.text,otherOptions:t.filteredOptions.filter(x=>x.text!==e.text).map(x=>x.text),key:n.type,position:ue(n.options??[],e.text)},consumedSuggestion:n,remainingActionable:S}}function ft(t){let e=v(t.activeFormatType)||t.filteredOptions.length===0?null:t.filteredOptions,n=t.editingParam,i=n?{type:n.suggestionType,text:n.suggestionPlaceholder,required:!0,options:n.options}:t.actionableSuggestions[0]??null;return{skeletonOptions:e,skeletonSuggestion:e?i:null,skeletonRequested:!1}}function gt(t,e,n){let i=t.slice(0,e),o=t.slice(n),r=(i===""||i.endsWith(" "))&&o.startsWith(" ");return r&&(o=o.slice(1)),{text:i+o,removed:n-e+(r?1:0)}}var ht=class{constructor(e){this.deps=e}start(e){let n=this.deps.store.get();if(n.editingParam?.id===e)return;let i=n.completedParams.find(s=>s.id===e);if(!i)return;let o=0,r=-1;for(let s of n.completedParams){let a=F(n.text,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 n=this.deps.store.get(),i=n.editingParam,o=n.editingAnchor,r=n.editingTail;if(!i||o==null||r==null||!n.completedParams.some(l=>l.id===i.id))return!1;let{text:s}=e===""?gt(n.text,o,r):{text:n.text.slice(0,o)+e+n.text.slice(r)},a=o+e.length;return this.deps.store.set(l=>({text:s,completedParams:l.completedParams.filter(d=>d.id!==i.id),editingTail:a,caretOffset:a,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(a),this.promoteIfExact(),!0}caretAfterInput(e){let n=this.deps.store.get(),i={caretOffset:e};n.editingParam&&n.editingAnchor!=null&&e!=null&&(e<n.editingAnchor?(i.editingParam=null,i.editingAnchor=null,i.editingTail=null,i.activeDropdownIndex=-1):n.editingTail!=null&&(i.editingTail=Math.max(n.editingTail,e))),this.deps.store.set(i),this.promoteIfExact()}caretMove(e){let n=this.deps.store.get();if(n.editingParam&&n.editingAnchor!=null&&n.editingTail!=null&&e!=null&&(e<n.editingAnchor||e>n.editingTail)){this.deps.store.set({caretOffset:e,editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1});return}this.deps.store.set({caretOffset:e})}selectOption(e){let n=this.deps.store.get(),i=n.editingParam,o=n.editingAnchor,r=n.editingTail;if(!i||o==null||r==null)return;this.deps.fireTelemetry("option",{raw_query:A(n.text,n.completedParams).rawQuery,selected_option:e.text,other_options:i.options.filter(g=>g.text!==e.text).map(g=>g.text),key:i.suggestionType,position:ue(i.options,e.text)});let s=n.text.slice(0,o),a=n.text.slice(r),l=o===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,c=a.length===0||a[0]!==" "?`${l} `:l,u=s+c+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=n.completedParams.findIndex(g=>g.id===i.id),S=n.completedParams.filter(g=>g.id!==i.id),x=h>=0?Math.min(h,S.length):S.length;S.splice(x,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,...ft(n)}),this.deps.startSelectionAnimationTimer(),this.deps.scheduleSetCursor(m),this.deps.fetchNow()}promoteIfExact(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let n=mt({mode:"edit",text:e.text,completedParams:e.completedParams,editingParam:e.editingParam,editingAnchor:e.editingAnchor,editingTail:e.editingTail});n&&(this.deps.store.set(n.patch),this.deps.scheduleSetCursor(n.caretPos))}};var mi=33,fi=70,gi=120,hi=50,te="data-aia-placeholder-leaving",pe=new WeakMap;function bt(t){t.timer!==null&&(clearTimeout(t.timer),t.timer=null)}function or(t){return t.closest('[data-animations="off"]')?!0:!!t.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function bi(t,e,n){e.shown=n,t.dataset.placeholder=e.target.slice(0,n)}function yi(t,e){if(e.timer=null,!t.isConnected||e.shown>=e.target.length||(bi(t,e,e.shown+1),e.shown>=e.target.length))return;let n=e.target[e.shown-1],i=n===" "||n==="-"?70:0;e.timer=setTimeout(()=>yi(t,e),33+i)}function pi(t,e){bi(t,e,0),e.timer=setTimeout(()=>yi(t,e),33)}function Si(t,e){let n=pe.get(t);if(e===""){n&&(bt(n),pe.delete(t)),t.removeAttribute(te),delete t.dataset.placeholder;return}if(n?.target===e)return;if(or(t)){n&&bt(n),t.removeAttribute(te),pe.set(t,{target:e,shown:e.length,timer:null}),t.dataset.placeholder=e;return}let i={target:e,shown:0,timer:null},o=n&&n.shown>0?n:null;if(n&&bt(n),pe.set(t,i),o){t.setAttribute(te,""),i.timer=setTimeout(()=>{i.timer=null,t.removeAttribute(te),t.isConnected&&pi(t,i)},170);return}t.removeAttribute(te),pi(t,i)}function xi(t){let e=pe.get(t);e&&(bt(e),pe.delete(t))}var sn="https://ai-autocomplete.com";function yt(t=sn){try{if(typeof window>"u"||!window.location)return t;let e=window.location.hostname;if(!e)return t;let n=new URL(t);return n.searchParams.set("utm_source",e),n.toString()}catch{return t}}function St(t,e){return t?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}function xt(t){let e=s=>{s.ctrlKey||vi(s.target,t,s.deltaX,s.deltaY)||s.preventDefault()},n=0,i=0,o=s=>{let a=s.touches[0];a&&(n=a.clientX,i=a.clientY)},r=s=>{if(s.touches.length!==1)return;let a=s.touches[0],l=n-a.clientX,d=i-a.clientY;n=a.clientX,i=a.clientY,s.cancelable&&!vi(s.target,t,l,d)&&s.preventDefault()};return t.addEventListener("wheel",e,{passive:!1}),t.addEventListener("touchstart",o,{passive:!0}),t.addEventListener("touchmove",r,{passive:!1}),()=>{t.removeEventListener("wheel",e),t.removeEventListener("touchstart",o),t.removeEventListener("touchmove",r)}}function vi(t,e,n,i){let o=t instanceof Element?t:null;for(;o;){if(i!==0&&rr(o,i)||n!==0&&sr(o,n))return!0;if(o===e)break;o=o.parentElement}return!1}var Ei=/^(auto|scroll|overlay)$/;function rr(t,e){return t.scrollHeight<=t.clientHeight||!Ei.test(getComputedStyle(t).overflowY)?!1:e>0?t.scrollTop+t.clientHeight<t.scrollHeight-1:t.scrollTop>0}function sr(t,e){if(t.scrollWidth<=t.clientWidth)return!1;let n=getComputedStyle(t);if(!Ei.test(n.overflowX))return!1;let i=Math.abs(t.scrollLeft),o=t.scrollWidth-t.clientWidth;return(n.direction==="rtl"?e<0:e>0)?i<o-1:i>0}var wi=new WeakMap,Pi=new WeakSet;function V(t,e,n){if(wi.set(t,n),Pi.has(t))return;Pi.add(t);let i=()=>wi.get(t),o=r=>{if(!(r instanceof Element))return null;let s=r.closest(e.itemSelector);return s&&t.contains(s)?s:null};e.onClick&&t.addEventListener("click",r=>{let s=o(r.target);s&&e.onClick?.(s,i(),r)}),e.onEnter&&t.addEventListener("mouseenter",r=>{let s=r.target;s instanceof HTMLElement&&s.matches(e.itemSelector)&&e.onEnter?.(s,i())},!0),e.onLeave&&t.addEventListener("mouseleave",r=>{let s=r.target;s instanceof HTMLElement&&s.matches(e.itemSelector)&&e.onLeave?.(s,i())},!0),e.preventMousedown&&t.addEventListener("mousedown",r=>r.preventDefault())}function K(t){return Number.parseInt(t.dataset.aiaIndex??"-1",10)}function Y(t){t.offsetWidth}var ar={selectedIso:null,selectedRange:null,rangeStart:null};function me(t){if(!v(t.activeFormatType))return ar;let e=t.editingIdentified;if(e){let{iso:i,isoEnd:o}=e;return{selectedIso:o?null:i,selectedRange:i&&o?xe(i,o):null,rangeStart:t.dateRangeStart}}let n=se(t.editingParam);return{selectedIso:n?null:Ae(t.editingParam?.text),selectedRange:n,rangeStart:t.dateRangeStart}}function vt(t){return t.pendingStart?xe(t.pendingStart,t.highlightedIso??t.pendingStart):t.selected}function Et(t,e){if(t==null)return{selected:!1,inRange:!1};let{selectedIso:n,range:i}=e,o=t===n||i!=null&&(t===i.start||t===i.end),r=i!=null&&t>i.start&&t<i.end;return{selected:o,inRange:r}}var Ti="data-aia-key";function Q(t,e,n){let i=new Map;for(let s of Array.from(t.children)){let a=s.getAttribute(Ti);a!=null&&i.set(a,s)}let o=new Set,r=[];for(let s=0;s<e.length;s++){let a=e[s],l=n.keyOf(a,s);o.add(l);let d=i.get(l);d||(d=n.create(a,s),d.setAttribute(Ti,l)),n.update?.(d,a,s),t.children[s]!==d&&t.insertBefore(d,t.children[s]??null),r.push(d)}for(let[s,a]of i)o.has(s)||a.remove();return r}function Ci(t,e){if(!e.interactive)return null;let n=e.options[K(t)];return n?.is_tappable?n:null}var lr={itemSelector:"[data-aia-date-cell], [data-aia-date-prev], [data-aia-date-next]",onClick:(t,e)=>{if(t.hasAttribute("data-aia-date-prev")){e.callbacks.onPreviousMonth();return}if(t.hasAttribute("data-aia-date-next")){e.callbacks.onNextMonth();return}let n=Ci(t,e);n&&(t.classList.add("magicx-aia-date-cell--pressed"),e.callbacks.onSelect(n),setTimeout(()=>t.classList.remove("magicx-aia-date-cell--pressed"),170))},onEnter:(t,e)=>{t.hasAttribute("data-aia-date-cell")&&Ci(t,e)&&e.callbacks.onHighlight(K(t))},onLeave:(t,e)=>{t.hasAttribute("data-aia-date-cell")&&e.callbacks.onHighlight(-1,K(t))}};function Oi(t,e,n,i,o,r,s,a=!0){let l=t.querySelector(".magicx-aia-datepicker");if(!o||e.length===0){l?.remove();return}if(!l){l=ur(),t.appendChild(l),Y(l);for(let u of l.querySelectorAll(".magicx-aia-datepicker-nav"))u.disabled=!1}V(l,lr,{options:e,callbacks:s,interactive:a});let d=l.querySelector(".magicx-aia-datepicker-month");d&&(d.textContent=Ce(o));let c=l.querySelector(".magicx-aia-datepicker-grid");c&&dr(c,e,n,i,r)}function dr(t,e,n,i,o){let r=M(new Date),s=vt({pendingStart:o.rangeStart,highlightedIso:N(e[n]),selected:o.selectedRange});Q(t,e,{keyOf:(a,l)=>N(a)??`pad-${l}`,create:a=>cr(a),update:(a,l,d)=>{let c=N(l),u=Et(c,{selectedIso:o.selectedIso,range:s}),m=d===n&&l.is_tappable;a.id=`${i}-option-${d}`,a.dataset.aiaIndex=String(d),a.setAttribute("aria-selected",String(m)),a.classList.toggle("magicx-aia-date-cell--past",c!=null&&c<r),a.classList.toggle("magicx-aia-date-cell--highlighted",m),a.classList.toggle("magicx-aia-date-cell--today",c!=null&&c===r),a.classList.toggle("magicx-aia-date-cell--selected",u.selected),a.classList.toggle("magicx-aia-date-cell--in-range",u.inRange)}})}function cr(t){let e=document.createElement("div");e.setAttribute("role","option"),e.setAttribute("data-aia-option",""),e.setAttribute("data-aia-date-cell","");let n=Le(t);if(n==null)return e.className="magicx-aia-date-cell magicx-aia-date-cell--blank",e.setAttribute("aria-hidden","true"),e.tabIndex=-1,e;e.className="magicx-aia-date-cell magicx-aia-date-cell--day",e.tabIndex=0,e.setAttribute("aria-label",t.text);let i=document.createElement("span");return i.className="magicx-aia-date-cell-number",i.textContent=String(n),e.appendChild(i),e}function ur(){let t=document.createElement("div");t.className="magicx-aia-datepicker",t.setAttribute("data-aia-datepicker","");let e=document.createElement("div");e.className="magicx-aia-datepicker-header";let n=document.createElement("span");n.className="magicx-aia-datepicker-month",n.setAttribute("data-aia-date-month",""),n.setAttribute("aria-live","polite"),e.append(Ii("prev","Previous month","\u2039"),n,Ii("next","Next month","\u203A"));let i=document.createElement("div");i.className="magicx-aia-datepicker-weekdays",i.setAttribute("aria-hidden","true");for(let r of ye){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",""),t.append(e,i,o),t}function Ii(t,e,n){let i=document.createElement("button");return i.type="button",i.tabIndex=-1,i.className="magicx-aia-datepicker-nav",i.setAttribute(`data-aia-date-${t}`,""),i.setAttribute("aria-label",e),i.textContent=n,i.disabled=!0,i}var pr={itemSelector:"[data-aia-pill]",onClick:(t,e)=>{if(e.loading||t.disabled)return;let n=Number.parseInt(t.dataset.aiaPillIndex??"-1",10);n>=0&&e.onSelectPill(n)},preventMousedown:!0},Ai=[125,69];function Li(t,e){return e?1:t===0?.7:t===1?.4:.2}function wt(t,e,n,i,o=!1,r=!1,s=!1){let a=t.querySelector(".magicx-aia-pill-list");if(a||(a=document.createElement("span"),a.className="magicx-aia-pill-list",t.appendChild(a)),V(a,pr,{onSelectPill:i,loading:r}),r&&e.length===0){a.setAttribute("data-aia-pill-list-loading",""),a.innerHTML="";for(let l=0;l<Ai.length;l++){let d=Ai[l],c=document.createElement("span");c.setAttribute("data-aia-pill-skeleton",""),c.className=`magicx-aia-pill magicx-aia-pill--skeleton${o?" magicx-aia-pill--rounded":""}`,c.style.width=`${d}px`,c.style.opacity=String(Li(l,!1)),a.appendChild(c)}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();Q(a,e,{keyOf:l=>`${l.type}-${l.text}`,create:l=>{let d=document.createElement("button");return d.type="button",d.tabIndex=-1,d.setAttribute("data-aia-pill",""),d.setAttribute("contenteditable","false"),d.textContent=l.text,d.disabled=!0,d},update:(l,d,c)=>{let u=l,m=s&&c===n&&!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(Li(c,m)),u.dataset.aiaPillIndex=String(c),r?u.setAttribute("data-aia-loading",""):u.removeAttribute("data-aia-loading")}}),Y(a);for(let l of a.querySelectorAll("[data-aia-pill]"))l.disabled=r}function an(t){t.querySelector(".magicx-aia-pill-list")?.remove()}var Ri=32;function ln(t,e){if(e.ctrlKey)return null;let n=e.deltaY||0,i=e.deltaX||0;if(!n||Math.abs(i)>=Math.abs(n))return null;let o=t.scrollWidth-t.clientWidth;if(o<=1)return null;let r=t.scrollLeft,s=n;return e.deltaMode===1?s*=32:e.deltaMode===2&&(s*=t.clientWidth),Math.max(0,Math.min(o,r+s))}function Pt(t){let e=n=>{let i=ln(t,n);i!==null&&(n.preventDefault(),t.scrollLeft=i)};return t.addEventListener("wheel",e,{passive:!1}),()=>t.removeEventListener("wheel",e)}var Di=Intl.Segmenter,Mi=Di?new Di(void 0,{granularity:"grapheme"}):null;function Tt(t){let e=t.trim().normalize("NFC").toUpperCase();if(Mi)for(let n of Mi.segment(e))return n.segment;return Array.from(e)[0]??"?"}var dn=new WeakMap,ki=new WeakMap,mr="Products";function _i(t,e,n,i,o,r="row",s="image"){let a=t.querySelector(".magicx-aia-products");if(e.length===0){a?.remove();return}if(!a){a=document.createElement("section"),a.className="magicx-aia-products",a.setAttribute("data-aia-products",""),a.setAttribute("role","group"),a.setAttribute("aria-labelledby",`${n}-products-label`);let d=document.createElement("div");d.className="magicx-aia-products-label",d.id=`${n}-products-label`,d.setAttribute("data-aia-products-label",""),d.textContent=mr;let c=document.createElement("div");c.className="magicx-aia-products-row",c.setAttribute("data-aia-products-row",""),Pt(c),a.append(d,c),t.appendChild(a)}a.setAttribute("data-aia-products-layout",r);let l=a.querySelector(".magicx-aia-products-row");if(l){Q(l,e,{keyOf:d=>gr(d),create:d=>hr(d,i,o,s),update:(d,c,u)=>{d.id=`${n}-product-${u}`,d.dataset.aiaIndex=String(u),ki.get(d)?.(s)}}),Y(l);for(let d of l.querySelectorAll("[data-aia-product]")){let c=dn.get(d);c&&(dn.delete(d),c())}}}function cn(t,e){let n=t.querySelectorAll("[data-aia-product]");for(let i of n)i.tabIndex=e?0:-1}var fr="Sold out";function gr(t){return[t.id,t.title,t.url,t.imageUrl,t.price,t.vendor,t.available===!1?"sold-out":""].map(e=>e??"").join("\0")}function hr(t,e,n,i){let o=document.createElement("a");o.className="magicx-aia-product",o.setAttribute("data-aia-product",""),o.setAttribute("role","option"),o.setAttribute("aria-selected","false"),o.tabIndex=0;let r=document.createElement("span");r.className="magicx-aia-product-media",r.setAttribute("aria-hidden","true");let s=t.imageUrl?.trim(),a=!!s,l=()=>{r.replaceChildren(),r.toggleAttribute("data-aia-product-placeholder",i==="image"),r.toggleAttribute("data-aia-product-initial",i==="initial"),i==="initial"&&(r.textContent=Tt(t.title))};if(ki.set(o,u=>{u!==i&&(i=u,a||l())}),s){let u=document.createElement("img");u.onerror=()=>{a=!1,l()},u.className="magicx-aia-product-image",u.src=s,u.alt="",u.loading="lazy",u.decoding="async",r.appendChild(u)}else l();o.appendChild(r);let d=document.createElement("span");if(d.className="magicx-aia-product-body",t.vendor){let u=document.createElement("span");u.className="magicx-aia-product-vendor",u.textContent=t.vendor,d.appendChild(u)}let c=document.createElement("span");if(c.className="magicx-aia-product-title",c.textContent=t.title,d.appendChild(c),t.price){let u=document.createElement("span");u.className="magicx-aia-product-price",u.textContent=t.price,d.appendChild(u)}if(t.available===!1){o.setAttribute("data-aia-product-sold-out","");let u=document.createElement("span");u.className="magicx-aia-product-badge",u.textContent=fr,d.appendChild(u)}return o.appendChild(d),dn.set(o,()=>{t.url&&(o.href=t.url),o.addEventListener("click",u=>{u.metaKey||u.ctrlKey||u.shiftKey||u.altKey||u.button!==0||(u.preventDefault(),e(t))})}),o.addEventListener("keydown",u=>{u.key!=="Enter"&&u.key!==" "||(u.preventDefault(),e(t))}),o.addEventListener("focus",()=>n(!0)),o.addEventListener("blur",u=>{u.relatedTarget?.closest("[data-aia-dropdown]")||n(!1)}),o}var Ni=80,Fi=150,Hi=280,Bi=16,Ct="--aia-option-enter-delay";function It(t,e,n,i="below"){let o=Math.max(1,Math.floor(e)),r=Math.floor(Math.max(0,t)/o);if(i!=="above")return r*80;let s=Math.max(1,Math.ceil(Math.max(0,n)/o));return Math.max(0,s-1-r)*80}function Ot(t,e){let n=Math.max(1,Math.floor(e));return(Math.max(1,Math.ceil(Math.max(0,t)/n))-1)*80+280}function H(t){if(!t)return null;let e=t.trim();if(e==="")return null;let n;try{n=new URL(e,typeof document>"u"?void 0:document.baseURI)}catch{return null}return n.protocol!=="http:"&&n.protocol!=="https:"?null:n.href}function fe(t){return t===void 0||!Number.isInteger(t)||t<0?null:t.toLocaleString()}var un={one:"item",other:"items"};function Wi(t,e=un){let n=fe(t);if(n===null)return null;let i=typeof e=="string"?e:t===1?e.one:e.other;return i===""?n:`${n} ${i}`}function qi(t){return H(t.image_url)!==null}var $i="http://www.w3.org/2000/svg",br=new Set(["svg","g","path","circle","ellipse","line","polyline","polygon","rect"]);function yr(t,e){let n=t.toLowerCase();return n.startsWith("on")||n.includes("href")||n==="style"||n==="xml:base"||n==="id"||n==="name"||/^\s*javascript:/i.test(e)||/url\s*\(\s*['"]?\s*[^#'"\s)]/i.test(e)}var Sr=["fill","stroke","stroke-width","stroke-linecap","stroke-linejoin","fill-rule","clip-rule","opacity","fill-opacity","stroke-opacity"],xr=/^[a-zA-Z0-9#.,%\s()-]+$/;function vr(t){let e=[];for(let n of Sr){let i=t.getAttribute(n);i===null||!xr.test(i)||/url\s*\(/i.test(i)||e.push(`${n}: ${i.trim()}`)}e.length>0&&t.setAttribute("style",e.join("; "))}function Gi(t){for(let e of Array.from(t.attributes))yr(e.name,e.value)&&t.removeAttribute(e.name);vr(t);for(let e of Array.from(t.childNodes))if(e.nodeType===Node.ELEMENT_NODE){let n=e;!br.has(n.localName)||n.namespaceURI!==$i?n.remove():Gi(n)}else e.remove()}function ge(t){if(typeof DOMParser>"u"||typeof XMLSerializer>"u")return null;let e=new DOMParser().parseFromString(t,"image/svg+xml"),n=e.documentElement;return!n||n.localName!=="svg"||n.namespaceURI!==$i||e.getElementsByTagName("parsererror").length>0?null:(Gi(n),n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false"),new XMLSerializer().serializeToString(n))}function At(t){return t.text}var Ui=new WeakMap;function Er(t,e,n){let i=e.length,o=ut(),r=Ui.get(t),s=n&&r&&pt(r.options,e)?r.plan:null,a=!s&&!n&<(i,o)?ct(t):null,l=s??dt(i,o,a?.rowWidths??null,a?.gridWidth??null);return n||Ui.set(t,{options:e,plan:l}),t.style.gridTemplateColumns=l.template,t.style.setProperty("--aia-grid-max-height",l.maxHeight),t.querySelectorAll("[data-aia-option]").forEach((d,c)=>{d.classList.toggle("magicx-aia-option--scroll-hint",!n&&l.scrollHintIndices.includes(c))}),l.cols}function Vi(t,e){if(e.loading||!e.interactive)return null;let n=e.options[K(t)];return n?.is_tappable?n:null}var wr={itemSelector:"[data-aia-option]",onClick:(t,e)=>{let n=Vi(t,e);n&&(t.classList.add("magicx-aia-option--pressed"),e.onSelect(n),setTimeout(()=>t.classList.remove("magicx-aia-option--pressed"),170))},onEnter:(t,e)=>{Vi(t,e)&&e.onHighlight(K(t))},onLeave:(t,e)=>e.onHighlight(-1,K(t))};function Ki(t,e,n,i,o,r,s,a="",l="below",d=!0,c=!0,u=!0,m=!0){let f=t.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"),t.appendChild(f)),V(f,wr,{options:e,onSelect:i,onHighlight:o,loading:s,interactive:m});let h=f.dataset.aiaGroup!==a;f.dataset.aiaGroup=a,Pr(f,e,n,r,s,{showIcons:d,showImages:c,showCounts:u});let S=Er(f,e,s);Tr(f,e.length,S,s,l),h&&(f.scrollTop=0)}function Pr(t,e,n,i,o,r){let s=o?"1":"0",a=t.dataset.aiaGroup??"",{showIcons:l,showImages:d,showCounts:c}=r,u=l?h=>h.icon??h.icon_svg??"":()=>"",m=d?h=>H(h.image_url)??"":()=>"",f=c?h=>fe(h.item_count)??"":()=>"";Q(t,e,{keyOf:h=>`${h.text}\0${u(h)}\0${m(h)}\0${f(h)}\0${s}\0${a}`,create:(h,S)=>{let x=Cr(h,o,r);return o||(x.dataset.aiaEntering=""),x},update:(h,S,x)=>{let g=x===n&&!o;h.id=`${i}-option-${x}`,h.dataset.aiaIndex=String(x),h.setAttribute("aria-selected",String(g)),h.classList.toggle("magicx-aia-option--highlighted",g)}})}function Tr(t,e,n,i,o){for(let r of t.querySelectorAll("[data-aia-entering]")){if(!i){let s=Number.parseInt(r.dataset.aiaIndex??"-1",10);s>=0&&r.style.setProperty(Ct,`${It(s,n,e,o)}ms`)}delete r.dataset.aiaEntering}}function Cr(t,e,{showIcons:n,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||!t.is_tappable?-1:0;let s=["magicx-aia-option"];t.is_tappable?s.push("magicx-aia-option--tappable"):s.push("magicx-aia-option--non-tappable"),r.className=s.join(" ");let a=document.createElement("span");a.className="magicx-aia-option-content";let l=i?H(t.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 d=!l&&n&&t.icon_svg?ge(t.icon_svg):null;if(d){let m=document.createElement("span");m.className="magicx-aia-option-icon",m.setAttribute("aria-hidden","true"),m.innerHTML=d,a.appendChild(m),t.icon&&(r.dataset.aiaIcon=t.icon)}let c=document.createElement("span");if(c.className="magicx-aia-option-text",c.textContent=At(t),a.appendChild(c),t.tag){let m=document.createElement("span");m.className="magicx-aia-option-tag",m.textContent=t.tag,a.appendChild(m)}let u=o?fe(t.item_count):null;if(u!==null){let m=document.createElement("span");m.className="magicx-aia-option-count",m.textContent=u,a.appendChild(m),r.dataset.aiaItemCount=String(t.item_count)}return r.appendChild(a),r}var mn="magicx-aia-scroll-arrow",fn="data-aia-scroll-arrow",ne="data-aia-visible",gn=1e3,hn=160,bn="--aia-scroll-arrow-bottom",yn="Scroll down for more options",Ir="[data-aia-products-label]",Or=4,Ar=8,Lr=240;function Rr(t,e,n,i){let o=t.scrollTop,r=n?.requestAnimationFrame,s=t.ownerDocument?.visibilityState==="hidden";if(!r||s||pn(t)){t.scrollTop=o+e,i();return}let a=n.performance?.now?.()??Date.now(),l=()=>n.performance?.now?.()??Date.now(),d=()=>{let c=Math.min(1,(l()-a)/Lr),u=1-(1-c)*(1-c);t.scrollTop=o+e*u,c<1?r.call(n,d):i()};r.call(n,d)}function Dr(t=document){let e="http://www.w3.org/2000/svg",n=t.createElementNS(e,"svg");n.setAttribute("viewBox","0 0 16 16"),n.setAttribute("width","18"),n.setAttribute("height","18"),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","1.75"),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false");let i=t.createElementNS(e,"path");return i.setAttribute("d","M4 6.5 8 10.5l4-4"),n.appendChild(i),n}function Yi(t=document){let e=t.createElement("button");return e.type="button",e.tabIndex=-1,e.className=mn,e.setAttribute(fn,""),e.setAttribute("aria-label",yn),e.setAttribute("aria-hidden","true"),e.disabled=!0,e.appendChild(Dr(t)),e}function Mr(t){let e=t.style.gridTemplateColumns.trim();return e?Math.max(1,e.split(/\s+/).length):1}function pn(t){return t.closest('[data-animations="off"]')?!0:!!t.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function Lt({dropdown:t,grid:e,button:n}){let i=e.ownerDocument?.defaultView??(typeof window<"u"?window:null),o=!1;n.disabled=!0;let r=null,s=null,a=null,l=null,d=p=>{if(p){if(n.hasAttribute(ne))return;if(n.setAttribute(ne,""),n.setAttribute("aria-hidden","false"),l!==null&&clearTimeout(l),pn(e)){n.disabled=!1;return}l=setTimeout(()=>{l=null,!o&&n.hasAttribute(ne)&&(n.disabled=!1)},gn)}else n.removeAttribute(ne),n.setAttribute("aria-hidden","true"),l!==null&&clearTimeout(l),l=null,n.disabled=!0},c=p=>{let b=0,y=p;for(;y&&y!==t;)b+=y.offsetTop,y=y.offsetParent instanceof HTMLElement?y.offsetParent:null;return b},u=()=>{let p=t.querySelector(Ir),b;if(p){let y=c(p)+p.offsetHeight/2;b=t.clientHeight-y-n.offsetHeight/2}else{let y=c(e),E=i&&Number.parseFloat(i.getComputedStyle(e).paddingBottom)||0;b=t.clientHeight-(y+e.offsetHeight)+(E>0?0:Ar)}n.style.setProperty(bn,`${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;d(!p&&b>Or)},f=()=>{if(o)return;u();let p=e.getAttribute("data-aia-group")??"";if(p!==r){r=p,d(!1),s!==null&&clearTimeout(s);let b=e.querySelectorAll("[data-aia-option]").length,y=pn(e)?0:Ot(b,Mr(e));s=setTimeout(()=>{s=null,m()},y);return}m()},h=()=>{o||s!==null||(d(!1),a!==null&&clearTimeout(a),a=setTimeout(()=>{a=null,m()},hn))};e.addEventListener("scroll",h,{passive:!0});let S=p=>p.preventDefault(),x=()=>{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);Rr(e,b,i,h)};n.addEventListener("mousedown",S),n.addEventListener("click",x);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,n.disabled=!0,e.removeEventListener("scroll",h),n.removeEventListener("mousedown",S),n.removeEventListener("click",x),g?.disconnect(),n.removeAttribute(ne),n.setAttribute("aria-hidden","true"))}}}var kr=[159,119,164];function Dt(t){let e=document.createElement("div");return e.id=t,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",n=>n.preventDefault()),xt(e),e}var Rt=new WeakMap;function _r(t,e){let n=Rt.get(t);if(n||(n={button:Yi(t.ownerDocument),grid:null,controller:null},t.appendChild(n.button),Rt.set(t,n)),n.grid!==e&&(n.controller?.destroy(),n.controller=null,n.grid=e,e)){n.controller=Lt({dropdown:t,grid:e,button:n.button});return}n.controller?.update()}function Sn(t){let e=Rt.get(t);e&&(e.controller?.destroy(),Rt.delete(t))}function Mt(t,e){let{filteredOptions:n,activeIndex:i,isOpen:o,isLoading:r,pills:s,showPills:a,isActivePillSelected:l,onSelect:d,onHighlight:c,onPillClick:u,onSkip:m}=e,f=s.length>0,h=a&&f,S=n.length>0,x=e.products.length>0,g=o&&(S||h||r||x);if(g?t.classList.add("magicx-aia-dropdown--visible"):t.classList.remove("magicx-aia-dropdown--visible"),r?t.setAttribute("data-aia-loading",""):t.removeAttribute("data-aia-loading"),!g){cn(t,!1);return}x?t.setAttribute("data-aia-has-products",""):t.removeAttribute("data-aia-has-products"),t.toggleAttribute("data-aia-skeleton-exiting",!!e.skeletonExiting);let p=t.querySelector(".aia-stack");p||(p=document.createElement("div"),p.className="aia-stack",p.style.setProperty("--aia-stack-space","8px"),t.appendChild(p));let b=e.showSkipButton&&f&&!e.isInputEmpty,y=h||r&&a||b,E=p.querySelector(".magicx-aia-pill-bar");if(y){E||(E=document.createElement("div"),E.className="magicx-aia-pill-bar aia-cluster",E.setAttribute("data-nowrap",""),E.setAttribute("data-aia-pillbar",""),p.insertBefore(E,p.firstChild));let _=E.querySelector(".magicx-aia-pill-scroll");_||(_=document.createElement("span"),_.className="magicx-aia-pill-scroll",_.setAttribute("data-aia-pill-scroll",""),E.insertBefore(_,E.firstChild)),wt(_,a?s:[],0,u,!0,r&&a,l),Hr(E,b,r||e.skipDisabled,s[0],m)}else E&&E.remove();let w=e.suggestions[0],P=w?`${w.type} ${w.text}`:"",R=v(e.formatType),T=R&&!r;Ki(p,R?[]:n,i,d,c,e.listboxId,r,P,e.optionsPosition??"below",e.showOptionIcons??!0,e.showOptionImages??!0,e.showOptionCounts??!0,!e.skipDisabled),_r(t,p.querySelector(".aia-grid")),Oi(p,T?n:[],i,e.listboxId,T?e.dateView:null,{selectedIso:e.selectedDateIso,selectedRange:e.selectedDateRange,rangeStart:e.dateRangeStart},{onSelect:d,onHighlight:c,onPreviousMonth:e.onPreviousMonth,onNextMonth:e.onNextMonth},!e.skipDisabled);let I=p.querySelector(".magicx-aia-skeleton-bars");if(r&&(!S||R)){if(!I){I=document.createElement("div"),I.className="magicx-aia-skeleton-bars",I.setAttribute("data-aia-skeleton-bars","");for(let _ of kr){let ie=document.createElement("span");ie.className="magicx-aia-skeleton-bar",ie.style.width=`${_}px`,I.appendChild(ie)}p.appendChild(I)}}else I&&I.remove();_i(p,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange,e.productsLayout??"row",e.productImageFallback??"image"),cn(t,!0);let X=p.querySelector(".magicx-aia-footer")??Wr(),D=i>=0&&!!n[i]?.is_tappable;Br(X,St(D,e.isInputEmpty)),X.isConnected||p.appendChild(X),Nr(p,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-datepicker",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"])}function Nr(t,e){let n=e.map(i=>t.querySelector(`:scope > ${i}`)).filter(i=>i!==null);for(let i=0;i<n.length;i++)t.children[i]!==n[i]&&t.insertBefore(n[i],t.children[i]??null)}var Fr={itemSelector:".magicx-aia-skip",onClick:(t,e)=>{e.loading||e.onSkip()}};function Hr(t,e,n,i,o){V(t,Fr,{onSkip:o,loading:n});let r=t.querySelector(".magicx-aia-skip");if(!e){r?.remove();return}r||(r=document.createElement("button"),r.type="button",r.tabIndex=-1,r.className="magicx-aia-skip",r.setAttribute("data-aia-skip",""),r.textContent="skip",r.disabled=!0,t.appendChild(r),Y(r)),r.setAttribute("aria-label",i?`Skip ${i.text}`:"Skip"),r.disabled=n}function Br(t,{key:e,hint:n}){let i=t.querySelector(".magicx-aia-footer-key"),o=t.querySelector(".magicx-aia-footer-hint");!i||!o||(i.textContent!==e&&(i.textContent=e),o.textContent!==n&&(o.textContent=n))}function Wr(){let t=document.createElement("footer");t.className="magicx-aia-footer",t.setAttribute("data-aia-footer","");let e=document.createElement("div");e.className="aia-cluster magicx-aia-footer-row",e.setAttribute("data-align","center"),e.setAttribute("data-justify","between"),e.setAttribute("data-nowrap","");let n=document.createElement("div");n.className="aia-cluster magicx-aia-footer-hint-group",n.setAttribute("data-align","center"),n.style.setProperty("--aia-cluster-gap","5px");let 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",n.append(i,o);let r=document.createElement("a");r.className="aia-cluster magicx-aia-footer-brand-link",r.setAttribute("data-align","center"),r.href=yt(),r.target="_blank",r.rel="noopener noreferrer",r.style.setProperty("--aia-cluster-gap","2px");let s=document.createElement("span");s.className="magicx-aia-footer-brand",s.textContent="AI";let a=document.createElement("span");return a.className="magicx-aia-footer-badge",a.textContent="Autocomplete",r.append(s,a),e.append(n,r),t.append(e),t}function Qi(t,e){let n=Dt(e.listboxId);return t.appendChild(n),{dropdown:n}}function xn(t,e,n){let i=me(e);Mt(t.dropdown,{suggestions:e.editingIdentified?[{type:e.editingIdentified.type,text:B(e.editingIdentified.type),required:!0,options:e.filteredOptions}]:e.dropdownSuggestion??e.actionableSuggestions[0]?[{...e.dropdownSuggestion??e.actionableSuggestions[0],options:e.dropdownOptions}]:[],filteredOptions:e.dropdownOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.dropdownLoading,skeletonExiting:e.skeletonExiting,listboxId:n.listboxId,pills:e.actionableSuggestions,showPills:!0,showSkipButton:n.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:n.showOptionIcons??!0,showOptionImages:n.showOptionImages??!0,showOptionCounts:n.showOptionCounts??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,productsLayout:n.productsLayout??"row",productImageFallback:n.productImageFallback??"image",formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:i.selectedIso,selectedDateRange:i.selectedRange,dateRangeStart:i.rangeStart,optionsPosition:n.optionsPosition??"below",onSelect:n.selectOption,onHighlight:(o,r)=>{r!==void 0&&n.store.get().activeDropdownIndex!==r||n.store.set({activeDropdownIndex:o})},onPillClick:n.setActivePill,onSkip:n.skipActivePill,onPreviousMonth:n.showPreviousMonth,onNextMonth:n.showNextMonth,onProductSelect:n.selectProduct,onProductFocusChange:o=>n.store.set({isFocused:o})})}var qr=6,$r=.3;function Xi(t){return t<=0?"0px":`${(-Math.min($r,2*qr/t)).toFixed(3)}px`}function kt(t){let{input:e,segments:n,newParamId:i,editingParamId:o,placeholderText:r,isFocused:s}=t,a=t.showChipIcons??!0,l=t.showChipImages??!0,d=n.length===0;e.dataset.aiaEmpty=d?"true":"false",Si(e,d?r:"");let c=n.map(p=>p.type==="completed"?`${p.type}:${p.value}${a?p.param.icon??p.param.icon_svg??"":""}${l?H(p.param.image_url)??"":""}`:`${p.type}:${p.value}`).join("\0"),u=e.dataset.segKey??"",m=e.dataset.newParamId??"",f=e.dataset.editingParamId??"";if(c===u&&(i??"")===m&&(o??"")===f)return;if(c===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?k(e):null;e.dataset.segKey=c,e.dataset.newParamId=i??"",e.dataset.editingParamId=o??"";let S=L(e),x=S.createDocumentFragment(),g=0;for(let p of n)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,E=p.param.id===o,w=["magicx-aia-segment","magicx-aia-segment--completed"];y&&w.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),E&&w.push("magicx-aia-segment--editing"),b.className=w.join(" "),b.style.letterSpacing=Xi(p.value.length);let P=l?H(p.param.image_url):null;if(P){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("${P}")`),b.appendChild(T),b.dataset.aiaImage=""}let R=!P&&a&&p.param.icon_svg?ge(p.param.icon_svg):null;if(R){let T=S.createElement("span");T.className="magicx-aia-segment-icon",T.setAttribute("contenteditable","false"),T.setAttribute("aria-hidden","true"),T.innerHTML=R,b.appendChild(T),p.param.icon&&(b.dataset.aiaIcon=p.param.icon)}b.appendChild(S.createTextNode(p.value)),x.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=Xi(p.value.length),b.textContent=p.value,x.appendChild(b)}else x.appendChild(S.createTextNode(p.value));e.replaceChildren(x),e.dataset.aiaTextLength=String(g),h!=null?O(e,Math.max(0,Math.min(h,g))):s&&ri(e)&&O(e,g)}var Gr='<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 ji(){let t=document.createElement("button");return t.type="button",t.className="magicx-aia-submit",t.setAttribute("aria-label","Submit"),t.setAttribute("data-aia-submit",""),t.innerHTML=Gr,t}function Ur(){let t=document.createElement("div");return t.setAttribute("contenteditable","plaintext-only"),t.contentEditable==="plaintext-only"}function zi(t,e){let n=e.firstElementChild;if(!n){e.removeAttribute("data-aia-pill-wrapped");return}let i=n.getBoundingClientRect(),o=t.getBoundingClientRect();i.top>=o.bottom-2?e.setAttribute("data-aia-pill-wrapped",""):e.removeAttribute("data-aia-pill-wrapped")}function Ji(t,e){let{listboxId:n}=e,i=Dt(n);t.appendChild(i);let o=document.createElement("div");o.className="magicx-aia-input-wrapper",o.setAttribute("data-aia-input-wrapper",""),t.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",Ur()?"plaintext-only":"true"),s.setAttribute("role","combobox"),s.setAttribute("aria-autocomplete","list"),s.setAttribute("aria-haspopup","listbox"),s.setAttribute("aria-controls",n),s.setAttribute("aria-expanded","false"),s.setAttribute("spellcheck","true"),s.setAttribute("enterkeyhint","send"),r.appendChild(s);let a=document.createElement("span");a.className="magicx-aia-pill-list-container",a.setAttribute("data-aia-pill-list-container",""),r.appendChild(a);let l=null,d=null;e.submitButton===void 0?(l=ji(),o.appendChild(l),d=l):e.submitButton!==null&&(d=e.submitButton,d.hasAttribute("data-aia-submit")||d.setAttribute("data-aia-submit",""),d.setAttribute("data-aia-submit-slot",""),o.appendChild(d));let c=new AbortController,{signal:u}=c,m=!1,f=0,h=()=>{let g=we(s),b=g.length>0&&g[0]!==g[0].toUpperCase()?g[0].toUpperCase()+g.slice(1):g;e.handleChange(b)},S=()=>{let g=G(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&&oi(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(k(s)))},{signal:u}),L(s).addEventListener("selectionchange",()=>{let g=G(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(k(s))},{signal:u}),s.addEventListener("click",g=>{let p=Je(s,g.target);p&&(e.startEditingParam(p),Ze(s,p))},{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=L(s),y=Ve(s);if(!y||!s.contains(y.startContainer))return;y.deleteContents();let E=b.createTextNode(p);y.insertNode(E),y.setStartAfter(E),Ee(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}),d&&d.addEventListener("click",g=>{let p=e.store.get();if(!(!!p.text||p.completedParams.length>0)||!e.onSubmit)return;g.stopPropagation(),e.onSubmit(U(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=G(s);(!g||!s.contains(g.node))&&Ee(s,s,0)}if(typeof ResizeObserver<"u"){let g=new ResizeObserver(()=>zi(s,a));g.observe(s),c.signal.addEventListener("abort",()=>g.disconnect(),{once:!0})}return{input:s,inlinePillContainer:a,dropdown:i,submitButton:l,abort:c}}function vn(t,e,n){let{input:i,inlinePillContainer:o,dropdown:r,submitButton:s}=t,{pillPlacement:a,setActivePill:l,selectOption:d,store:c}=n;i.setAttribute("aria-expanded",String(e.isDropdownOpen));let u=e.activeDropdownIndex>=0?`${n.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(kt({input:i,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused,showChipIcons:n.showChipIcons??!0,showChipImages:n.showChipImages??!0}),a==="inline"){let g=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;g||e.actionableSuggestions.length>0?wt(o,e.actionableSuggestions,0,l,!1,g,e.isActivePillSelected):an(o)}else an(o);zi(i,o),f?(i.focus(),O(i,e.caretOffset??e.text.length)):e.isFocused&&we(i)!==e.text&&O(i,e.text.length);let h=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:e.editingIdentified?{type:e.editingIdentified.type,text:B(e.editingIdentified.type),required:!0,options:[]}:null,S=e.dropdownSuggestion??h??e.actionableSuggestions[0],x=me(e);Mt(r,{suggestions:S?[{...S,options:e.dropdownOptions}]:[],filteredOptions:e.dropdownOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.dropdownLoading,skeletonExiting:e.skeletonExiting,listboxId:n.listboxId,pills:h?[h]:e.actionableSuggestions,showPills:a==="dropdown",showSkipButton:n.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:n.showOptionIcons??!0,showOptionImages:n.showOptionImages??!0,showOptionCounts:n.showOptionCounts??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,productsLayout:n.productsLayout??"row",productImageFallback:n.productImageFallback??"image",formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:x.selectedIso,selectedDateRange:x.selectedRange,dateRangeStart:x.rangeStart,optionsPosition:n.optionsPosition??"below",onSelect:d,onHighlight:(g,p)=>{p!==void 0&&c.get().activeDropdownIndex!==p||c.set({activeDropdownIndex:g})},onPillClick:l,onSkip:n.skipActivePill,onPreviousMonth:n.showPreviousMonth,onNextMonth:n.showNextMonth,onProductSelect:n.selectProduct,onProductFocusChange:g=>c.set({isFocused:g})})}function _t(t){let e=t,n=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 d=i.shift();d;d=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[c,u]=d;for(let m of n)m(c,u)}}catch(l){throw i.length=0,l}finally{o=!1}}},subscribe:r=>(n.add(r),()=>{n.delete(r)})}}function Zi(t,e){let n,i,o=r=>(r!==n&&(n=r,i=e(r)),i);return{get:()=>{let r=t.get();return{...r,...o(r)}},set:r=>{typeof r=="function"?t.set(s=>{let a={...s,...o(s)};return r(a)}):t.set(r)},peek:r=>{let s={...t.get(),...r};return{...s,...e(s)}},subscribe:r=>t.subscribe((s,a)=>{let l={...a,...o(a)},d={...s,...o(s)};r(d,l)})}}var En=new WeakSet,eo=new WeakMap;function no(t){return t.nodeType===Node.DOCUMENT_NODE}function Vr(t){return no(t)?t:t.ownerDocument}function Kr(t){let e=eo.get(t);if(e)return e;let n=t.defaultView?.CSSStyleSheet;if(typeof n!="function")return null;try{let i=new n;return typeof i.replaceSync!="function"?null:(i.replaceSync(oo),eo.set(t,i),i)}catch{return null}}function to(t,e){if(e.querySelector("style[data-magicx-aia]"))return;let n=t.createElement("style");n.setAttribute("data-magicx-aia",""),n.textContent=oo,e.appendChild(n)}function io(t){if(typeof document>"u")return;let e=t??document;if(En.has(e))return;let n=Vr(e);if(no(e)){let r=e.head??e.documentElement;if(!r)return;to(n,r),En.add(e);return}let i=Kr(n),o=e.adoptedStyleSheets;i&&Array.isArray(o)?o.includes(i)||(e.adoptedStyleSheets=[...o,i]):to(n,e),En.add(e)}var oo=`.aia-stack {
|
|
2
2
|
display: flex;
|
|
3
3
|
flex-direction: column;
|
|
4
4
|
gap: var(--aia-stack-space, 0.5rem);
|
|
@@ -666,6 +666,8 @@
|
|
|
666
666
|
text-decoration: none;
|
|
667
667
|
cursor: pointer;
|
|
668
668
|
transition: background-color 150ms ease;
|
|
669
|
+
/* The sold-out badge is positioned against the card. */
|
|
670
|
+
position: relative;
|
|
669
671
|
}
|
|
670
672
|
|
|
671
673
|
.magicx-aia-product:hover {
|
|
@@ -781,6 +783,39 @@
|
|
|
781
783
|
);
|
|
782
784
|
}
|
|
783
785
|
|
|
786
|
+
/* Sold-out badge. It sits last in the text column, so the card's accessible
|
|
787
|
+
name ends with it, and is lifted over the image's top-left corner: card
|
|
788
|
+
padding (6px) plus the same again. A light chip with dark, tracked capitals
|
|
789
|
+
reads on any photo, light or dark, and on either panel surface. */
|
|
790
|
+
.magicx-aia-product-badge {
|
|
791
|
+
position: absolute;
|
|
792
|
+
top: var(--aia-product-badge-inset, 12px);
|
|
793
|
+
left: var(--aia-product-badge-inset, 12px);
|
|
794
|
+
padding: 3px 6px;
|
|
795
|
+
border-radius: 4px;
|
|
796
|
+
background: var(--aia-product-badge-bg, rgba(255, 255, 255, 0.94));
|
|
797
|
+
color: var(--aia-product-badge-color, #1f2328);
|
|
798
|
+
/* A hairline ring keeps the chip's edge on a pale image or a light panel. */
|
|
799
|
+
box-shadow:
|
|
800
|
+
0 0 0 1px rgba(0, 0, 0, 0.08),
|
|
801
|
+
0 1px 2px rgba(0, 0, 0, 0.18);
|
|
802
|
+
font-family: inherit;
|
|
803
|
+
font-size: var(--aia-product-badge-font-size, 9px);
|
|
804
|
+
font-weight: 600;
|
|
805
|
+
line-height: 1;
|
|
806
|
+
letter-spacing: 0.08em;
|
|
807
|
+
text-transform: uppercase;
|
|
808
|
+
white-space: nowrap;
|
|
809
|
+
pointer-events: none;
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
/* A sold-out product's image steps back, so the badge is not the only cue.
|
|
813
|
+
Desaturated rather than faded: opacity lets the panel show through, which
|
|
814
|
+
muddies a photo on a dark surface. */
|
|
815
|
+
.magicx-aia-product[data-aia-product-sold-out] .magicx-aia-product-image {
|
|
816
|
+
filter: grayscale(0.55);
|
|
817
|
+
}
|
|
818
|
+
|
|
784
819
|
/* --- List layout (\`productsLayout: "list"\`) ---
|
|
785
820
|
The same cards stacked as full-width rows \u2014 thumbnail on the left, text on
|
|
786
821
|
the right \u2014 for results that read as a list (courses, listings, documents)
|
|
@@ -818,6 +853,27 @@
|
|
|
818
853
|
flex: 1 1 auto;
|
|
819
854
|
}
|
|
820
855
|
|
|
856
|
+
/* In a list the badge is a banner across the bottom of the thumbnail. The
|
|
857
|
+
thumbnail is centred in the card and the card's top and bottom padding
|
|
858
|
+
match, so its bottom edge is half a thumbnail below the card's centre; its
|
|
859
|
+
left edge is the card's 8px inline padding. */
|
|
860
|
+
.magicx-aia-products[data-aia-products-layout="list"] .magicx-aia-product-badge {
|
|
861
|
+
top: calc(50% + var(--aia-product-list-media-size, 44px) / 2);
|
|
862
|
+
left: 8px;
|
|
863
|
+
width: var(--aia-product-list-media-size, 44px);
|
|
864
|
+
transform: translateY(-100%);
|
|
865
|
+
padding: 2px 0;
|
|
866
|
+
border-radius: 0 0 8px 8px;
|
|
867
|
+
/* A dark scrim rather than the light chip: a light banner at a tile's edge
|
|
868
|
+
merges with a light panel and reads as a cropped photo. */
|
|
869
|
+
background: var(--aia-product-badge-list-bg, rgba(17, 17, 17, 0.72));
|
|
870
|
+
color: var(--aia-product-badge-list-color, #fff);
|
|
871
|
+
box-shadow: none;
|
|
872
|
+
font-size: var(--aia-product-badge-list-font-size, 7px);
|
|
873
|
+
letter-spacing: 0.02em;
|
|
874
|
+
text-align: center;
|
|
875
|
+
}
|
|
876
|
+
|
|
821
877
|
/* --- "More below" scroll arrow (see render/scrollArrow.ts) ---
|
|
822
878
|
A bare down chevron at the bottom-centre of the option list, shown while
|
|
823
879
|
there is more to scroll to \u2014 no disc, border or shadow around it. It rests
|
|
@@ -2183,5 +2239,5 @@
|
|
|
2183
2239
|
background: var(--aia-surface, #ffffff);
|
|
2184
2240
|
}
|
|
2185
2241
|
}
|
|
2186
|
-
`;var Nt=class{constructor(){this.reported=new Set}run(e,n){try{return n()}catch(i){this.report(e,i,e);return}}runListener(e,n,i=e){try{return n(),!0}catch(o){return this.report(e,o,i),!1}}report(e,n,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.`,n))}};var Ft=class{constructor(e){this.boundary=e;this.listeners={};this.keys=new WeakMap;this.registrationCount=0}on(e,n){let i=`${String(e)}#${++this.registrationCount}`,o=(...s)=>n(...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,...n){let i=this.listeners[e];if(!i)return!0;let o=!0;for(let r of i)this.boundary.runListener(String(e),()=>r(...n),this.keys.get(r)??String(e))||(o=!1);return o}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var Ht=class{constructor(){this.timers=new Map}schedule(e,n,i){this.clear(e);let o=setTimeout(()=>{this.timers.delete(e),n()},i);this.timers.set(e,o)}clear(e){let n=this.timers.get(e);n!==void 0&&(clearTimeout(n),this.timers.delete(e))}clearAll(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};var he=class{constructor(e,n="auto",i){this.container=e;this.mode=n;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)}};var Ur=50,Kr=new Set(["search_started","submit","product_click","impression"]),Yr="newParam",ro="suggestionRemoval",Qr="selectionAnimation",wn="skeletonExit",Xr=650,jr=0;function zr(){return`:ac-${++jr}:`}var so=170,Jr=100;function ao(){return{text:"",completedParams:[],identifiedParams:[],skippedParams:[],pendingSpan:null,suggestions:[],products:[],customFields:null,optionSearch:null,activeDropdownIndex:-1,newParamId:null,isLoading:!1,isReady:!1,error:null,filterBase:0,filterInProgress:!1,pillTapped:!1,skipNextFetch:!1,lastRawQuery:"",isFocused:!1,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:null,inSelectionAnimation:!1,skeletonOptions:null,skeletonSuggestion:null,skeletonRequested:!1,dateViewMonth:null,pendingRangeStart:null,editingIdentified:null}}var Bt=class{constructor(e,n={}){this.inputStore=_t(ao());this._listboxId=zr();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new Ht;this.boundary=new Nt;this.subscriberCount=0;this.emitter=new Ft(this.boundary);this.sessionId=crypto.randomUUID();this.lastRequestId=null;this.searchStartedSessionId=null;this.funnelTelemetry=null;this.pendingSearchStarted=!1;this.lastImpressionKey="";this.emitSubmit=e=>(this.recordSubmit(e),this.emitter.emit("submit",e));this.emitError=e=>this.emitter.emit("error",e);this.container=e,this.opts=n,this.renderMode=n.renderMode??"full",this.store=Zi(this.inputStore,i=>di(i,this.opts)),n.onSubmit&&this.emitter.on("submit",n.onSubmit),n.onResult&&this.emitter.on("result",n.onResult),n.onError&&this.emitter.on("error",n.onError),n.onChange&&this.emitter.on("change",n.onChange),n.onParamsChange&&this.emitter.on("paramsChange",n.onParamsChange),n.onStateChange&&this.emitter.on("stateChange",n.onStateChange),n.onFocus&&this.emitter.on("focus",n.onFocus),n.onBlur&&this.emitter.on("blur",n.onBlur),n.onProductSelect&&this.emitter.on("productSelect",n.onProductSelect),n.value!==void 0&&this.store.set({text:n.value}),n.completedParams!==void 0&&this.store.set({completedParams:n.completedParams}),this.pillsController=new ot(this.store,{onPillSelected:({rawQuery:i,selectedPill:o,otherPills:r})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:o,other_pills:r})}}),this.reEdit=new ht({store:this.store,scheduleSetCursor:i=>this.scheduleSetCursor(i),fireTelemetry:(i,o)=>this.fireTelemetry(i,o),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer(),fetchNow:()=>this.fetchNow()}),this.productsController=new st(this.store,()=>this.opts.products,()=>this.opts.showProducts!==!1),this.optionSource=new it(this.store,()=>this.opts.optionOverrides,{onAnswer:i=>{i==="edit"?this.reEdit.promoteIfExact():this.maybePromoteExactMatch(this.store.get().text)},onMiss:(i,o)=>{i==="pill"&&o.length>0&&this.fetchController.attemptNow()}}),this.fetchController=new Ve(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.emitter.hasListeners("error")?this.emitError:void 0,()=>this.sessionId,()=>this.resolveSource(),()=>this.opts.additionalContext,{onRequest:({query:i,signal:o,isCurrent:r})=>{this.productsController.run(i,o,r).catch(()=>{})},onAutoMatch:({active:i,matched:o,rawQuery:r})=>{let s=i.options??[];this.fireTelemetry("option",{raw_query:r,selected_option:o.text,other_options:s.filter(a=>a.text!==o.text).map(a=>a.text),key:i.type,position:ue(s,o.text)})},onResponse:({requestId:i,funnelTelemetry:o})=>{this.lastRequestId=i,this.funnelTelemetry=o,this.pendingSearchStarted&&(this.pendingSearchStarted=!1,this.fireTelemetry("search_started",{})),this.fireImpression(),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 nt(this.store,{columns:n.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.emitter.hasListeners("submit")?this.emitSubmit:void 0,getOptionsPosition:()=>this.opts.optionsPosition??"below",afterSubmit:this.renderMode==="full"?()=>this.resetAfterSubmit():void 0,selectOption: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.subscribeSkeletonMirror(),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}=$e(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===Te(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=Yn(o.text,i.text,s);if(l===null){this.store.set({pendingSpan:null});return}s=l}i.text.slice(s).trim().length===0||Un(i.segments,s)?this.store.set({pendingSpan:null}):s!==r.anchor&&this.store.set({pendingSpan:{anchor:s,snapshot:r.snapshot}})})),this.renderMode!=="headless"&&(io(this.opts.styleRoot??ee(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({...ao(),isFocused:e,skipNextFetch:!0}),this.sessionId=crypto.randomUUID(),this.lastRequestId=null,this.lastImpressionKey="",this.pendingSearchStarted=!1,this.fetchController.doFetch("",[])}resetAfterSubmit(){this.opts.resetOnSubmit!==!1&&this.reset()}destroy(){this.fetchController.dispose(),this.optionSource.dispose(),this.modeController?.destroy(),this.timers.clearAll(),this.emitter.clear();for(let e of this.unsubscribers)e();this.unsubscribers=[],this.domRefs?.abort.abort(),this.domRefs&&(xi(this.domRefs.input),Sn(this.domRefs.dropdown)),this.dropdownRefs&&Sn(this.dropdownRefs.dropdown),this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}prefillText(e){this.applyTextChange(e,!1)}noteSearchStarted(){this.searchStartedSessionId!==this.sessionId&&(this.searchStartedSessionId=this.sessionId,this.funnelTelemetry===null?this.pendingSearchStarted=!0:this.fireTelemetry("search_started",{}))}setValue(e){let n=this.store.get();if(n.editingIdentified&&e!==n.text){this.store.set({text:e,editingIdentified:null,activeDropdownIndex:-1});return}this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e);let n=this.store.get().text.length;this.store.set({caretOffset:n,isFocused:!0}),this.scheduleSetCursor(n)}removeLastParam(){this.pillsController.removeLastParam()}findChipSpanAt(e){let n=0;for(let i of this.store.get().segments){let o=n;if(n+=i.value.length,i.type!=="text"&&e>o&&e<=n)return{kind:i.type,param:i.param,start:o,end:n}}return null}withoutChip(e,n){return n.kind==="completed"?{completedParams:e.completedParams.filter(i=>i.id!==n.param.id)}:{identifiedParams:e.identifiedParams.filter(i=>i.id!==n.param.id)}}removeParamAtCaret(e){let n=this.findChipSpanAt(e);if(!n)return!1;let{text:i}=this.store.get(),{start:o,end:r}=n;if(e===r){let{text:l,removed:d}=gt(i,o,r);return this.store.set(c=>({text:l,filterBase:Math.min(c.filterBase>o?Math.max(o,c.filterBase-d):c.filterBase,l.length),...this.withoutChip(c,n),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(o),!0}let s=tt(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,n),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(s),!0}startEditingParamAtCaret(e){let n=this.findChipSpanAt(e);return!n||n.kind!=="completed"||n.end!==e?!1:(this.reEdit.start(n.param.id),this.store.get().editingParam?.id===n.param.id)}scheduleSetCursor(e){queueMicrotask(()=>{let n=this.domRefs;if(n)n.input.focus(),O(n.input,e);else{let i=this.opts.setCursor;i&&this.boundary.runListener("setCursor",()=>i(e))}})}clearNewParamId(){this.store.set({newParamId:null})}startEditingIdentified(e){let n=this.store.get();if(n.editingIdentified?.id===e)return!0;let i=n.identifiedParams.find(c=>c.id===e);if(!i)return!1;let o=q(i);if(!v(o))return!1;let r=z(i.text),s=o==="date-range"||r?"date-range":"date",a=0,l=-1;for(let c of n.segments){if(c.type!=="text"&&c.param.id===e){l=a;break}a+=c.value.length}if(l<0)return!1;let d=l+i.text.length;return this.store.set({editingIdentified:{id:e,type:i.type,anchor:l,tail:d,text:i.text,iso:r?r.start:De(i),isoEnd:r?r.end:null,format:s},editingParam:null,editingAnchor:null,editingTail:null,caretOffset:d,activeDropdownIndex:-1,pillTapped:!0}),!0}exitEditingIdentified(){this.store.get().editingIdentified&&this.store.set({editingIdentified:null,activeDropdownIndex:-1})}startEditingParam(e){this.reEdit.start(e),this.store.get().editingParam?.id!==e&&this.startEditingIdentified(e)}replaceEditingRange(e){return this.reEdit.replaceRange(e)}exitEditMode(){this.reEdit.exit()}handleCaretAfterInput(e){this.reEdit.caretAfterInput(e)}handleCaretMove(e){let n=this.store.get().editingIdentified;n&&e!=null&&(e<n.anchor||e>n.tail)&&this.store.set({editingIdentified:null,activeDropdownIndex:-1}),this.reEdit.caretMove(e)}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}clearHighlight(e){this.store.get().activeDropdownIndex===e&&this.store.set({activeDropdownIndex:-1})}recordSubmit(e){this.fireTelemetry("submit",{query:e.query,completed_pills:e.completed_params.filter(n=>n.placeholder).map(n=>({key:n.type,value:n.text??""}))})}selectProduct(e){let n=this.store.get(),i=n.products.findIndex(r=>r.id===e.id),o=n.customFields?.items?.matched?.find(r=>r.source_id===e.id)?.origin_id;this.fireTelemetry("product_click",{query:n.text,product_id:e.id,...o&&{origin_id:o},position:i>=0?i+1:null}),this.emitter.emit("productSelect",e)}handleTextChange(e){this.applyTextChange(e,!0)}applyTextChange(e,n){this.store.get().editingIdentified&&this.store.set({editingIdentified:null,activeDropdownIndex:-1}),this.handleChange(e,n)}showPreviousMonth(){this.pageDateView(-1)}showNextMonth(){this.pageDateView(1)}pageDateView(e){let n=this.store.get();if(!v(n.activeFormatType)||!n.dateView)return;let i=Ie(n.dateView,e);this.store.set({dateViewMonth:{...i,key:Te(n)},activeDropdownIndex:-1})}skipActivePill(){let e=this.store.get();if(e.editingParam||e.inSelectionAnimation)return;let n=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:[...n,...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 n=`subscribe#${++this.subscriberCount}`;return this.store.subscribe(i=>{this.boundary.runListener("subscribe",()=>e(i),n)})}getState(){return this.store.get()}getResult(){return this.buildResult()}buildResult(){let e=this.store.get();return V(e.text,e.completedParams,e.skippedParams,{identifiedParams:e.identifiedParams,isReady:e.isReady,customFields:e.customFields})}get listboxId(){return this._listboxId}get isReady(){return this.store.get().isReady}on(e,n){return this.emitter.on(e,n)}update(e){let n=this.opts.products,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!==n||"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.productImageFallback!==void 0||e.showChipIcons!==void 0||e.showChipImages!==void 0)&&this.store.set({}),e.value!==void 0&&this.setValue(e.value),e.completedParams!==void 0&&this.store.set({completedParams:e.completedParams})}selectOption(e){let n=!this.store.get().text;this.applyOption(e),n&&this.store.get().text&&this.noteSearchStarted()}applyOption(e){let n=this.store.get();if(n.activeFormatType==="date-range"){let o=N(e);if(o){let r=n.dateRangeStart;if(!r){this.store.set({pendingRangeStart:{iso:o,key:Te(n)}});return}this.store.set({pendingRangeStart:null}),this.selectOption(_n(r,o));return}}if(n.editingIdentified){this.commitIdentifiedDate(e);return}if(n.editingParam&&n.editingAnchor!=null&&n.editingTail!=null){this.timers.clear(wn),this.reEdit.selectOption(e);return}let i=ui(n,e);if(i){if(this.fireTelemetry("option",{raw_query:A(n.text,n.completedParams).rawQuery,selected_option:i.telemetry.selectedOption,other_options:v(n.activeFormatType)?[]:i.telemetry.otherOptions,key:i.telemetry.key,position:v(n.activeFormatType)?null:i.telemetry.position}),this.timers.clear(wn),this.store.set({...i.patch,...ft(n)}),this.startSelectionAnimationTimer(),this.timers.clear(ro),i.remainingActionable>0){let o=i.consumedSuggestion;this.timers.schedule(ro,()=>{this.store.get().suggestions.includes(o)&&this.store.set(r=>({suggestions:r.suggestions.filter(s=>s!==o)}))},so)}this.fetchNow()}}startSelectionAnimationTimer(){this.timers.schedule(Qr,()=>this.store.set({inSelectionAnimation:!1}),so)}resolveVisitorId(){let e=this.opts.visitorId;if(typeof e!="function")return e;try{return e()}catch{return}}resolveSource(){return this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk")}fireImpression(){if(this.funnelTelemetry!==!0)return;let e=this.store.get(),n=e.suggestions.filter(r=>r.type!=="placeholder").map(r=>({key:r.type,options:(r.options??[]).slice(0,Ur).map(s=>s.text)})),i=e.products.map(r=>r.id);if(n.length===0&&i.length===0)return;let o=JSON.stringify([n,i]);o!==this.lastImpressionKey&&(this.lastImpressionKey=o,this.fireTelemetry("impression",{query:e.text,pills:n,product_ids:i}))}fireTelemetry(e,n){let i=this.funnelTelemetry===!0;if(!i&&Kr.has(e))return;if(!i&&e==="option"){let{key:r,position:s,...a}=n;n=a}let o=this.resolveSource();ci({source:o,sessionId:this.sessionId,visitorId:i?this.resolveVisitorId():void 0,requestId:i?this.lastRequestId:null,keepalive:i,type:e,queryData:n,apiConfig:this.opts.apiConfig})}setupContainer(){this.container.classList.add("magicx-aia"),this.container.dataset.pillPlacement=this.renderMode==="dropdown"?"dropdown":this.opts.pillPlacement??"dropdown",this.container.dataset.optionsPosition=this.opts.optionsPosition??"below",this.container.dataset.animations=this.opts.animations??!0?"on":"off",this.modeController=new he(this.container,this.opts.mode??"auto")}buildAndRenderFull(){let e=this,n={store:this.store,listboxId:this.listboxId,get pillPlacement(){return e.opts.pillPlacement??"dropdown"},get showSkipButton(){return e.opts.showSkipButton??!0},get showOptionIcons(){return e.opts.showOptionIcons??!0},get showOptionImages(){return e.opts.showOptionImages??!0},get showOptionCounts(){return e.opts.showOptionCounts??!0},get productsLayout(){return e.opts.productsLayout??"row"},get productImageFallback(){return e.opts.productImageFallback??"image"},get showChipIcons(){return e.opts.showChipIcons??!0},get showChipImages(){return e.opts.showChipImages??!0},get optionsPosition(){return e.opts.optionsPosition??"below"},get onSubmit(){return e.emitter.hasListeners("submit")?e.emitSubmit:void 0},afterSubmit:()=>e.resetAfterSubmit(),submitButton:this.opts.submitButton,autoFocus:this.opts.autoFocus??!0,selectOption: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,!0),startEditingParam:o=>this.startEditingParam(o),handleCaretAfterInput:o=>this.handleCaretAfterInput(o),handleCaretMove:o=>this.handleCaretMove(o),replaceEditingRange:o=>this.replaceEditingRange(o)};this.domRefs=Ji(this.container,n);let i=()=>{this.domRefs&&vn(this.domRefs,this.store.get(),n)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),vn(this.domRefs,this.store.get(),n),this.subscribeNewParamTimer()}buildAndRenderDropdown(){let e=this,n={store:this.store,listboxId:this.listboxId,get showSkipButton(){return e.opts.showSkipButton??!0},get showOptionIcons(){return e.opts.showOptionIcons??!0},get showOptionImages(){return e.opts.showOptionImages??!0},get showOptionCounts(){return e.opts.showOptionCounts??!0},get productsLayout(){return e.opts.productsLayout??"row"},get productImageFallback(){return e.opts.productImageFallback??"image"},get optionsPosition(){return e.opts.optionsPosition??"below"},selectOption: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=Qi(this.container,n);let i=()=>{this.dropdownRefs&&xn(this.dropdownRefs,this.store.get(),n)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),xn(this.dropdownRefs,this.store.get(),n),this.subscribeNewParamTimer()}subscribeViewportBreakpoint(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;let n=window.matchMedia(Pe),i=()=>e();n.addEventListener("change",i),this.unsubscribers.push(()=>n.removeEventListener("change",i))}subscribeBatchedRender(e){let n=!1;this.unsubscribers.push(this.store.subscribe(()=>{n||(n=!0,queueMicrotask(()=>{n=!1,e()}))}))}subscribeSkeletonMirror(){this.unsubscribers.push(this.store.subscribe((e,n)=>{if(!e.skeletonOptions)return;if(!n.isLoading&&e.isLoading){e.skeletonRequested||this.store.set({skeletonRequested:!0});return}if(!n.isLoading||e.isLoading)return;let i={skeletonOptions:null,skeletonSuggestion:null,skeletonRequested:!1};if(!e.skeletonExiting){this.store.set(i);return}this.timers.schedule(wn,()=>this.store.set(i),Jr)}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,n)=>{e.newParamId&&e.newParamId!==n.newParamId&&this.timers.schedule(Yr,()=>this.store.set({newParamId:null}),Xr)}))}handleChange(e,n){let i=this.store.get();n&&e&&!i.text&&this.noteSearchStarted(),this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:o,invalid:r}=zn(e,i.completedParams);r.length>0&&this.store.set({completedParams:o}),this.maybePromoteExactMatch(e),this.maybeOpenPendingSpan()}maybeOpenPendingSpan(){let e=this.store.get();if(e.pendingSpan||e.actionableSuggestions.length===0)return;let n=G(e.text,Math.min(e.filterBase,e.text.length),e.placeholderText),i=Vn(e.segments,n);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 n=e.caretOffset??e.editingAnchor,i=e.text.slice(e.editingAnchor,n);Z(e.editingParam.options,i).some(r=>r.is_tappable)||(this.reEdit.exit(),this.fetchNow())}fetchNow(){let e=this.store.get(),{rawQuery:n,completedParams:i}=A(e.text,e.completedParams);this.fetchController.doFetch(n,i)}commitIdentifiedDate(e){let n=this.store.get(),i=n.editingIdentified;if(!i)return;if(n.text.slice(i.anchor,i.tail)!==i.text){this.store.set({editingIdentified:null,activeDropdownIndex:-1});return}let o=n.text.slice(0,i.anchor),r=n.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,d=o+l+r,c=d.length,u={id:crypto.randomUUID(),placeholder:"",type:i.type,text:s,value:e.value,kind:e.kind,suggestionType:i.type,suggestionPlaceholder:B(i.type),options:[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url};this.fireTelemetry("option",{raw_query:A(n.text,n.completedParams).rawQuery,selected_option:e.text,other_options:[],key:i.type,position:null}),this.store.set({text:d,completedParams:[...n.completedParams,u],identifiedParams:n.identifiedParams.filter(m=>m.id!==i.id),newParamId:u.id,filterBase:c,caretOffset:c,editingIdentified:null,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.startSelectionAnimationTimer(),this.scheduleSetCursor(c),this.fetchNow()}maybePromoteExactMatch(e){let n=this.store.get();if(v(n.activeFormatType))return;let i=mt({mode:"fresh",text:e,completedParams:n.completedParams,suggestions:n.suggestions,filterBase:n.filterBase,filterInProgress:n.filterInProgress});i&&this.store.set(i.patch)}};0&&(module.exports={AIAutocomplete,ATTRIBUTION_URL,DATE_RANGE_META_END,DATE_RANGE_META_START,DEFAULT_OPTION_COUNT_UNIT,ModeController,OPTIONS_GRID_MOBILE_QUERY,OPTION_ENTER_DELAY_VAR,OPTION_ENTER_FADE_MS,OPTION_ENTER_RISE_MS,OPTION_ENTER_RISE_PX,OPTION_ENTER_STAGGER_MS,PLACEHOLDER_FADE_OUT_MS,PLACEHOLDER_LEAVING_ATTR,PLACEHOLDER_SWAP_GAP_MS,PLACEHOLDER_TYPE_MS,PLACEHOLDER_WORD_PAUSE_MS,PRODUCT_PATH_PREFIX,PRODUCT_ROW_PX_PER_LINE,RANGE_SEPARATOR,SCROLL_ARROW_ATTR,SCROLL_ARROW_BOTTOM_VAR,SCROLL_ARROW_CLASS,SCROLL_ARROW_FADE_MS,SCROLL_ARROW_LABEL,SCROLL_ARROW_SCROLL_IDLE_MS,SCROLL_ARROW_VISIBLE_ATTR,SKIPPED_PARAM_TEXT,WEEKDAY_LABELS,addMonths,attachProductRowWheel,attachScrollArrow,buildAttributionUrl,buildDateOptions,buildQuery,buildSubmitResult,cellDay,cellIso,chipIdFromTap,computeOptionsGridLayout,containScroll,createStore,cursorIsAtEnd,dateCellMarks,dateSelectionFor,extractPlainText,formatAbsoluteDate,formatDate,formatDateRange,formatOptionCount,getCursorOffset,getFooterHint,identifiedParamLabel,isCalendarFormat,isOptionsGridMobileViewport,isoDate,keepCaretOnChip,measureOptionsGrid,monthLabel,needsOptionsGridMeasurement,optionCountLabel,optionEnterDelayMs,optionHasImage,optionImageSrc,optionLabel,optionsEntranceDurationMs,optionsGridTemplateColumns,parseDate,parseLooseDate,parseLooseDateRange,plainTextLength,planOptionsGrid,previousGraphemeBoundary,productFromMatchedItem,productInitial,productRowWheelTarget,productsFromCustomFields,renderEditableContent,resolveFormatType,resolveIdentifiedDate,sameOptionRows,sanitizeOptionIconSvg,scrollCaretIntoView,selectedIsoFromText,selectedRangeFor,setCursorOffset,toWireIdentifiedParams,visibleDateRange,withSkippedParams});
|
|
2242
|
+
`;var Nt=class{constructor(){this.reported=new Set}run(e,n){try{return n()}catch(i){this.report(e,i,e);return}}runListener(e,n,i=e){try{return n(),!0}catch(o){return this.report(e,o,i),!1}}report(e,n,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.`,n))}};var Ft=class{constructor(e){this.boundary=e;this.listeners={};this.keys=new WeakMap;this.registrationCount=0}on(e,n){let i=`${String(e)}#${++this.registrationCount}`,o=(...s)=>n(...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,...n){let i=this.listeners[e];if(!i)return!0;let o=!0;for(let r of i)this.boundary.runListener(String(e),()=>r(...n),this.keys.get(r)??String(e))||(o=!1);return o}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var Ht=class{constructor(){this.timers=new Map}schedule(e,n,i){this.clear(e);let o=setTimeout(()=>{this.timers.delete(e),n()},i);this.timers.set(e,o)}clear(e){let n=this.timers.get(e);n!==void 0&&(clearTimeout(n),this.timers.delete(e))}clearAll(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};var he=class{constructor(e,n="auto",i){this.container=e;this.mode=n;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)}};var Yr=50,Qr=new Set(["search_started","submit","product_click","impression"]),Xr="newParam",ro="suggestionRemoval",jr="selectionAnimation",wn="skeletonExit",zr=650,Jr=0;function Zr(){return`:ac-${++Jr}:`}var so=170,es=100;function ao(){return{text:"",completedParams:[],identifiedParams:[],skippedParams:[],pendingSpan:null,suggestions:[],products:[],customFields:null,optionSearch:null,activeDropdownIndex:-1,newParamId:null,isLoading:!1,isReady:!1,error:null,filterBase:0,filterInProgress:!1,pillTapped:!1,skipNextFetch:!1,lastRawQuery:"",isFocused:!1,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:null,inSelectionAnimation:!1,skeletonOptions:null,skeletonSuggestion:null,skeletonRequested:!1,dateViewMonth:null,pendingRangeStart:null,editingIdentified:null}}var Bt=class{constructor(e,n={}){this.inputStore=_t(ao());this._listboxId=Zr();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new Ht;this.boundary=new Nt;this.subscriberCount=0;this.emitter=new Ft(this.boundary);this.sessionId=crypto.randomUUID();this.lastRequestId=null;this.searchStartedSessionId=null;this.funnelTelemetry=null;this.pendingSearchStarted=!1;this.lastImpressionKey="";this.emitSubmit=e=>(this.recordSubmit(e),this.emitter.emit("submit",e));this.emitError=e=>this.emitter.emit("error",e);this.container=e,this.opts=n,this.renderMode=n.renderMode??"full",this.store=Zi(this.inputStore,i=>di(i,this.opts)),n.onSubmit&&this.emitter.on("submit",n.onSubmit),n.onResult&&this.emitter.on("result",n.onResult),n.onError&&this.emitter.on("error",n.onError),n.onChange&&this.emitter.on("change",n.onChange),n.onParamsChange&&this.emitter.on("paramsChange",n.onParamsChange),n.onStateChange&&this.emitter.on("stateChange",n.onStateChange),n.onFocus&&this.emitter.on("focus",n.onFocus),n.onBlur&&this.emitter.on("blur",n.onBlur),n.onProductSelect&&this.emitter.on("productSelect",n.onProductSelect),n.value!==void 0&&this.store.set({text:n.value}),n.completedParams!==void 0&&this.store.set({completedParams:n.completedParams}),this.pillsController=new ot(this.store,{onPillSelected:({rawQuery:i,selectedPill:o,otherPills:r})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:o,other_pills:r})}}),this.reEdit=new ht({store:this.store,scheduleSetCursor:i=>this.scheduleSetCursor(i),fireTelemetry:(i,o)=>this.fireTelemetry(i,o),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer(),fetchNow:()=>this.fetchNow()}),this.productsController=new st(this.store,()=>this.opts.products,()=>this.opts.showProducts!==!1),this.optionSource=new it(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 Ue(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})=>{let s=i.options??[];this.fireTelemetry("option",{raw_query:r,selected_option:o.text,other_options:s.filter(a=>a.text!==o.text).map(a=>a.text),key:i.type,position:ue(s,o.text)})},onResponse:({requestId:i,funnelTelemetry:o})=>{this.lastRequestId=i,this.funnelTelemetry=o,this.pendingSearchStarted&&(this.pendingSearchStarted=!1,this.fireTelemetry("search_started",{})),this.fireImpression(),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 nt(this.store,{columns:n.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.emitter.hasListeners("submit")?this.emitSubmit:void 0,getOptionsPosition:()=>this.opts.optionsPosition??"below",afterSubmit:this.renderMode==="full"?()=>this.resetAfterSubmit():void 0,selectOption: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.subscribeSkeletonMirror(),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}=Ge(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===Te(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=Yn(o.text,i.text,s);if(l===null){this.store.set({pendingSpan:null});return}s=l}i.text.slice(s).trim().length===0||Vn(i.segments,s)?this.store.set({pendingSpan:null}):s!==r.anchor&&this.store.set({pendingSpan:{anchor:s,snapshot:r.snapshot}})})),this.renderMode!=="headless"&&(io(this.opts.styleRoot??ee(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({...ao(),isFocused:e,skipNextFetch:!0}),this.sessionId=crypto.randomUUID(),this.lastRequestId=null,this.lastImpressionKey="",this.pendingSearchStarted=!1,this.fetchController.doFetch("",[])}resetAfterSubmit(){this.opts.resetOnSubmit!==!1&&this.reset()}destroy(){this.fetchController.dispose(),this.optionSource.dispose(),this.modeController?.destroy(),this.timers.clearAll(),this.emitter.clear();for(let e of this.unsubscribers)e();this.unsubscribers=[],this.domRefs?.abort.abort(),this.domRefs&&(xi(this.domRefs.input),Sn(this.domRefs.dropdown)),this.dropdownRefs&&Sn(this.dropdownRefs.dropdown),this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}prefillText(e){this.applyTextChange(e,!1)}noteSearchStarted(){this.searchStartedSessionId!==this.sessionId&&(this.searchStartedSessionId=this.sessionId,this.funnelTelemetry===null?this.pendingSearchStarted=!0:this.fireTelemetry("search_started",{}))}setValue(e){let n=this.store.get();if(n.editingIdentified&&e!==n.text){this.store.set({text:e,editingIdentified:null,activeDropdownIndex:-1});return}this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e);let n=this.store.get().text.length;this.store.set({caretOffset:n,isFocused:!0}),this.scheduleSetCursor(n)}removeLastParam(){this.pillsController.removeLastParam()}findChipSpanAt(e){let n=0;for(let i of this.store.get().segments){let o=n;if(n+=i.value.length,i.type!=="text"&&e>o&&e<=n)return{kind:i.type,param:i.param,start:o,end:n}}return null}withoutChip(e,n){return n.kind==="completed"?{completedParams:e.completedParams.filter(i=>i.id!==n.param.id)}:{identifiedParams:e.identifiedParams.filter(i=>i.id!==n.param.id)}}removeParamAtCaret(e){let n=this.findChipSpanAt(e);if(!n)return!1;let{text:i}=this.store.get(),{start:o,end:r}=n;if(e===r){let{text:l,removed:d}=gt(i,o,r);return this.store.set(c=>({text:l,filterBase:Math.min(c.filterBase>o?Math.max(o,c.filterBase-d):c.filterBase,l.length),...this.withoutChip(c,n),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(o),!0}let s=tt(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,n),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(s),!0}startEditingParamAtCaret(e){let n=this.findChipSpanAt(e);return!n||n.kind!=="completed"||n.end!==e?!1:(this.reEdit.start(n.param.id),this.store.get().editingParam?.id===n.param.id)}scheduleSetCursor(e){queueMicrotask(()=>{let n=this.domRefs;if(n)n.input.focus(),O(n.input,e);else{let i=this.opts.setCursor;i&&this.boundary.runListener("setCursor",()=>i(e))}})}clearNewParamId(){this.store.set({newParamId:null})}startEditingIdentified(e){let n=this.store.get();if(n.editingIdentified?.id===e)return!0;let i=n.identifiedParams.find(c=>c.id===e);if(!i)return!1;let o=q(i);if(!v(o))return!1;let r=z(i.text),s=o==="date-range"||r?"date-range":"date",a=0,l=-1;for(let c of n.segments){if(c.type!=="text"&&c.param.id===e){l=a;break}a+=c.value.length}if(l<0)return!1;let d=l+i.text.length;return this.store.set({editingIdentified:{id:e,type:i.type,anchor:l,tail:d,text:i.text,iso:r?r.start:De(i),isoEnd:r?r.end:null,format:s},editingParam:null,editingAnchor:null,editingTail:null,caretOffset:d,activeDropdownIndex:-1,pillTapped:!0}),!0}exitEditingIdentified(){this.store.get().editingIdentified&&this.store.set({editingIdentified:null,activeDropdownIndex:-1})}startEditingParam(e){this.reEdit.start(e),this.store.get().editingParam?.id!==e&&this.startEditingIdentified(e)}replaceEditingRange(e){return this.reEdit.replaceRange(e)}exitEditMode(){this.reEdit.exit()}handleCaretAfterInput(e){this.reEdit.caretAfterInput(e)}handleCaretMove(e){let n=this.store.get().editingIdentified;n&&e!=null&&(e<n.anchor||e>n.tail)&&this.store.set({editingIdentified:null,activeDropdownIndex:-1}),this.reEdit.caretMove(e)}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}clearHighlight(e){this.store.get().activeDropdownIndex===e&&this.store.set({activeDropdownIndex:-1})}recordSubmit(e){this.fireTelemetry("submit",{query:e.query,completed_pills:e.completed_params.filter(n=>n.placeholder).map(n=>({key:n.type,value:n.text??""}))})}selectProduct(e){let n=this.store.get(),i=n.products.findIndex(r=>r.id===e.id),o=n.customFields?.items?.matched?.find(r=>r.source_id===e.id)?.origin_id;this.fireTelemetry("product_click",{query:n.text,product_id:e.id,...o&&{origin_id:o},position:i>=0?i+1:null}),this.emitter.emit("productSelect",e)}handleTextChange(e){this.applyTextChange(e,!0)}applyTextChange(e,n){this.store.get().editingIdentified&&this.store.set({editingIdentified:null,activeDropdownIndex:-1}),this.handleChange(e,n)}showPreviousMonth(){this.pageDateView(-1)}showNextMonth(){this.pageDateView(1)}pageDateView(e){let n=this.store.get();if(!v(n.activeFormatType)||!n.dateView)return;let i=Ie(n.dateView,e);this.store.set({dateViewMonth:{...i,key:Te(n)},activeDropdownIndex:-1})}skipActivePill(){let e=this.store.get();if(e.editingParam||e.inSelectionAnimation)return;let n=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:[...n,...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 n=`subscribe#${++this.subscriberCount}`;return this.store.subscribe(i=>{this.boundary.runListener("subscribe",()=>e(i),n)})}getState(){return this.store.get()}getResult(){return this.buildResult()}buildResult(){let e=this.store.get();return U(e.text,e.completedParams,e.skippedParams,{identifiedParams:e.identifiedParams,isReady:e.isReady,customFields:e.customFields})}get listboxId(){return this._listboxId}get isReady(){return this.store.get().isReady}on(e,n){return this.emitter.on(e,n)}update(e){let n=this.opts.products,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!==n||"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.productImageFallback!==void 0||e.showChipIcons!==void 0||e.showChipImages!==void 0)&&this.store.set({}),e.value!==void 0&&this.setValue(e.value),e.completedParams!==void 0&&this.store.set({completedParams:e.completedParams})}selectOption(e){let n=!this.store.get().text;this.applyOption(e),n&&this.store.get().text&&this.noteSearchStarted()}applyOption(e){let n=this.store.get();if(n.activeFormatType==="date-range"){let o=N(e);if(o){let r=n.dateRangeStart;if(!r){this.store.set({pendingRangeStart:{iso:o,key:Te(n)}});return}this.store.set({pendingRangeStart:null}),this.selectOption(_n(r,o));return}}if(n.editingIdentified){this.commitIdentifiedDate(e);return}if(n.editingParam&&n.editingAnchor!=null&&n.editingTail!=null){this.timers.clear(wn),this.reEdit.selectOption(e);return}let i=ui(n,e);if(i){if(this.fireTelemetry("option",{raw_query:A(n.text,n.completedParams).rawQuery,selected_option:i.telemetry.selectedOption,other_options:v(n.activeFormatType)?[]:i.telemetry.otherOptions,key:i.telemetry.key,position:v(n.activeFormatType)?null:i.telemetry.position}),this.timers.clear(wn),this.store.set({...i.patch,...ft(n)}),this.startSelectionAnimationTimer(),this.timers.clear(ro),i.remainingActionable>0){let o=i.consumedSuggestion;this.timers.schedule(ro,()=>{this.store.get().suggestions.includes(o)&&this.store.set(r=>({suggestions:r.suggestions.filter(s=>s!==o)}))},so)}this.fetchNow()}}startSelectionAnimationTimer(){this.timers.schedule(jr,()=>this.store.set({inSelectionAnimation:!1}),so)}resolveVisitorId(){let e=this.opts.visitorId;if(typeof e!="function")return e;try{return e()}catch{return}}resolveSource(){return this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk")}fireImpression(){if(this.funnelTelemetry!==!0)return;let e=this.store.get(),n=e.suggestions.filter(r=>r.type!=="placeholder").map(r=>({key:r.type,options:(r.options??[]).slice(0,Yr).map(s=>s.text)})),i=e.products.map(r=>r.id);if(n.length===0&&i.length===0)return;let o=JSON.stringify([n,i]);o!==this.lastImpressionKey&&(this.lastImpressionKey=o,this.fireTelemetry("impression",{query:e.text,pills:n,product_ids:i}))}fireTelemetry(e,n){let i=this.funnelTelemetry===!0;if(!i&&Qr.has(e))return;if(!i&&e==="option"){let{key:r,position:s,...a}=n;n=a}let o=this.resolveSource();ci({source:o,sessionId:this.sessionId,visitorId:i?this.resolveVisitorId():void 0,requestId:i?this.lastRequestId:null,keepalive:i,type:e,queryData:n,apiConfig:this.opts.apiConfig})}setupContainer(){this.container.classList.add("magicx-aia"),this.container.dataset.pillPlacement=this.renderMode==="dropdown"?"dropdown":this.opts.pillPlacement??"dropdown",this.container.dataset.optionsPosition=this.opts.optionsPosition??"below",this.container.dataset.animations=this.opts.animations??!0?"on":"off",this.modeController=new he(this.container,this.opts.mode??"auto")}buildAndRenderFull(){let e=this,n={store:this.store,listboxId:this.listboxId,get pillPlacement(){return e.opts.pillPlacement??"dropdown"},get showSkipButton(){return e.opts.showSkipButton??!0},get showOptionIcons(){return e.opts.showOptionIcons??!0},get showOptionImages(){return e.opts.showOptionImages??!0},get showOptionCounts(){return e.opts.showOptionCounts??!0},get productsLayout(){return e.opts.productsLayout??"row"},get productImageFallback(){return e.opts.productImageFallback??"image"},get showChipIcons(){return e.opts.showChipIcons??!0},get showChipImages(){return e.opts.showChipImages??!0},get optionsPosition(){return e.opts.optionsPosition??"below"},get onSubmit(){return e.emitter.hasListeners("submit")?e.emitSubmit:void 0},afterSubmit:()=>e.resetAfterSubmit(),submitButton:this.opts.submitButton,autoFocus:this.opts.autoFocus??!0,selectOption: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,!0),startEditingParam:o=>this.startEditingParam(o),handleCaretAfterInput:o=>this.handleCaretAfterInput(o),handleCaretMove:o=>this.handleCaretMove(o),replaceEditingRange:o=>this.replaceEditingRange(o)};this.domRefs=Ji(this.container,n);let i=()=>{this.domRefs&&vn(this.domRefs,this.store.get(),n)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),vn(this.domRefs,this.store.get(),n),this.subscribeNewParamTimer()}buildAndRenderDropdown(){let e=this,n={store:this.store,listboxId:this.listboxId,get showSkipButton(){return e.opts.showSkipButton??!0},get showOptionIcons(){return e.opts.showOptionIcons??!0},get showOptionImages(){return e.opts.showOptionImages??!0},get showOptionCounts(){return e.opts.showOptionCounts??!0},get productsLayout(){return e.opts.productsLayout??"row"},get productImageFallback(){return e.opts.productImageFallback??"image"},get optionsPosition(){return e.opts.optionsPosition??"below"},selectOption: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=Qi(this.container,n);let i=()=>{this.dropdownRefs&&xn(this.dropdownRefs,this.store.get(),n)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),xn(this.dropdownRefs,this.store.get(),n),this.subscribeNewParamTimer()}subscribeViewportBreakpoint(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;let n=window.matchMedia(Pe),i=()=>e();n.addEventListener("change",i),this.unsubscribers.push(()=>n.removeEventListener("change",i))}subscribeBatchedRender(e){let n=!1;this.unsubscribers.push(this.store.subscribe(()=>{n||(n=!0,queueMicrotask(()=>{n=!1,e()}))}))}subscribeSkeletonMirror(){this.unsubscribers.push(this.store.subscribe((e,n)=>{if(!e.skeletonOptions)return;if(!n.isLoading&&e.isLoading){e.skeletonRequested||this.store.set({skeletonRequested:!0});return}if(!n.isLoading||e.isLoading)return;let i={skeletonOptions:null,skeletonSuggestion:null,skeletonRequested:!1};if(!e.skeletonExiting){this.store.set(i);return}this.timers.schedule(wn,()=>this.store.set(i),es)}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,n)=>{e.newParamId&&e.newParamId!==n.newParamId&&this.timers.schedule(Xr,()=>this.store.set({newParamId:null}),zr)}))}handleChange(e,n){let i=this.store.get();n&&e&&!i.text&&this.noteSearchStarted(),this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:o,invalid:r}=zn(e,i.completedParams);r.length>0&&this.store.set({completedParams:o}),this.maybePromoteExactMatch(e),this.maybeOpenPendingSpan()}maybeOpenPendingSpan(){let e=this.store.get();if(e.pendingSpan||e.actionableSuggestions.length===0)return;let n=$(e.text,Math.min(e.filterBase,e.text.length),e.placeholderText),i=Un(e.segments,n);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 n=e.caretOffset??e.editingAnchor,i=e.text.slice(e.editingAnchor,n);Z(e.editingParam.options,i).some(r=>r.is_tappable)||(this.reEdit.exit(),this.fetchNow())}fetchNow(){let e=this.store.get(),{rawQuery:n,completedParams:i}=A(e.text,e.completedParams);this.fetchController.doFetch(n,i)}commitIdentifiedDate(e){let n=this.store.get(),i=n.editingIdentified;if(!i)return;if(n.text.slice(i.anchor,i.tail)!==i.text){this.store.set({editingIdentified:null,activeDropdownIndex:-1});return}let o=n.text.slice(0,i.anchor),r=n.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,d=o+l+r,c=d.length,u={id:crypto.randomUUID(),placeholder:"",type:i.type,text:s,value:e.value,kind:e.kind,suggestionType:i.type,suggestionPlaceholder:B(i.type),options:[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url};this.fireTelemetry("option",{raw_query:A(n.text,n.completedParams).rawQuery,selected_option:e.text,other_options:[],key:i.type,position:null}),this.store.set({text:d,completedParams:[...n.completedParams,u],identifiedParams:n.identifiedParams.filter(m=>m.id!==i.id),newParamId:u.id,filterBase:c,caretOffset:c,editingIdentified:null,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.startSelectionAnimationTimer(),this.scheduleSetCursor(c),this.fetchNow()}maybePromoteExactMatch(e){let n=this.store.get();if(v(n.activeFormatType))return;let i=mt({mode:"fresh",text:e,completedParams:n.completedParams,suggestions:n.suggestions,filterBase:n.filterBase,filterInProgress:n.filterInProgress});i&&this.store.set(i.patch)}};0&&(module.exports={AIAutocomplete,ATTRIBUTION_URL,DATE_RANGE_META_END,DATE_RANGE_META_START,DEFAULT_OPTION_COUNT_UNIT,ModeController,OPTIONS_GRID_MOBILE_QUERY,OPTION_ENTER_DELAY_VAR,OPTION_ENTER_FADE_MS,OPTION_ENTER_RISE_MS,OPTION_ENTER_RISE_PX,OPTION_ENTER_STAGGER_MS,PLACEHOLDER_FADE_OUT_MS,PLACEHOLDER_LEAVING_ATTR,PLACEHOLDER_SWAP_GAP_MS,PLACEHOLDER_TYPE_MS,PLACEHOLDER_WORD_PAUSE_MS,PRODUCT_PATH_PREFIX,PRODUCT_ROW_PX_PER_LINE,RANGE_SEPARATOR,SCROLL_ARROW_ATTR,SCROLL_ARROW_BOTTOM_VAR,SCROLL_ARROW_CLASS,SCROLL_ARROW_FADE_MS,SCROLL_ARROW_LABEL,SCROLL_ARROW_SCROLL_IDLE_MS,SCROLL_ARROW_VISIBLE_ATTR,SKIPPED_PARAM_TEXT,WEEKDAY_LABELS,addMonths,attachProductRowWheel,attachScrollArrow,buildAttributionUrl,buildDateOptions,buildQuery,buildSubmitResult,cellDay,cellIso,chipIdFromTap,computeOptionsGridLayout,containScroll,createStore,cursorIsAtEnd,dateCellMarks,dateSelectionFor,extractPlainText,formatAbsoluteDate,formatDate,formatDateRange,formatOptionCount,getCursorOffset,getFooterHint,identifiedParamLabel,isCalendarFormat,isOptionsGridMobileViewport,isoDate,keepCaretOnChip,measureOptionsGrid,monthLabel,needsOptionsGridMeasurement,optionCountLabel,optionEnterDelayMs,optionHasImage,optionImageSrc,optionLabel,optionsEntranceDurationMs,optionsGridTemplateColumns,parseDate,parseLooseDate,parseLooseDateRange,plainTextLength,planOptionsGrid,previousGraphemeBoundary,productFromMatchedItem,productInitial,productRowWheelTarget,productsFromCustomFields,renderEditableContent,resolveFormatType,resolveIdentifiedDate,sameOptionRows,sanitizeOptionIconSvg,scrollCaretIntoView,selectedIsoFromText,selectedRangeFor,setCursorOffset,toWireIdentifiedParams,visibleDateRange,withSkippedParams});
|
|
2187
2243
|
//# sourceMappingURL=index.js.map
|