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