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