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