@magicx-eng/ai-autocomplete-vanilla 0.18.0 → 0.19.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 +25 -4
- package/dist/index.d.mts +214 -11
- package/dist/index.d.ts +214 -11
- package/dist/index.js +9 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +9 -2
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
function Ne(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9]+/).filter(Boolean).map(e=>e.toLowerCase())}function N(n){let e=Ne(n);return e.length>0?e.join(" "):n}var G=["January","February","March","April","May","June","July","August","September","October","November","December"],te=["S","M","T","W","T","F","S"],Pt=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],Et="aiaDate",wt="aiaDay",St=n=>String(n).padStart(2,"0");function I(n){return`${n.getFullYear()}-${St(n.getMonth()+1)}-${St(n.getDate())}`}function He(n){return new Date(n.getFullYear(),n.getMonth(),n.getDate())}function Fn(n){let e=He(n).getTime()-He(new Date).getTime();return Math.round(e/864e5)}function Tt(n){let e=Fn(n);return e>=0&&e<7?Pt[n.getDay()]:n.getFullYear()===new Date().getFullYear()?`${G[n.getMonth()]} ${n.getDate()}`:`${G[n.getMonth()]} ${n.getDate()} ${n.getFullYear()}`}function ne(n){if(!n)return null;let e=Pt.findIndex(a=>a.toLowerCase()===n.trim().toLowerCase());if(e>=0){let a=He(new Date),d=(e-a.getDay()+7)%7;return new Date(a.getFullYear(),a.getMonth(),a.getDate()+d)}let t=/^\s*([A-Za-z]+)\s+(\d{1,2})(?:\s+(\d{4}))?\s*$/.exec(n);if(!t)return null;let i=G.findIndex(a=>a.toLowerCase()===t[1].toLowerCase());if(i<0)return null;let r=Number(t[2]),o=t[3]?Number(t[3]):new Date().getFullYear(),s=new Date(o,i,r);return s.getMonth()!==i||s.getDate()!==r?null:s}function Fe(n){return`${G[n.month]} ${n.year}`}function Be(){let n=new Date;return{year:n.getFullYear(),month:n.getMonth()}}function Ct(n){return{year:n.getFullYear(),month:n.getMonth()}}function We(n,e){let t=new Date(n.year,n.month+e,1);return{year:t.getFullYear(),month:t.getMonth()}}function vt(){return{text:"",is_tappable:!1,kind:null}}function Ge(n){let e=new Date(n.year,n.month,1).getDay(),t=new Date(n.year,n.month+1,0).getDate(),i=[];for(let r=0;r<e;r++)i.push(vt());for(let r=1;r<=t;r++){let o=new Date(n.year,n.month,r);i.push({text:Tt(o),is_tappable:!0,kind:null,metadata:{[Et]:I(o),[wt]:r}})}for(;i.length%te.length!==0;)i.push(vt());return i}function j(n){let e=ne(n);return e?I(e):null}function V(n){let e=n?.metadata?.[Et];return typeof e=="string"?e:null}function Ve(n){let e=n?.metadata?.[wt];return typeof e=="number"?e:null}function Bn(n){return n.replace(/(\d+)(?:st|nd|rd|th)\b/g,"$1")}function At(n){let e=n.toLowerCase().replace(/\.$/,"");return e.length<3?-1:G.findIndex(t=>t.toLowerCase().startsWith(e))}function Wn(n,e,t){let i=new Date(t.getFullYear(),n,e);if(i.getMonth()!==n||i.getDate()!==e)return null;let r=new Date(t.getFullYear(),t.getMonth(),t.getDate());if(i>=r)return i;let o=new Date(t.getFullYear()+1,n,e);return o.getMonth()===n&&o.getDate()===e?o:null}function Ot(n,e,t){let i=new Date(n,e,t);return i.getMonth()===e&&i.getDate()===t?i:null}function re(n,e={}){if(!n)return null;let t=e.today??new Date,i=Bn(n.trim().toLowerCase()).replace(/\s+/g," "),r=/^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(i);if(r){let d=Ot(Number(r[1]),Number(r[2])-1,Number(r[3]));return d?I(d):null}let o=/^([a-z]+)\.? (\d{1,2})(?:,? (\d{4}))?$/.exec(i);if(o){let d=At(o[1]);if(d>=0)return ie(d,Number(o[2]),o[3],t)}let s=/^(\d{1,2}) (?:of )?([a-z]+)\.?(?:,? (\d{4}))?$/.exec(i);if(s){let d=At(s[2]);if(d>=0)return ie(d,Number(s[1]),s[3],t)}let a=/^(\d{1,2})[/\-.](\d{1,2})(?:[/\-.](\d{2,4}))?$/.exec(i);if(a){let d=Number(a[1]),l=Number(a[2]);return d>12&&l<=12?ie(l-1,d,a[3],t):l>12&&d<=12?ie(d-1,l,a[3],t):null}return null}function ie(n,e,t,i){if(t){if(t.length!==4)return null;let o=Ot(Number(t),n,e);return o?I(o):null}let r=Wn(n,e,i);return r?I(r):null}function qe(n,e={}){let t=n.isoDate;return typeof t=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t)?t:re(n.text,e)}var Gn=new Set(["date","dates"]),It=3;function Vn(n){if(!n)return 0;let e=0;for(let t of n)if(t.is_tappable&&(re(t.text)!==null&&(e+=1),e>=It))return e;return e}function H(n){if(!n)return"options";let e=n.formatType;return e==="date"||e==="options"?e:Ne(n.type).some(t=>Gn.has(t))||Vn(n.options)>=It?"date":"options"}var oe=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 qn="https://api.ai-autocomplete.com",se=`${qn}/api/suggest`,Mt=new WeakMap;function z(n){return n?.type==="accessToken"}function $n(n){if(!(!n||z(n)))return n}function ae(n){let e=Mt.get(n.getAccessToken);return e||(e=new oe(n),Mt.set(n.getAccessToken,e)),e}function le(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function de(n){let e=$n(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}function X(n){return n.map(e=>({type:e.type,value:e.text}))}var Lt="skipped";function J(n,e){if(e.length===0)return n;let t=new Set(n.map(r=>r.type)),i=e.filter(r=>!t.has(r.type)).map(r=>({placeholder:"",type:r.type,text:Lt,kind:null}));return i.length>0?[...n,...i]:n}var Kn="0.18.0",Dt=!1;function Un(){return crypto.randomUUID()}function Qn(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.text},kind:n.kind}}function Yn(n,e,t,i,r,o,s,a){let d=e.find(c=>c.type==="contact"&&c.metadata?.contact_account_count)?.metadata?.contact_account_count,l=typeof d=="number"?d:void 0;return{data:{raw_query:n,completed_params:J(e.map(c=>Qn(c,t)),s??[]),...r&&r.length>0&&{identified_params:X(r)},...o&&o.length>0&&{recently_suggested:o},...l!=null&&{contact_account_count:l},...a!==void 0&&{additional_context:a}},meta:{request_id:Un(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:Kn,session_id:i}}}async function kt(n,e,t,i,r){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:r})}async function Rt(n,e,t){let i=t.apiConfig,r=!t.maskCompletedText,o=Yn(n,e,r,t.sessionId,t.identifiedParams,t.recentlySuggested,t.skippedParams,t.additionalContext),s=le(i),a=i?.endpoint??se,d=JSON.stringify(o);if(z(i)){let u=ae(i),f=await u.getToken(),g=await kt(a,s,f,d,t.signal);if(g.status===401){let h=await u.getToken(!0);g=await kt(a,s,h,d,t.signal)}if(!g.ok)throw new Error(`API error: ${g.status} ${g.statusText}`);return g.json()}let l=de(i);!l&&!Dt&&(Dt=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),l&&(s.Authorization=l);let c=await fetch(a,{method:"POST",headers:s,body:d,signal:t.signal});if(!c.ok)throw new Error(`API error: ${c.status} ${c.statusText}`);return c.json()}function T(n,e){let t=n,i={},r=[],o=[],s=0;for(let a of e){let d=(i[a.type]??0)+1;i[a.type]=d;let c=`{{${a.type.toUpperCase().replace(/\s+/g,"_")}_${d}}}`,u=g=>{let h=t.indexOf(a.text,g);for(;h!==-1&&o.some(x=>h<x.end&&h+a.text.length>x.start);)h=t.indexOf(a.text,h+1);return h},f=u(s);if(f===-1&&(f=u(0)),f!==-1){t=t.slice(0,f)+c+t.slice(f+a.text.length);let g=c.length-a.text.length;for(let h of o)h.start>=f+a.text.length&&(h.start+=g,h.end+=g);o.push({start:f,end:f+c.length}),s=f>=s?f+c.length:s+g}r.push({...a,placeholder:c})}return{rawQuery:t,completedParams:r}}function k(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function ce(n,e,t){return e===0&&n.length>0&&t.length>0&&t.toLowerCase().startsWith(n.toLowerCase())}function F(n,e,t){let i=n.slice(e);if(t||e===0||n[e-1]===" ")return i;let r=i.indexOf(" ");return r===-1?"":i.slice(r+1)}function _t(n,e){let t=n.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let i=t.split(" "),r=e.toLowerCase();for(let o=0;o<i.length;o++){let s=i.slice(o).join(" ");if(r.startsWith(s.toLowerCase())){let a=t.length-s.length;return n.length-a}}return 0}function B(n,e){if(!n)return[];let t=e.trimStart();if(!t)return n;let i=t.toLowerCase();return n.filter(r=>!r.is_tappable||r.text.toLowerCase().includes(i))}function q(n,e){if(!n)return null;let t=e.trim();if(!t)return null;let i=t.toLowerCase();return n.find(r=>r.is_tappable&&r.text.toLowerCase()===i)??null}function Nt(n,e){return e?n.map(t=>e[t.type]?{...t,options:[]}:t):n}function Ht(n,e){let t=0,i=e;for(let r of n)t+=r.value.length,r.type!=="text"&&(i=Math.max(i,t));return i}function Ft(n,e){let t=0;for(let i of n){let r=t+i.value.length;if(i.type==="text"&&r>e&&i.value.slice(Math.max(e-t,0)).trim().length>0)return!1;t=r}return!0}function Bt(n,e){let t=[],i=new Set;for(let r of[...n,...e])r.type==="placeholder"||i.has(r.type)||(i.add(r.type),t.push({type:r.type,text:r.text}));return t}function Wt(n,e,t){if(n===e)return t;let i=Math.min(n.length,e.length),r=0;for(;r<i&&n[r]===e[r];)r++;if(r>=t)return t;let o=0;for(;o<i-r&&n[n.length-1-o]===e[e.length-1-o];)o++;return n.length-o<=t?t+(e.length-n.length):null}function $e(n,e){let t=[],i=[],r=0;for(let o of e){let s=n.indexOf(o.text,r);if(s===-1){i.push(o);continue}t.push({start:s,end:s+o.text.length,param:o}),r=s+o.text.length}return{located:t,missing:i}}function Gt(n,e,t){let i=[],r=[],o=0;for(let s of t){let a=n.indexOf(s.text,o);for(;a!==-1&&e.some(d=>a<d.end&&a+s.text.length>d.start);)a=n.indexOf(s.text,a+1);if(a===-1){r.push(s);continue}i.push({start:a,end:a+s.text.length,param:s}),o=a+s.text.length}return{located:i,missing:r}}function Vt(n,e,t=[]){let i=$e(n,e).located,r=Gt(n,i,t).located,o=[...i.map(l=>({start:l.start,end:l.end,segment:{type:"completed",value:l.param.text,param:l.param}})),...r.map(l=>({start:l.start,end:l.end,segment:{type:"identified",value:l.param.text,param:l.param}}))].sort((l,c)=>l.start-c.start),s=[],a=0;for(let l of o)l.start>a&&s.push({type:"text",value:n.slice(a,l.start)}),s.push(l.segment),a=l.end;let d=n.slice(a);return d&&s.push({type:"text",value:d}),s}function qt(n,e){let{located:t,missing:i}=$e(n,e);return{valid:t.map(r=>r.param),invalid:i}}function ue(n,e,t){let i=$e(n,e).located,{located:r,missing:o}=Gt(n,i,t);return{valid:r.map(s=>s.param),invalid:o}}function jn(n){if(n instanceof Error)return n;try{return new Error(String(n))}catch{return new Error("Unknown error")}}var zn=100,Xn=300,Jn=2,pe=class{constructor(e,t,i,r,o,s,a,d={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=r;this.getOnError=o;this.getSessionId=s;this.getAdditionalContext=a;this.callbacks=d;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null}start(){this.doFetch("",[]);let e=this.store.get().text,t=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(i=>{(i.text!==e||i.completedParams!==t)&&(e=i.text,t=i.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let i=new AbortController;this.abortController=i;let r=++this.fetchVersion,o=this.store.get().text.length;try{this.callbacks.onRequest?.({query:this.store.get().text,signal:i.signal,isCurrent:()=>r===this.fetchVersion})}catch{}try{this.store.set({isLoading:!0,error:null});let s=this.store.get(),a=s.pendingSpan?Bt(s.pendingSpan.snapshot,s.actionableSuggestions):void 0,d=await Rt(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig(),identifiedParams:s.identifiedParams,recentlySuggested:a,skippedParams:s.skippedParams,additionalContext:this.getAdditionalContext()});if(r!==this.fetchVersion)return;let l=(d.data.input??[]).filter(b=>b.source==="identified").map(b=>({id:crypto.randomUUID(),type:b.type,text:b.text})),c=Nt(d.data.suggestions??[],this.getOptionOverrides()),u=d.data.input??[],f=u[u.length-1],g=this.store.get().text,h,x;if(f?.state==="in_progress"){x=!0;let b=g.toLowerCase().lastIndexOf(f.text.toLowerCase());h=b!==-1?b:o}else x=!1,h=o;let p=c.filter(b=>b.type!=="placeholder")[0],m=null;if(p&&H(p)!=="date"){let b=F(g,h,x),y=q(p.options,b);y&&(m={id:crypto.randomUUID(),placeholder:"",type:p.type,text:y.text,kind:y.kind,suggestionType:p.type,suggestionPlaceholder:p.text,options:p.options??[],metadata:y.metadata},c=c.filter(v=>v!==p),this.callbacks.onAutoMatch?.({active:p,matched:y,rawQuery:e}))}this.store.set(b=>{let y=m?[...b.completedParams,m]:b.completedParams,v=ue(b.text,y,l).valid,C=new Set(s.skippedParams.map(P=>P.id)),_=new Set(b.skippedParams.filter(P=>!C.has(P.id)).map(P=>P.type));return{suggestions:_.size>0?c.filter(P=>P.type==="placeholder"||!_.has(P.type)):c,isLoading:!1,isReady:d.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:h,filterInProgress:x,identifiedParams:v,...m?{completedParams:y}:{}}}),this.callbacks.onResponse?.()}catch(s){let a=jn(s);r===this.fetchVersion&&(this.store.set({error:a,isLoading:!1}),this.getOnError()?.(a))}finally{if(r===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(Jn)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},zn),this.slowDebounceTimer=setTimeout(()=>this.attemptFetch(1),Xn)}attemptFetch(e,t=!1){let i=this.store.get();if(!i.text&&i.completedParams.length===0)return this.doFetch("",[]),!0;let r=this.callbacks.consumerTick?.(i,e)??"no";if(r==="asked")return!0;if(r==="owns")return!1;let o=i.suggestions.filter(y=>y.type==="placeholder").map(y=>y.text).join(" "),s=k(i.text,i.filterBase,o),a=F(i.text,s,i.filterInProgress),l=i.suggestions.filter(y=>y.type!=="placeholder")[0],c=i.activeFormatType==="date",f=(l&&!c?B(l.options,a):[]).filter(y=>y.is_tappable),g=l&&!c?q(l.options,a)!==null:!1,h=a.trim().length>0;if(f.length>0&&!g&&h||ce(i.text,i.completedParams.length,o))return!1;let{rawQuery:x,completedParams:S}=T(i.text,i.completedParams),p=x.length<i.lastRawQuery.length,m=Math.abs(x.length-i.lastRawQuery.length),b=t&&x!==i.lastRawQuery;return p||m>=e||b?(this.doFetch(x,S),!0):!1}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};function Zn(n){return n.nodeType===Node.DOCUMENT_NODE?!0:n.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in n}function me(n){let e=typeof n.getRootNode=="function"?n.getRootNode():null;return e&&Zn(e)?e:n.ownerDocument??n}function A(n){return n.ownerDocument??n}function M(n){let t=me(n).getSelection?.();return t||(A(n).getSelection?.()??null)}function fe(n,e){let t=n?me(n):typeof document<"u"?document:null;return t?typeof t.getElementById=="function"?t.getElementById(e):typeof document<"u"?document.getElementById(e):null:null}var ge=2,ei="magicx-aia";function $t(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 i=n;for(;i&&i!==e.body&&i!==e.documentElement;){let r=i.scrollWidth>i.clientWidth,o=i.scrollHeight>i.clientHeight;if(r||o){let s=t.getComputedStyle(i);if(r&&$t(s.overflowX)||o&&$t(s.overflowY))return i}if(i.classList.contains(ei))return null;i=i.parentElement}return null}function Ke(n){let e=M(n);if(!e||e.rangeCount===0)return;let t=e.getRangeAt(0);if(!t.collapsed||!n.contains(t.startContainer))return;let i=ti(n);if(!i||typeof t.getBoundingClientRect!="function")return;let r=t.getBoundingClientRect();if(r.height===0)return;let o=i.getBoundingClientRect();if(i.scrollWidth>i.clientWidth){let s=o.left+i.clientLeft,a=s+i.clientWidth;r.right>a?i.scrollLeft+=r.right-a+ge:r.left<s&&(i.scrollLeft-=s-r.left+ge)}if(i.scrollHeight>i.clientHeight){let s=o.top+i.clientTop,a=s+i.clientHeight;r.bottom>a?i.scrollTop+=r.bottom-a+ge:r.top<s&&(i.scrollTop-=s-r.top+ge)}}var Qt='[contenteditable="false"]',ni="strong[data-param-id]",$;function ii(){if($!==void 0)return $;let n=globalThis.Intl.Segmenter;if(!n)return $=null,null;try{$=new n(void 0,{granularity:"grapheme"})}catch{$=null}return $??null}function he(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(Qt))return!0;t=t.parentNode}return!1}function be(n){return A(n).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return he(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function ye(n){let e=be(n),t="",i=e.nextNode();for(;i;)t+=i.data,i=e.nextNode();return t}function Ue(n){let e=be(n),t=0,i=e.nextNode();for(;i;)t+=i.data.length,i=e.nextNode();return t}function L(n){let e=M(n);if(!e||e.rangeCount===0)return null;let t=e.anchorNode,i=e.anchorOffset;if(!t||!n.contains(t))return null;if(t.nodeType===Node.ELEMENT_NODE){let r=t;if(he(r,n)&&r!==n)return null;let o=0;for(let s=0;s<i&&s<r.childNodes.length;s++)o+=Yt(r.childNodes[s],n);return o+Kt(r,n)}return t.nodeType!==Node.TEXT_NODE||he(t,n)?null:Kt(t,n)+i}function Yt(n,e){if(n.nodeType===Node.TEXT_NODE)return he(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(Qt))return 0;let i=0;for(let r of Array.from(t.childNodes))i+=Yt(r,e);return i}function Kt(n,e){let t=be(e),i=0,r=t.nextNode();for(;r;){if(r===n||n.nodeType===Node.ELEMENT_NODE&&n.contains(r))return i;i+=r.data.length,r=t.nextNode()}return i}function O(n,e){let t=A(n),i=M(n);if(!i)return;let r=Math.max(0,Math.min(e,Ue(n))),o=be(n),s=0,a=null,d=0,l=o.nextNode(),c=null;for(;l;){let f=l.data.length;if(r<s+f){a=l,d=r-s;break}if(r===s+f){let g=o.nextNode();g?(a=g,d=0):(a=l,d=f);break}s+=f,c=l,l=o.nextNode()}let u=t.createRange();if(a){let f=a.parentElement?.closest('strong[data-seg="completed"]');f&&f!==n&&n.contains(f)?d===0?u.setStartBefore(f):d===a.data.length?u.setStartAfter(f):u.setStart(a,d):u.setStart(a,d)}else c?u.setStart(c,c.data.length):u.setStart(n,0);u.collapse(!0),i.removeAllRanges(),i.addRange(u),ri(n,i,u,r),Ke(n)}function Ut(n,e){if(!n||!e.contains(n))return null;let i=(n.nodeType===Node.ELEMENT_NODE?n:n.parentElement)?.closest(ni)??null;return i&&e.contains(i)?i:null}function ri(n,e,t,i){let r=Ut(e.anchorNode,n);if(r&&r!==Ut(t.startContainer,n)){n.dataset.aiaCaretEscapedChip=`${i}:${r.dataset.paramId}`;return}delete n.dataset.aiaCaretEscapedChip}function jt(n,e){let t=n.dataset.aiaCaretEscapedChip;if(!t)return!1;let i=L(n);return i!==null&&t===`${i}:${e}`}function Qe(n){let e=L(n);return e==null?!1:e>=Ue(n)}function Ye(n,e){if(e<=0)return 0;let t=ii();if(!t)return e-1;let i=n.slice(0,e),r=0;for(let{index:o}of t.segment(i))o<e&&(r=o);return r}function W(n,e,t=[],i={}){let{rawQuery:r,completedParams:o}=T(n,e);return{query:n.trim(),raw_query:r,completed_params:J(o,t),identified_params:X(i.identifiedParams??[]),is_ready:i.isReady??!1}}function je(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 ze(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?L(n):null}var xe=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:r}=this.ctx,o=e.target instanceof Node?e.target:null,s=this.getEffectiveColumns(o),a=r(),d=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 l=this.ctx.getOptionsPosition()==="above";switch(e.key){case"ArrowDown":{let c=je(e.target,t),u=!!t.editingParam;if(!c&&!u&&t.activeDropdownIndex<0)break;if(t.activeDropdownIndex<0){if(l)break;e.preventDefault();let h=t.activeFormatType==="date"?this.dateEntryIndex(t,!1):d[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:h});break}if(d.length===0)return;this.store.set({activeDropdownIndex:h});break}if(e.preventDefault(),d.length===0)return;if(t.activeFormatType==="date"){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 f=d.indexOf(t.activeDropdownIndex),g=f<d.length-1?f+1:0;this.store.set({activeDropdownIndex:d[g]});break}case"ArrowUp":{if(t.activeDropdownIndex<0){if(!l)break;let f=je(e.target,t),g=!!t.editingParam;if(!f&&!g)break;e.preventDefault();let h=t.activeFormatType==="date"?this.dateEntryIndex(t,!0):this.firstTappableInBottomRow(s)??d[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:h});break}if(d.length===0)return;this.store.set({activeDropdownIndex:h});break}if(d.length===0)break;if(e.preventDefault(),t.activeFormatType==="date"){this.stepDateWeek(t,-7);break}if(t.activeDropdownIndex<s){this.store.set({activeDropdownIndex:-1});break}let c=d.indexOf(t.activeDropdownIndex),u=c>0?c-1:d.length-1;this.store.set({activeDropdownIndex:d[u]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeFormatType==="date"){this.stepDateDay(t,1);break}if(t.activeDropdownIndex%s<s-1){let f=t.activeDropdownIndex+1;f<t.filteredOptions.length&&t.filteredOptions[f]?.is_tappable&&this.store.set({activeDropdownIndex:f})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let u=e.target.closest("[data-aia-input]")??e.target,f=t.editingTail;this.ctx.exitEditMode?.(),O(u,f);break}je(e.target,t)&&t.actionableSuggestions.length>=1&&(e.preventDefault(),this.ctx.skipActivePill());break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeFormatType==="date"){this.stepDateDay(t,-1);break}if(t.activeDropdownIndex%s>0){let c=t.activeDropdownIndex-1;c>=0&&t.filteredOptions[c]?.is_tappable&&this.store.set({activeDropdownIndex:c});break}if(!t.editingParam&&this.ctx.startEditingParamAtCaret){let c=ze(e.target);c!=null&&this.ctx.startEditingParamAtCaret(c)}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let c=e.target.closest("[data-aia-input]")??e.target,u=t.editingAnchor;this.ctx.exitEditMode?.(),O(c,u);break}if(this.ctx.startEditingParamAtCaret){let c=ze(e.target);c!=null&&this.ctx.startEditingParamAtCaret(c)&&e.preventDefault()}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let c=ze(e.target);if(c==null)break;this.ctx.removeParamAtCaret(c)&&e.preventDefault();break}case"Enter":{e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable?this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i,o):a&&a(W(t.text,t.completedParams,t.skippedParams,{identifiedParams:t.identifiedParams,isReady:t.isReady}))&&this.ctx.afterSubmit?.();break}case"Tab":{let c=t.filteredOptions.map((g,h)=>g.is_tappable?h:-1).filter(g=>g!==-1);if(c.length===0)break;if(!t.isDropdownOpen){if(t.actionableSuggestions.length===0)break;e.preventDefault();let g=e.shiftKey?c[c.length-1]:c[0];this.store.set({pillTapped:!0,activeDropdownIndex:g});break}e.preventDefault();let u=c.indexOf(t.activeDropdownIndex),f;if(u<0)f=e.shiftKey?c.length-1:0;else{let g=e.shiftKey?-1:1;f=(u+g+c.length)%c.length}this.store.set({activeDropdownIndex:c[f]});break}case"Escape":{if(t.editingIdentified){this.ctx.exitEditingIdentified?.(),this.store.set({activeDropdownIndex:-1});break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){let c=e.target.closest("[data-aia-input]")??e.target,u=t.editingTail;this.ctx.exitEditMode?.(),O(c,u)}this.store.set({activeDropdownIndex:-1});break}}}firstTappableInBottomRow(e){let t=this.store.get();if(t.filteredOptions.length===0)return null;let r=Math.floor((t.filteredOptions.length-1)/e)*e;for(let o=r;o<t.filteredOptions.length;o++)if(t.filteredOptions[o]?.is_tappable)return o;return null}dateEntryIndex(e,t){let i=I(new Date),r=e.filteredOptions.findIndex(s=>V(s)===i);if(r>=0)return r;let o=e.filteredOptions.map((s,a)=>s.is_tappable?a:-1).filter(s=>s!==-1);return(t?o[o.length-1]:o[0])??0}stepDateDay(e,t){for(let i=e.activeDropdownIndex+t;i>=0&&i<e.filteredOptions.length;i+=t)if(e.filteredOptions[i]?.is_tappable){this.store.set({activeDropdownIndex:i});return}}stepDateWeek(e,t){let i=e.activeDropdownIndex+t;this.store.set({activeDropdownIndex:e.filteredOptions[i]?.is_tappable?i:-1})}getTappableIndices(e){let i=this.store.get().filteredOptions.map((o,s)=>o.is_tappable?s:-1).filter(o=>o!==-1),r=Array.from({length:e},()=>[]);for(let o of i)r[o%e].push(o);return r.flat()}getEffectiveColumns(e){let t=fe(e,this.ctx.listboxId);if(!t)return this.ctx.columns;let r=fe(e,`${this.ctx.listboxId}-option-0`)?.parentElement??null;for(;r;){let o=getComputedStyle(r).gridTemplateColumns;if(o&&o!=="none"){let s=o.split(" ").filter(Boolean).length;if(s>0)return s}if(r===t)break;r=r.parentElement}return this.ctx.columns}clickOrSelect(e,t,i,r){let o=fe(r,`${i}-option-${e}`);o?o.click():this.ctx.selectOption(t[e])}};var Se=class{constructor(e,t,i={}){this.store=e;this.getOverrides=t;this.callbacks=i;this.unsubscribe=null;this.current=null;this.version=0;this.lastMiss=null;this.hasLoggedError=!1}start(){this.unsubscribe=this.store.subscribe(e=>this.sync(e)),this.sync(this.store.get())}dispose(){this.unsubscribe?.(),this.unsubscribe=null,this.cancel(),this.current=null}reset(){this.cancel(),this.current=null,this.lastMiss=null}refresh(){this.reset(),this.sync(this.store.get())}hasOverride(e){return!!this.getOverrides()?.[e]}owns(e,t){return this.hasOverride(e)&&!this.missCovers(e,t)}tick(e,t){let i=this.resolveTarget(e);if(!i||this.missCovers(i.type,i.query))return"no";let r=this.current;if(r&&r.key===i.key){if(r.query===i.query)return"owns";let o=Math.abs(i.query.length-r.query.length),s=i.query.length<r.query.length;if(t>1&&!s&&o<t)return"owns"}return this.ask(i),"asked"}sync(e){let t=this.resolveTarget(e);if(!t){this.current&&(this.cancel(),this.current=null),e.optionSearch&&this.store.set({optionSearch:null});return}this.current&&this.current.key===t.key||this.ask(t)}resolveTarget(e){if(e.activeFormatType==="date"||e.editingIdentified)return null;let t=e.editingParam;if(t&&e.editingAnchor!=null)return this.hasOverride(t.suggestionType)?{mode:"edit",key:t.id,type:t.suggestionType,suggestion:{type:t.suggestionType,text:t.suggestionPlaceholder,required:!0,options:t.options},query:e.optionQuery}:null;let i=e.actionableSuggestions[0];return!i||!this.hasOverride(i.type)?null:{mode:"pill",key:i,type:i.type,suggestion:i,query:e.optionQuery}}missCovers(e,t){return this.lastMiss!=null&&this.lastMiss.type===e&&this.lastMiss.query===t}ask(e){this.cancel();let t=this.getOverrides()?.[e.type],i=++this.version;if(!t||this.missCovers(e.type,e.query)){this.current={key:e.key,type:e.type,query:e.query,abort:null},this.setSearch(e,"done");return}let r=new AbortController;this.current={key:e.key,type:e.type,query:e.query,abort:r};let o;try{o=t(e.query,r.signal,e.suggestion)}catch(s){this.logOnce(s),this.commit(e,[],i);return}if(Array.isArray(o)){this.commit(e,o,i);return}this.setSearch(e,"loading"),this.await(e,o,r.signal,i)}async await(e,t,i,r){let o;try{let s=await t;if(i.aborted||r!==this.version)return;o=Array.isArray(s)?s:[]}catch(s){if(i.aborted||r!==this.version||oi(s))return;this.logOnce(s),o=[]}this.commit(e,o,r)}commit(e,t,i){if(i!==this.version)return;let r=this.resolveTarget(this.store.get());if(!r||r.key!==e.key)return;t.length===0?this.lastMiss={type:e.type,query:e.query}:this.lastMiss?.type===e.type&&(this.lastMiss=null);let o={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:o}));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(d=>d===e.suggestion?s:d),optionSearch:o}))}t.length===0?this.callbacks.onMiss?.(e.mode,e.query):this.callbacks.onAnswer?.(e.mode,e.query)}setSearch(e,t){let i=this.store.get().optionSearch;i&&i.type===e.type&&i.query===e.query&&i.status===t||this.store.set({optionSearch:{type:e.type,query:e.query,status:t}})}cancel(){this.current?.abort?.abort(),this.version++}logOnce(e){this.hasLoggedError||(this.hasLoggedError=!0,console.warn("[AIAutocomplete] an optionOverrides entry threw or rejected \u2014 treated as no options. Later failures on this instance are not logged.",e))}};function oi(n){return n instanceof Error&&n.name==="AbortError"}var ve=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),i=t.suggestions.filter(l=>l.type!=="placeholder");if(e<0||e>=i.length)return;let r=i[e],o=i.filter((l,c)=>c!==e),s=t.suggestions.filter(l=>l.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:l}=T(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:l,selectedPill:r.text,otherPills:o.map(c=>c.text)})}let a=[...s,r,...o],d=this.store.peek({suggestions:a}).filteredOptions.findIndex(l=>l.is_tappable);this.store.set({suggestions:a,pillTapped:!0,activeDropdownIndex:d})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};var Pe=class{constructor(e,t){this.store=e;this.getConfig=t;this.hasLoggedError=!1}async run(e,t,i){let r=this.getConfig();if(r){if(e.trim().length===0){this.clear(i);return}try{let o=await r.fetch(e,t);if(t.aborted||!i())return;let s=r.transform(o),a=Array.isArray(s)?s:[],d=r.limit!=null?a.slice(0,r.limit):a;if(t.aborted||!i())return;this.commit(d)}catch(o){if(t.aborted||si(o))return;this.logOnce(o),this.clear(i)}}}clearNow(){this.commit([])}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 si(n){return n instanceof Error&&n.name==="AbortError"}var Ee="(max-width: 768px)";var ai="var(--aia-option-row-height, 37px)",li="var(--aia-grid-scroll-top, 0px) + var(--aia-grid-scroll-bottom, 0px)";function zt(n,e){return e?Xe(1,Math.min(n,5)):Xe(1,Math.min(n,4))}function Xe(n,e){return{cols:n,rows:e,maxHeight:`calc(${e} * ${ai} + ${li})`}}function Je(n,e){return!e&&n>=5}function Ze(n,e,t,i){if(!(!e&&n>=5&&di(t,i))){let a=zt(n,e);return{...a,template:Jt(a.cols),scrollHintIndices:!e&&n>a.rows?[a.rows-1]:[]}}let[o]=Xt(t),s=6;return{...Xe(2,3),template:`${o}px minmax(0,1fr)`,scrollHintIndices:n>s?[s-2,s-1]:[]}}function Xt(n){let e=0,t=0;return n.forEach((i,r)=>{r%2===0?e=Math.max(e,i):t=Math.max(t,i)}),[Math.ceil(e),Math.ceil(t)]}function di(n,e){if(!n||n.length===0||e==null||e<=0||n.some(r=>r<=0))return!1;let[t,i]=Xt(n);return t+i<=e}function et(n){if(typeof document>"u")return null;let e=Array.from(n.querySelectorAll("[data-aia-option]"));if(e.length===0)return null;let t=document.createElement("div");t.style.cssText="position:absolute;visibility:hidden;left:-9999px;top:0;";for(let s of e){let a=s.cloneNode(!0);a.removeAttribute("id"),a.removeAttribute("role"),a.removeAttribute("aria-selected"),a.style.whiteSpace="nowrap",a.style.width="max-content",t.appendChild(a)}n.appendChild(t);let i=Array.from(t.children).map(s=>s.offsetWidth);t.remove();let r=getComputedStyle(n),o=n.clientWidth-(Number.parseFloat(r.paddingLeft)||0)-(Number.parseFloat(r.paddingRight)||0)-(Number.parseFloat(r.columnGap)||0);return{rowWidths:i,gridWidth:o}}function Jt(n){return Array.from({length:n},()=>"minmax(0,1fr)").join(" ")}function tt(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(Ee).matches}function Zt(n,e){let t=e.dropdownTrigger??"auto",i=e.closeDropdownOnBlur??!0,s=n.filteredOptionsLength>0||n.activePillHasNoOptions||n.hasProducts;if(n.inEditMode){let a=i?n.isFocused:!0;return s&&a}if(t==="auto"){let a=i?n.isFocused:!0,d=n.text.replace(/\s+$/,"").length,l=n.caretOffset==null||n.caretOffset>=d;return(s||n.isLoading)&&a&&l}return t==="manual"?(s||n.isLoading)&&n.pillTapped:!1}function nt(n){if(n.editingIdentified){let{type:t,anchor:i}=n.editingIdentified;return`identified:${t}@${i}`}return n.editingParam!=null&&n.editingAnchor!=null?`edit:${n.editingParam?.id}`:`pill:${n.actionableSuggestions[0]?.type??""}`}function ci(n){if(!n)return Be();let[e,t]=n.split("-").map(Number);return{year:e,month:t-1}}function ui(n){let e=ne(n);return e?Ct(e):Be()}function en(n,e){let t=Vt(n.text,n.completedParams,n.identifiedParams),i=n.suggestions.filter(E=>E.type!=="placeholder"),r=i[0],o=n.suggestions.filter(E=>E.type==="placeholder").map(E=>E.text).join(" "),s=k(n.text,Math.min(n.filterBase,n.text.length),o),d=s===0&&ce(n.text,n.completedParams.length,o)?"":F(n.text,s,n.filterInProgress),l=r?.options??[],c=n.editingParam!=null&&n.editingAnchor!=null,u,f,g,h;if(c&&n.editingParam&&n.editingAnchor!=null){let E=n.editingParam.id,w=n.completedParams.some(Hn=>Hn.id===E),Y=n.caretOffset??n.editingAnchor,xt=w?"":n.text.slice(n.editingAnchor,Y);f=xt.trim(),g=n.editingParam.options,h=n.editingParam.suggestionType,u=B(n.editingParam.options,xt)}else f=d.trim(),g=l,h=r?.type,u=B(l,d);let x=n.optionSearch,S=x!=null&&h!=null&&x.type===h;S&&x.status==="done"&&x.query===f&&(u=g);let p=S&&x.status==="loading",m=e.showNonTappableOptions===!1;m&&(u=u.filter(E=>E.is_tappable));let b=n.editingIdentified,y=b?{type:b.type}:c?n.editingParam&&{type:n.editingParam.suggestionType,options:n.editingParam.options}:r,v=H(y),C=null;if(v==="date"){let E=nt({...n,actionableSuggestions:i}),w=n.dateViewMonth;C=w&&w.key===E?{year:w.year,month:w.month}:b?ci(b.iso):ui(n.editingParam?.text),u=Ge(C)}let _=E=>m?E.is_tappable:!0,D;if(c){let E=n.editingParam?.options??[];D=n.editingParam!=null&&E.filter(_).length===0}else D=r!=null&&l.filter(_).length===0;let P=Zt({inEditMode:c||b!=null,filteredOptionsLength:u.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading||p,pillTapped:n.pillTapped,activePillHasNoOptions:D,hasProducts:n.products.length>0},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),Q=P&&n.activeDropdownIndex>=0&&!!u[n.activeDropdownIndex]?.is_tappable;return{segments:t,actionableSuggestions:i,filteredOptions:u,activeFormatType:v,dateView:C,placeholderText:o,optionQuery:f,isSearchingOptions:p,isDropdownOpen:P,isActivePillSelected:Q}}function we(n){return n.mode==="fresh"?pi(n):mi(n)}function pi(n){let{text:e,completedParams:t,suggestions:i,filterBase:r,filterInProgress:o}=n,a=i.filter(y=>y.type!=="placeholder")[0];if(!a?.options)return null;let d=i.filter(y=>y.type==="placeholder").map(y=>y.text).join(" "),l=k(e,r,d),c=F(e,l,o),u=q(a.options,c);if(!u)return null;let f=u.text.toLowerCase(),g=e.toLowerCase().lastIndexOf(f),h=g>=0?g:Math.max(0,e.length-u.text.length),x=h+u.text.length,S=e.slice(h,x),m=x<e.length&&e[x]===" "?x+1:x,b={id:crypto.randomUUID(),placeholder:"",type:a.type,text:S,kind:u.kind,suggestionType:a.type,suggestionPlaceholder:a.text,options:a.options??[],metadata:u.metadata};return{patch:{text:e,completedParams:[...t,b],suggestions:i.filter(y=>y!==a),filterBase:m,newParamId:b.id,caretOffset:m,activeDropdownIndex:-1},caretPos:m}}function mi(n){let{text:e,completedParams:t,editingParam:i,editingAnchor:r,editingTail:o}=n;if(t.some(b=>b.id===i.id))return null;let s=e.slice(r,o),a=q(i.options,s);if(!a)return null;let d=a.text.toLowerCase(),l=s.toLowerCase().lastIndexOf(d),c=r+Math.max(0,l),u=c+a.text.length,f=e.slice(c,u),g=u<e.length&&e[u]===" "?u+1:u,h=e.length,x={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:f,kind:a.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:a.metadata},S=t.length,p=0;for(let b=0;b<t.length;b++){let y=e.indexOf(t[b].text,p);if(y!==-1){if(y>=g){S=b;break}p=y+t[b].text.length}}let m=[...t];return m.splice(S,0,x),{patch:{text:e,completedParams:m,newParamId:x.id,filterBase:h,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:h,activeDropdownIndex:-1},caretPos:h}}function Te(n,e,t){let i=n.slice(0,e),r=n.slice(t),o=(i===""||i.endsWith(" "))&&r.startsWith(" ");return o&&(r=r.slice(1)),{text:i+r,removed:t-e+(o?1:0)}}var Ce=class{constructor(e){this.deps=e}start(e){let t=this.deps.store.get();if(t.editingParam?.id===e)return;let i=t.completedParams.find(s=>s.id===e);if(!i)return;let r=0,o=-1;for(let s of t.completedParams){let a=t.text.indexOf(s.text,r);if(a!==-1){if(s.id===e){o=a;break}r=a+s.text.length}}o<0||this.deps.store.set({editingParam:i,editingAnchor:o,editingTail:o+i.text.length,caretOffset:o+i.text.length,activeDropdownIndex:-1,editingIdentified:null})}exit(){this.deps.store.get().editingParam&&this.deps.store.set({editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1})}replaceRange(e){let t=this.deps.store.get(),i=t.editingParam,r=t.editingAnchor,o=t.editingTail;if(!i||r==null||o==null||!t.completedParams.some(d=>d.id===i.id))return!1;let{text:s}=e===""?Te(t.text,r,o):{text:t.text.slice(0,r)+e+t.text.slice(o)},a=r+e.length;return this.deps.store.set(d=>({text:s,completedParams:d.completedParams.filter(l=>l.id!==i.id),editingTail:a,caretOffset:a,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(a),this.promoteIfExact(),!0}caretAfterInput(e){let t=this.deps.store.get(),i={caretOffset:e};t.editingParam&&t.editingAnchor!=null&&e!=null&&(e<t.editingAnchor?(i.editingParam=null,i.editingAnchor=null,i.editingTail=null,i.activeDropdownIndex=-1):t.editingTail!=null&&(i.editingTail=Math.max(t.editingTail,e))),this.deps.store.set(i),this.promoteIfExact()}caretMove(e){let t=this.deps.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null&&e!=null&&(e<t.editingAnchor||e>t.editingTail)){this.deps.store.set({caretOffset:e,editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1});return}this.deps.store.set({caretOffset:e})}selectOption(e){let t=this.deps.store.get(),i=t.editingParam,r=t.editingAnchor,o=t.editingTail;if(!i||r==null||o==null)return;this.deps.fireTelemetry("option",{raw_query:T(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:i.options.filter(p=>p.text!==e.text).map(p=>p.text)});let s=t.text.slice(0,r),a=t.text.slice(o),d=r===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,c=a.length===0||a[0]!==" "?`${d} `:d,u=s+c+a,f=u.length,g={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:d,kind:e.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:e.metadata},h=t.completedParams.findIndex(p=>p.id===i.id),x=t.completedParams.filter(p=>p.id!==i.id),S=h>=0?Math.min(h,x.length):x.length;x.splice(S,0,g),this.deps.store.set({text:u,completedParams:x,newParamId:g.id,filterBase:f,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:f,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.deps.startSelectionAnimationTimer(),this.deps.scheduleSetCursor(f),this.deps.fetchNow()}promoteIfExact(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let t=we({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 fi=33,gi=70,hi=120,bi=50,K="data-aia-placeholder-leaving",U=new WeakMap;function Ae(n){n.timer!==null&&(clearTimeout(n.timer),n.timer=null)}function yi(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function nn(n,e,t){e.shown=t,n.dataset.placeholder=e.target.slice(0,t)}function rn(n,e){if(e.timer=null,!n.isConnected||e.shown>=e.target.length||(nn(n,e,e.shown+1),e.shown>=e.target.length))return;let t=e.target[e.shown-1],i=t===" "||t==="-"?70:0;e.timer=setTimeout(()=>rn(n,e),33+i)}function tn(n,e){nn(n,e,0),e.timer=setTimeout(()=>rn(n,e),33)}function on(n,e){let t=U.get(n);if(e===""){t&&(Ae(t),U.delete(n)),n.removeAttribute(K),delete n.dataset.placeholder;return}if(t?.target===e)return;if(yi(n)){t&&Ae(t),n.removeAttribute(K),U.set(n,{target:e,shown:e.length,timer:null}),n.dataset.placeholder=e;return}let i={target:e,shown:0,timer:null},r=t&&t.shown>0?t:null;if(t&&Ae(t),U.set(n,i),r){n.setAttribute(K,""),i.timer=setTimeout(()=>{i.timer=null,n.removeAttribute(K),n.isConnected&&tn(n,i)},170);return}n.removeAttribute(K),tn(n,i)}function sn(n){let e=U.get(n);e&&(Ae(e),U.delete(n))}var an="https://ai-autocomplete.com";function it(n=an){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 rt(n,e){return n?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}var ln="data-aia-key";function R(n,e,t){let i=new Map;for(let s of Array.from(n.children)){let a=s.getAttribute(ln);a!=null&&i.set(a,s)}let r=new Set,o=[];for(let s=0;s<e.length;s++){let a=e[s],d=t.keyOf(a,s);r.add(d);let l=i.get(d);l||(l=t.create(a,s),l.setAttribute(ln,d)),t.update?.(l,a,s),n.children[s]!==l&&n.insertBefore(l,n.children[s]??null),o.push(l)}for(let[s,a]of i)r.has(s)||a.remove();return o}function cn(n,e,t,i,r,o,s){let a=n.querySelector(".magicx-aia-datepicker");if(!r||e.length===0){a?.remove();return}a||(a=vi(),n.appendChild(a));let d=a.querySelector(".magicx-aia-datepicker-month");d&&(d.textContent=Fe(r));let l=a.querySelector("[data-aia-date-prev]"),c=a.querySelector("[data-aia-date-next]");l&&(l.onclick=()=>s.onPreviousMonth()),c&&(c.onclick=()=>s.onNextMonth());let u=a.querySelector(".magicx-aia-datepicker-grid");u&&xi(u,e,t,i,o,s)}function xi(n,e,t,i,r,o){let s=I(new Date);R(n,e,{keyOf:(a,d)=>V(a)??`pad-${d}`,create:a=>Si(a),update:(a,d,l)=>{let c=V(d),u=l===t&&d.is_tappable;a.id=`${i}-option-${l}`,a.dataset.aiaIndex=String(l),a.setAttribute("aria-selected",String(u)),a.classList.toggle("magicx-aia-date-cell--past",c!=null&&c<s),a.classList.toggle("magicx-aia-date-cell--highlighted",u),a.classList.toggle("magicx-aia-date-cell--today",c!=null&&c===s),a.classList.toggle("magicx-aia-date-cell--selected",c!=null&&r!=null&&c===r),d.is_tappable?(a.onclick=()=>{a.classList.add("magicx-aia-date-cell--pressed"),o.onSelect(d),setTimeout(()=>a.classList.remove("magicx-aia-date-cell--pressed"),170)},a.onmouseenter=()=>{let f=Number.parseInt(a.dataset.aiaIndex??"-1",10);f>=0&&o.onHighlight(f)}):(a.onclick=null,a.onmouseenter=null)}})}function Si(n){let e=document.createElement("div");e.setAttribute("role","option"),e.setAttribute("data-aia-option",""),e.setAttribute("data-aia-date-cell","");let t=Ve(n);if(t==null)return e.className="magicx-aia-date-cell magicx-aia-date-cell--blank",e.setAttribute("aria-hidden","true"),e.tabIndex=-1,e;e.className="magicx-aia-date-cell magicx-aia-date-cell--day",e.tabIndex=0,e.setAttribute("aria-label",n.text);let i=document.createElement("span");return i.className="magicx-aia-date-cell-number",i.textContent=String(t),e.appendChild(i),e}function vi(){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(dn("prev","Previous month","\u2039"),t,dn("next","Next month","\u203A"));let i=document.createElement("div");i.className="magicx-aia-datepicker-weekdays",i.setAttribute("aria-hidden","true");for(let o of te){let s=document.createElement("span");s.className="magicx-aia-datepicker-weekday",s.textContent=o,i.appendChild(s)}let r=document.createElement("div");return r.className="magicx-aia-datepicker-grid",r.setAttribute("data-aia-date-grid",""),n.append(e,i,r),n}function dn(n,e,t){let i=document.createElement("button");return i.type="button",i.tabIndex=-1,i.className="magicx-aia-datepicker-nav",i.setAttribute(`data-aia-date-${n}`,""),i.setAttribute("aria-label",e),i.textContent=t,i.addEventListener("mousedown",r=>r.preventDefault()),i}var un=[125,69];function pn(n,e){return e?1:n===0?.7:n===1?.4:.2}function Oe(n,e,t,i,r=!1,o=!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)),o&&e.length===0){a.setAttribute("data-aia-pill-list-loading",""),a.innerHTML="";for(let d=0;d<un.length;d++){let l=un[d],c=document.createElement("span");c.setAttribute("data-aia-pill-skeleton",""),c.className=`magicx-aia-pill magicx-aia-pill--skeleton${r?" magicx-aia-pill--rounded":""}`,c.style.width=`${l}px`,c.style.opacity=String(pn(d,!1)),a.appendChild(c)}return}o?a.setAttribute("data-aia-pill-list-loading",""):a.removeAttribute("data-aia-pill-list-loading");for(let d of a.querySelectorAll("[data-aia-pill-skeleton]"))d.remove();R(a,e,{keyOf:d=>`${d.type}-${d.text}`,create:d=>{let l=document.createElement("button");return l.type="button",l.tabIndex=-1,l.setAttribute("data-aia-pill",""),l.setAttribute("contenteditable","false"),l.textContent=d.text,l.addEventListener("mousedown",c=>c.preventDefault()),l},update:(d,l,c)=>{let u=d,f=s&&c===t&&!o,g=["magicx-aia-pill"];r&&g.push("magicx-aia-pill--rounded"),o&&g.push("magicx-aia-pill--skeleton"),u.className=g.join(" "),u.style.width="",u.style.opacity=String(pn(c,f)),o?(u.setAttribute("data-aia-loading",""),u.disabled=!0,u.onclick=null):(u.removeAttribute("data-aia-loading"),u.disabled=!1,u.onclick=()=>i(c))}})}function ot(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var Pi="Products";function mn(n,e,t,i,r){let o=n.querySelector(".magicx-aia-products");if(e.length===0){o?.remove();return}if(!o){o=document.createElement("section"),o.className="magicx-aia-products",o.setAttribute("data-aia-products",""),o.setAttribute("role","group"),o.setAttribute("aria-labelledby",`${t}-products-label`);let a=document.createElement("div");a.className="magicx-aia-products-label",a.id=`${t}-products-label`,a.textContent=Pi;let d=document.createElement("div");d.className="magicx-aia-products-row",d.setAttribute("data-aia-products-row",""),o.append(a,d),n.appendChild(o)}let s=o.querySelector(".magicx-aia-products-row");s&&R(s,e,{keyOf:a=>Ei(a),create:a=>wi(a,i,r),update:(a,d,l)=>{a.id=`${t}-product-${l}`,a.dataset.aiaIndex=String(l)}})}function st(n,e){let t=n.querySelectorAll("[data-aia-product]");for(let i of t)i.tabIndex=e?0:-1}function Ei(n){return[n.id,n.title,n.url,n.imageUrl,n.price,n.vendor].map(e=>e??"").join("\0")}function wi(n,e,t){let i=document.createElement("a");i.className="magicx-aia-product",i.setAttribute("data-aia-product",""),i.setAttribute("role","option"),i.setAttribute("aria-selected","false"),i.href=n.url,i.tabIndex=0;let r=document.createElement("span");if(r.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",r.appendChild(a)}else r.setAttribute("data-aia-product-placeholder","");i.appendChild(r);let o=document.createElement("span");if(o.className="magicx-aia-product-body",n.vendor){let a=document.createElement("span");a.className="magicx-aia-product-vendor",a.textContent=n.vendor,o.appendChild(a)}let s=document.createElement("span");if(s.className="magicx-aia-product-title",s.textContent=n.title,o.appendChild(s),n.price){let a=document.createElement("span");a.className="magicx-aia-product-price",a.textContent=n.price,o.appendChild(a)}return i.appendChild(o),i.addEventListener("click",a=>{a.metaKey||a.ctrlKey||a.shiftKey||a.altKey||a.button!==0||(a.preventDefault(),e(n))}),i.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),e(n))}),i.addEventListener("focus",()=>t(!0)),i.addEventListener("blur",a=>{a.relatedTarget?.closest("[data-aia-dropdown]")||t(!1)}),i}var Ti=80,Ci=150,Ai=280,Oi=16,at="--aia-option-enter-delay";function lt(n,e,t,i="below"){let r=Math.max(1,Math.floor(e)),o=Math.floor(Math.max(0,n)/r);if(i!=="above")return o*80;let s=Math.max(1,Math.ceil(Math.max(0,t)/r));return Math.max(0,s-1-o)*80}function dt(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 Ii(n,e,t){let i=tt(),r=!t&&Je(e,i)?et(n):null,o=Ze(e,i,r?.rowWidths??null,r?.gridWidth??null);return n.style.gridTemplateColumns=o.template,n.style.setProperty("--aia-grid-max-height",o.maxHeight),n.querySelectorAll("[data-aia-option]").forEach((s,a)=>{s.classList.toggle("magicx-aia-option--scroll-hint",!t&&o.scrollHintIndices.includes(a))}),o.cols}function fn(n,e,t,i,r,o,s,a="",d="below"){let l=n.querySelector(".aia-grid");if(e.length===0){l?.remove();return}l||(l=document.createElement("div"),l.className="aia-grid magicx-aia-grid",l.setAttribute("data-scroll",""),l.style.setProperty("--aia-grid-min","250px"),l.style.setProperty("--aia-grid-max","1fr"),l.style.setProperty("--aia-grid-gap","0"),n.appendChild(l));let c=l.dataset.aiaGroup!==a;l.dataset.aiaGroup=a,Mi(l,e,t,i,r,o,s);let u=Ii(l,e.length,s);Li(l,e.length,u,s,d),c&&(l.scrollTop=0)}function Mi(n,e,t,i,r,o,s){let a=s?"1":"0",d=n.dataset.aiaGroup??"";R(n,e,{keyOf:l=>`${l.text}\0${a}\0${d}`,create:(l,c)=>{let u=Di(l,s);return s||(u.dataset.aiaEntering=""),u},update:(l,c,u)=>{let f=u===t&&!s;l.id=`${o}-option-${u}`,l.dataset.aiaIndex=String(u),l.setAttribute("aria-selected",String(f)),l.classList.toggle("magicx-aia-option--highlighted",f),!s&&c.is_tappable?(l.onclick=()=>{l.classList.add("magicx-aia-option--pressed"),i(c),setTimeout(()=>l.classList.remove("magicx-aia-option--pressed"),170)},l.onmouseenter=()=>{let g=Number.parseInt(l.dataset.aiaIndex??"-1",10);g>=0&&r(g)}):(l.onclick=null,l.onmouseenter=null)}})}function Li(n,e,t,i,r){for(let o of n.querySelectorAll("[data-aia-entering]")){if(!i){let s=Number.parseInt(o.dataset.aiaIndex??"-1",10);s>=0&&o.style.setProperty(at,`${lt(s,t,e,r)}ms`)}delete o.dataset.aiaEntering}}function Di(n,e){let t=document.createElement("div");t.setAttribute("role","option"),t.setAttribute("data-aia-option",""),e&&t.setAttribute("data-aia-loading",""),t.tabIndex=e||!n.is_tappable?-1:0;let i=["magicx-aia-option"];n.is_tappable?i.push("magicx-aia-option--tappable"):i.push("magicx-aia-option--non-tappable"),t.className=i.join(" ");let r=document.createElement("span");r.className="magicx-aia-option-content";let o=document.createElement("span");if(o.className="magicx-aia-option-text",o.textContent=n.icon?`${n.icon} ${n.text}`:n.text,r.appendChild(o),n.tag){let s=document.createElement("span");s.className="magicx-aia-option-tag",s.textContent=n.tag,r.appendChild(s)}return t.appendChild(r),t}var gn="magicx-aia-scroll-arrow",hn="data-aia-scroll-arrow",Z="data-aia-visible",Ie="data-aia-leaving",bn=240,yn="--aia-scroll-arrow-bottom",xn="Scroll down for more options",ki=4,Ri=8,_i=240;function Ni(n,e,t,i){let r=n.scrollTop,o=t?.requestAnimationFrame,s=n.ownerDocument?.visibilityState==="hidden";if(!o||s||ct(n)){n.scrollTop=r+e,i();return}let a=t.performance?.now?.()??Date.now(),d=()=>t.performance?.now?.()??Date.now(),l=()=>{let c=Math.min(1,(d()-a)/_i),u=1-(1-c)*(1-c);n.scrollTop=r+e*u,c<1?o.call(t,l):i()};o.call(t,l)}function Hi(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","14"),t.setAttribute("height","14"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.75"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let i=n.createElementNS(e,"path");return i.setAttribute("d","M4 6.5 8 10.5l4-4"),t.appendChild(i),t}function Sn(n=document){let e=n.createElement("button");return e.type="button",e.tabIndex=-1,e.className=gn,e.setAttribute(hn,""),e.setAttribute("aria-label",xn),e.setAttribute("aria-hidden","true"),e.appendChild(Hi(n)),e}function Fi(n){let e=n.style.gridTemplateColumns.trim();return e?Math.max(1,e.split(/\s+/).length):1}function ct(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function ut({dropdown:n,grid:e,button:t}){let i=e.ownerDocument?.defaultView??(typeof window<"u"?window:null),r=!1,o=null,s=null,a=null,d=()=>{a!==null&&clearTimeout(a),a=null,t.removeAttribute(Ie)},l=p=>{if(p){d(),t.setAttribute(Z,""),t.setAttribute("aria-hidden","false");return}let m=t.hasAttribute(Z);t.removeAttribute(Z),t.setAttribute("aria-hidden","true"),!(!m||ct(t))&&(t.setAttribute(Ie,""),a=setTimeout(()=>{a=null,t.removeAttribute(Ie)},bn))},c=()=>{let p=0,m=e;for(;m&&m!==n;)p+=m.offsetTop,m=m.offsetParent instanceof HTMLElement?m.offsetParent:null;let b=i&&Number.parseFloat(i.getComputedStyle(e).paddingBottom)||0,y=n.clientHeight-(p+e.offsetHeight)+(b>0?0:Ri);t.style.setProperty(yn,`${Math.max(0,Math.round(y))}px`)},u=()=>{if(r||s!==null)return;let p=e.querySelector("[data-aia-option][data-aia-loading]")!==null,m=e.scrollHeight-e.clientHeight-e.scrollTop;l(!p&&m>ki)},f=()=>{if(r)return;c();let p=e.getAttribute("data-aia-group")??"";if(p!==o){o=p,l(!1),s!==null&&clearTimeout(s);let m=e.querySelectorAll("[data-aia-option]").length,b=ct(e)?0:dt(m,Fi(e));s=setTimeout(()=>{s=null,u()},b);return}u()},g=()=>u();e.addEventListener("scroll",g,{passive:!0});let h=p=>p.preventDefault(),x=()=>{let p=i?(Number.parseFloat(i.getComputedStyle(e).paddingTop)||0)+(Number.parseFloat(i.getComputedStyle(e).paddingBottom)||0):0,m=Math.max(1,e.clientHeight-p);Ni(e,m,i,u)};t.addEventListener("mousedown",h),t.addEventListener("click",x);let S=null;return i&&typeof i.ResizeObserver=="function"&&(S=new i.ResizeObserver(()=>{c(),u()}),S.observe(e)),f(),{update:f,destroy(){r||(r=!0,s!==null&&clearTimeout(s),s=null,e.removeEventListener("scroll",g),t.removeEventListener("mousedown",h),t.removeEventListener("click",x),S?.disconnect(),d(),t.removeAttribute(Z),t.setAttribute("aria-hidden","true"))}}}var Bi=[159,119,164];function Le(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 Me=new WeakMap;function Wi(n,e){let t=Me.get(n);if(t||(t={button:Sn(n.ownerDocument),grid:null,controller:null},n.appendChild(t.button),Me.set(n,t)),t.grid!==e&&(t.controller?.destroy(),t.controller=null,t.grid=e,e)){t.controller=ut({dropdown:n,grid:e,button:t.button});return}t.controller?.update()}function pt(n){let e=Me.get(n);e&&(e.controller?.destroy(),Me.delete(n))}function De(n,e){let{filteredOptions:t,activeIndex:i,isOpen:r,isLoading:o,pills:s,showPills:a,isActivePillSelected:d,onSelect:l,onHighlight:c,onPillClick:u,onSkip:f}=e,g=s.length>0,h=a&&g,x=t.length>0,S=e.products.length>0,p=r&&(x||h||o||S);if(p?n.classList.add("magicx-aia-dropdown--visible"):n.classList.remove("magicx-aia-dropdown--visible"),o?n.setAttribute("data-aia-loading",""):n.removeAttribute("data-aia-loading"),!p){st(n,!1);return}S?n.setAttribute("data-aia-has-products",""):n.removeAttribute("data-aia-has-products");let m=n.querySelector(".aia-stack");m||(m=document.createElement("div"),m.className="aia-stack",m.style.setProperty("--aia-stack-space","8px"),n.appendChild(m));let b=e.showSkipButton&&g&&!e.isInputEmpty,y=h||o&&a||b,v=m.querySelector(".magicx-aia-pill-bar");if(y){v||(v=document.createElement("div"),v.className="magicx-aia-pill-bar aia-cluster",v.setAttribute("data-nowrap",""),v.setAttribute("data-aia-pillbar",""),m.insertBefore(v,m.firstChild));let w=v.querySelector(".magicx-aia-pill-scroll");w||(w=document.createElement("span"),w.className="magicx-aia-pill-scroll",w.setAttribute("data-aia-pill-scroll",""),v.insertBefore(w,v.firstChild)),Oe(w,a?s:[],0,u,!0,o&&a,d),Vi(v,b,o||e.skipDisabled,s[0],f)}else v&&v.remove();let C=e.suggestions[0],_=C?`${C.type} ${C.text}`:"",D=e.formatType==="date";fn(m,D?[]:t,i,l,c,e.listboxId,o,_,e.optionsPosition??"below"),Wi(n,m.querySelector(".aia-grid")),cn(m,D?t:[],i,e.listboxId,D?e.dateView:null,e.selectedDateIso,{onSelect:l,onHighlight:c,onPreviousMonth:e.onPreviousMonth,onNextMonth:e.onNextMonth});let P=m.querySelector(".magicx-aia-skeleton-bars");if(o&&!x){if(!P){P=document.createElement("div"),P.className="magicx-aia-skeleton-bars",P.setAttribute("data-aia-skeleton-bars","");for(let w of Bi){let Y=document.createElement("span");Y.className="magicx-aia-skeleton-bar",Y.style.width=`${w}px`,P.appendChild(Y)}m.appendChild(P)}}else P&&P.remove();mn(m,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange),st(n,!0);let Q=m.querySelector(".magicx-aia-footer")??$i(),E=i>=0&&!!t[i]?.is_tappable;qi(Q,rt(E,e.isInputEmpty)),Q.isConnected||m.appendChild(Q),Gi(m,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-datepicker",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"])}function Gi(n,e){let t=e.map(i=>n.querySelector(`:scope > ${i}`)).filter(i=>i!==null);for(let i=0;i<t.length;i++)n.children[i]!==t[i]&&n.insertBefore(t[i],n.children[i]??null)}function Vi(n,e,t,i,r){let o=n.querySelector(".magicx-aia-skip");if(!e){o?.remove();return}o||(o=document.createElement("button"),o.type="button",o.tabIndex=-1,o.className="magicx-aia-skip",o.setAttribute("data-aia-skip",""),o.textContent="skip",o.addEventListener("mousedown",s=>s.preventDefault()),n.appendChild(o)),o.setAttribute("aria-label",i?`Skip ${i.text}`:"Skip"),o.disabled=t,o.onclick=t?null:()=>r()}function qi(n,{key:e,hint:t}){let i=n.querySelector(".magicx-aia-footer-key"),r=n.querySelector(".magicx-aia-footer-hint");!i||!r||(i.textContent!==e&&(i.textContent=e),r.textContent!==t&&(r.textContent=t))}function $i(){let n=document.createElement("footer");n.className="magicx-aia-footer",n.setAttribute("data-aia-footer","");let e=document.createElement("div");e.className="aia-cluster magicx-aia-footer-row",e.setAttribute("data-align","center"),e.setAttribute("data-justify","between"),e.setAttribute("data-nowrap","");let t=document.createElement("div");t.className="aia-cluster magicx-aia-footer-hint-group",t.setAttribute("data-align","center"),t.style.setProperty("--aia-cluster-gap","5px");let i=document.createElement("kbd");i.className="magicx-aia-footer-key",i.textContent="tab";let r=document.createElement("span");r.className="magicx-aia-footer-hint",r.textContent="to select",t.append(i,r);let o=document.createElement("a");o.className="aia-cluster magicx-aia-footer-brand-link",o.setAttribute("data-align","center"),o.href=it(),o.target="_blank",o.rel="noopener noreferrer",o.style.setProperty("--aia-cluster-gap","2px");let s=document.createElement("span");s.className="magicx-aia-footer-brand",s.textContent="AI";let a=document.createElement("span");return a.className="magicx-aia-footer-badge",a.textContent="Autocomplete",o.append(s,a),e.append(t,o),n.append(e),n}function vn(n,e){let t=Le(e.listboxId);return n.appendChild(t),{dropdown:t}}function mt(n,e,t){De(n.dropdown,{suggestions:e.editingIdentified?[{type:e.editingIdentified.type,text:N(e.editingIdentified.type),required:!0,options:e.filteredOptions}]:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation||e.isSearchingOptions,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,showSkipButton:t.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:e.editingIdentified?e.editingIdentified.iso:j(e.editingParam?.text),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 Ki=6,Ui=.3;function Pn(n){return n<=0?"0px":`${(-Math.min(Ui,2*Ki/n)).toFixed(3)}px`}function ft(n){let{input:e,segments:t,newParamId:i,editingParamId:r,placeholderText:o,isFocused:s}=n,a=t.length===0;e.dataset.aiaEmpty=a?"true":"false",on(e,a?o:"");let d=t.map(S=>`${S.type}:${S.value}`).join("\0"),l=e.dataset.segKey??"",c=e.dataset.newParamId??"",u=e.dataset.editingParamId??"";if(d===l&&(i??"")===c&&(r??"")===u)return;let f=s?L(e):null;e.dataset.segKey=d,e.dataset.newParamId=i??"",e.dataset.editingParamId=r??"";let g=A(e),h=g.createDocumentFragment(),x=0;for(let S of t)if(x+=S.value.length,S.type==="completed"){let p=g.createElement("strong");p.dataset.seg="completed",p.dataset.paramId=S.param.id;let m=S.param.id===i,b=S.param.id===r,y=["magicx-aia-segment","magicx-aia-segment--completed"];m&&y.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),b&&y.push("magicx-aia-segment--editing"),p.className=y.join(" "),p.style.letterSpacing=Pn(S.value.length),p.textContent=S.value,h.appendChild(p)}else if(S.type==="identified"){let p=g.createElement("strong");p.dataset.seg="identified",p.dataset.paramId=S.param.id;let m=["magicx-aia-segment","magicx-aia-segment--completed"];S.param.id===r&&m.push("magicx-aia-segment--editing"),p.className=m.join(" "),p.style.letterSpacing=Pn(S.value.length),p.textContent=S.value,h.appendChild(p)}else h.appendChild(g.createTextNode(S.value));e.replaceChildren(h),e.dataset.aiaTextLength=String(x),f!=null&&O(e,Math.max(0,Math.min(f,x)))}var Qi='<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 En(){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=Qi,n}function Yi(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function wn(n,e){let t=e.firstElementChild;if(!t){e.removeAttribute("data-aia-pill-wrapped");return}let i=t.getBoundingClientRect(),r=n.getBoundingClientRect();i.top>=r.bottom-2?e.setAttribute("data-aia-pill-wrapped",""):e.removeAttribute("data-aia-pill-wrapped")}function Tn(n,e){let{listboxId:t}=e,i=Le(t);n.appendChild(i);let r=document.createElement("div");r.className="magicx-aia-input-wrapper",n.appendChild(r);let o=document.createElement("div");o.className="magicx-aia-editor",o.setAttribute("data-aia-editor",""),r.appendChild(o);let s=document.createElement("div");s.className="magicx-aia-input",s.setAttribute("data-aia-input",""),s.setAttribute("contenteditable",Yi()?"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"),o.appendChild(s);let a=document.createElement("span");a.className="magicx-aia-pill-list-container",a.setAttribute("data-aia-pill-list-container",""),o.appendChild(a);let d=null,l=null;e.submitButton===void 0?(d=En(),r.appendChild(d),l=d):e.submitButton!==null&&(l=e.submitButton,l.hasAttribute("data-aia-submit")||l.setAttribute("data-aia-submit",""),r.appendChild(l));let c=new AbortController,{signal:u}=c,f=!1,g=0,h=()=>{let p=ye(s),b=p.length>0&&p[0]!==p[0].toUpperCase()?p[0].toUpperCase()+p.slice(1):p;e.handleChange(b)},x=()=>{let p=M(s);if(!p||p.rangeCount===0)return null;let m=p.anchorNode;if(!m||!s.contains(m))return null;let v=(m.nodeType===Node.ELEMENT_NODE?m:m.parentElement)?.closest("strong[data-param-id]")?.dataset.paramId??null;return v&&jt(s,v)?null:v};if(r.addEventListener("click",p=>{p.target?.closest("[data-aia-pill]")||s.focus()},{signal:u}),s.addEventListener("input",()=>{f||(g=performance.now(),h(),e.handleCaretAfterInput(L(s)))},{signal:u}),A(s).addEventListener("selectionchange",()=>{let p=M(s);if(!p||p.rangeCount===0||!s.contains(p.anchorNode))return;let m=p.isCollapsed?x():null,b=e.store.get(),y=b.editingParam?.id??b.editingIdentified?.id??null;if(m&&m!==y){e.startEditingParam(m);return}performance.now()-g<50||e.handleCaretMove(L(s))},{signal:u}),s.addEventListener("compositionstart",()=>{f=!0},{signal:u}),s.addEventListener("compositionend",()=>{f=!1,h()},{signal:u}),s.addEventListener("beforeinput",p=>{let m=p,b=m.inputType;if(b==="insertParagraph"||b==="insertLineBreak"||b==="insertFromDrop"){p.preventDefault();return}if(b.startsWith("insert")||b.startsWith("delete")){let y=b.startsWith("delete")?"":m.data??"";e.replaceEditingRange(y)&&p.preventDefault()}},{signal:u}),s.addEventListener("paste",p=>{p.preventDefault();let m=(p.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!m)return;let b=A(s),y=M(s);if(!y||y.rangeCount===0)return;let v=y.getRangeAt(0);if(!s.contains(v.startContainer))return;v.deleteContents();let C=b.createTextNode(m);v.insertNode(C),v.setStartAfter(C),v.collapse(!0),y.removeAllRanges(),y.addRange(v),h()},{signal:u}),s.addEventListener("keydown",p=>e.handleKeyDown(p),{signal:u}),s.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:u}),s.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:u}),l&&l.addEventListener("click",p=>{let m=e.store.get();if(!(!!m.text||m.completedParams.length>0)||!e.onSubmit)return;p.stopPropagation(),e.onSubmit(W(m.text,m.completedParams,m.skippedParams,{identifiedParams:m.identifiedParams,isReady:m.isReady}))&&e.afterSubmit?.()},{signal:u}),e.autoFocus!==!1){s.focus();let p=A(s),m=M(s),b=m&&m.rangeCount>0&&s.contains(m.anchorNode);if(m&&!b){let y=p.createRange();y.selectNodeContents(s),y.collapse(!0),m.removeAllRanges(),m.addRange(y)}}if(typeof ResizeObserver<"u"){let p=new ResizeObserver(()=>wn(s,a));p.observe(s),c.signal.addEventListener("abort",()=>p.disconnect(),{once:!0})}return{input:s,inlinePillContainer:a,dropdown:i,submitButton:d,abort:c}}function gt(n,e,t){let{input:i,inlinePillContainer:r,dropdown:o,submitButton:s}=n,{pillPlacement:a,setActivePill:d,selectOption:l,store:c}=t;i.setAttribute("aria-expanded",String(e.isDropdownOpen));let u=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(u?i.setAttribute("aria-activedescendant",u):i.removeAttribute("aria-activedescendant"),s){let S=!!e.text||e.completedParams.length>0;s.disabled=!S}let f=i.dataset.newParamId??"",g=e.newParamId!==null&&e.newParamId!==f;if(ft({input:i,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused}),a==="inline"){let S=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;S||e.actionableSuggestions.length>0?Oe(r,e.actionableSuggestions,0,d,!1,S,e.isActivePillSelected):ot(r)}else ot(r);wn(i,r),g?(i.focus(),O(i,e.caretOffset??e.text.length)):e.isFocused&&ye(i)!==e.text&&O(i,e.text.length);let h=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:e.editingIdentified?{type:e.editingIdentified.type,text:N(e.editingIdentified.type),required:!0,options:[]}:null,x=h??e.actionableSuggestions[0];De(o,{suggestions:x?[{...x,options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation||e.isSearchingOptions,listboxId:t.listboxId,pills:h?[h]:e.actionableSuggestions,showPills:a==="dropdown",showSkipButton:t.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:e.editingIdentified?e.editingIdentified.iso:j(e.editingParam?.text),optionsPosition:t.optionsPosition??"below",onSelect:l,onHighlight:S=>c.set({activeDropdownIndex:S}),onPillClick:d,onSkip:t.skipActivePill,onPreviousMonth:t.showPreviousMonth,onNextMonth:t.showNextMonth,onProductSelect:t.selectProduct,onProductFocusChange:S=>c.set({isFocused:S})})}function Cn(n,e){let t=n.actionableSuggestions[0];if(!t)return null;let i=n.filterBase,r=n.text.slice(0,i),o=r.length===0&&n.text.length===0,s=r.length===0&&n.text.length>0&&n.placeholderText.length>0&&n.placeholderText.toLowerCase().startsWith(n.text.toLowerCase());(o||s)&&n.placeholderText&&(r=`${n.placeholderText} `);let a=_t(r,e.text);a>0&&(r=r.slice(0,r.length-a));let d=r.length>0&&r[r.length-1]!==" ",l=`${r}${d?" ":""}${e.text} `,c=(o||s)&&l.length>0?l[0].toUpperCase()+l.slice(1):l,u=c.toLowerCase().lastIndexOf(e.text.toLowerCase()),f=u>=0?c.slice(u,u+e.text.length):e.text,g={id:crypto.randomUUID(),placeholder:"",type:t.type,text:f,kind:e.kind,suggestionType:t.type,suggestionPlaceholder:t.text,options:t.options??[],metadata:e.metadata},h=n.actionableSuggestions.length-1;return{patch:{text:c,filterBase:c.length,completedParams:[...n.completedParams,g],newParamId:g.id,caretOffset:c.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:!0,inSelectionAnimation:!0,pendingSpan:null},telemetry:{selectedOption:e.text,otherOptions:n.filteredOptions.filter(x=>x.text!==e.text).map(x=>x.text)},consumedSuggestion:t,remainingActionable:h}}function ht(n){let e=n,t=new Set,i=[],r=!1;return{get:()=>e,set:o=>{let s=typeof o=="function"?o(e):o,a=e;if(e={...e,...s},i.push([e,a]),!r){r=!0;try{let d=0;for(let l=i.shift();l;l=i.shift()){if(++d>1e4)throw i.length=0,new Error("createStore: notifications did not settle after 10000 deliveries \u2014 a listener is likely calling set() on every notification");let[c,u]=l;for(let f of t)f(c,u)}}catch(d){throw i.length=0,d}finally{r=!1}}},subscribe:o=>(t.add(o),()=>{t.delete(o)})}}function An(n,e){let t,i,r=o=>(o!==t&&(t=o,i=e(o)),i);return{get:()=>{let o=n.get();return{...o,...r(o)}},set:o=>{typeof o=="function"?n.set(s=>{let a={...s,...r(s)};return o(a)}):n.set(o)},peek:o=>{let s={...n.get(),...o};return{...s,...e(s)}},subscribe:o=>n.subscribe((s,a)=>{let d={...a,...r(a)},l={...s,...r(s)};o(l,d)})}}var bt=new WeakSet,On=new WeakMap;function Mn(n){return n.nodeType===Node.DOCUMENT_NODE}function ji(n){return Mn(n)?n:n.ownerDocument}function zi(n){let e=On.get(n);if(e)return e;let t=n.defaultView?.CSSStyleSheet;if(typeof t!="function")return null;try{let i=new t;return typeof i.replaceSync!="function"?null:(i.replaceSync(Dn),On.set(n,i),i)}catch{return null}}function In(n,e){if(e.querySelector("style[data-magicx-aia]"))return;let t=n.createElement("style");t.setAttribute("data-magicx-aia",""),t.textContent=Dn,e.appendChild(t)}function Ln(n){if(typeof document>"u")return;let e=n??document;if(bt.has(e))return;let t=ji(e);if(Mn(e)){let o=e.head??e.documentElement;if(!o)return;In(t,o),bt.add(e);return}let i=zi(t),r=e.adoptedStyleSheets;i&&Array.isArray(r)?r.includes(i)||(e.adoptedStyleSheets=[...r,i]):In(t,e),bt.add(e)}var Dn=`@layer layout {
|
|
1
|
+
function qe(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9]+/).filter(Boolean).map(e=>e.toLowerCase())}function B(n){let e=qe(n);return e.length>0?e.join(" "):n}var U=["January","February","March","April","May","June","July","August","September","October","November","December"],ce=["S","M","T","W","T","F","S"],_t=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],Nt="aiaDate",Ht="aiaDay",Lt=n=>String(n).padStart(2,"0");function I(n){return`${n.getFullYear()}-${Lt(n.getMonth()+1)}-${Lt(n.getDate())}`}function Ke(n){return new Date(n.getFullYear(),n.getMonth(),n.getDate())}function ni(n){let e=Ke(n).getTime()-Ke(new Date).getTime();return Math.round(e/864e5)}function Ft(n){let e=ni(n);return e>=0&&e<7?_t[n.getDay()]:Q(n)}function Q(n){return n.getFullYear()===new Date().getFullYear()?`${U[n.getMonth()]} ${n.getDate()}`:`${U[n.getMonth()]} ${n.getDate()} ${n.getFullYear()}`}function ue(n){if(!n)return null;let e=_t.findIndex(a=>a.toLowerCase()===n.trim().toLowerCase());if(e>=0){let a=Ke(new Date),l=(e-a.getDay()+7)%7;return new Date(a.getFullYear(),a.getMonth(),a.getDate()+l)}let t=/^\s*([A-Za-z]+)\s+(\d{1,2})(?:\s+(\d{4}))?\s*$/.exec(n);if(!t)return null;let i=U.findIndex(a=>a.toLowerCase()===t[1].toLowerCase());if(i<0)return null;let r=Number(t[2]),o=t[3]?Number(t[3]):new Date().getFullYear(),s=new Date(o,i,r);return s.getMonth()!==i||s.getDate()!==r?null:s}function Ue(n){return`${U[n.month]} ${n.year}`}function Qe(){let n=new Date;return{year:n.getFullYear(),month:n.getMonth()}}function Bt(n){return{year:n.getFullYear(),month:n.getMonth()}}function Ye(n,e){let t=new Date(n.year,n.month+e,1);return{year:t.getFullYear(),month:t.getMonth()}}function kt(){return{text:"",is_tappable:!1,kind:null}}function je(n){let e=new Date(n.year,n.month,1).getDay(),t=new Date(n.year,n.month+1,0).getDate(),i=[];for(let r=0;r<e;r++)i.push(kt());for(let r=1;r<=t;r++){let o=new Date(n.year,n.month,r);i.push({text:Ft(o),is_tappable:!0,kind:null,metadata:{[Nt]:I(o),[Ht]:r}})}for(;i.length%ce.length!==0;)i.push(kt());return i}function ze(n){let e=ue(n);return e?I(e):null}function L(n){let e=n?.metadata?.[Nt];return typeof e=="string"?e:null}function Xe(n){let e=n?.metadata?.[Ht];return typeof e=="number"?e:null}function ii(n){return n.replace(/(\d+)(?:st|nd|rd|th)\b/g,"$1")}function Wt(n){let e=n.toLowerCase().replace(/\.$/,"");return e.length<3?-1:U.findIndex(t=>t.toLowerCase().startsWith(e))}function ri(n,e,t){let i=new Date(t.getFullYear(),n,e);if(i.getMonth()!==n||i.getDate()!==e)return null;let r=new Date(t.getFullYear(),t.getMonth(),t.getDate());if(i>=r)return i;let o=new Date(t.getFullYear()+1,n,e);return o.getMonth()===n&&o.getDate()===e?o:null}function Gt(n,e,t){let i=new Date(n,e,t);return i.getMonth()===e&&i.getDate()===t?i:null}function W(n,e={}){if(!n)return null;let t=e.today??new Date,i=ii(n.trim().toLowerCase()).replace(/\s+/g," "),r=/^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(i);if(r){let l=Gt(Number(r[1]),Number(r[2])-1,Number(r[3]));return l?I(l):null}let o=/^([a-z]+)\.? (\d{1,2})(?:,? (\d{4}))?$/.exec(i);if(o){let l=Wt(o[1]);if(l>=0)return pe(l,Number(o[2]),o[3],t)}let s=/^(\d{1,2}) (?:of )?([a-z]+)\.?(?:,? (\d{4}))?$/.exec(i);if(s){let l=Wt(s[2]);if(l>=0)return pe(l,Number(s[1]),s[3],t)}let a=/^(\d{1,2})[/\-.](\d{1,2})(?:[/\-.](\d{2,4}))?$/.exec(i);if(a){let l=Number(a[1]),d=Number(a[2]);return l>12&&d<=12?pe(d-1,l,a[3],t):d>12&&l<=12?pe(l-1,d,a[3],t):null}return null}function pe(n,e,t,i){if(t){if(t.length!==4)return null;let o=Gt(Number(t),n,e);return o?I(o):null}let r=ri(n,e,i);return r?I(r):null}function Je(n,e={}){let t=n.isoDate;return typeof t=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t)?t:W(n.text,e)}var Vt=" - ",et="aiaDateRangeStart",tt="aiaDateRangeEnd";function ee(n,e){return n<=e?{start:n,end:e}:{start:e,end:n}}var Ze=/^\d{4}-\d{2}-\d{2}$/;function $t(n){if(!Ze.test(n))return null;let[e,t,i]=n.split("-").map(Number),r=new Date(e,t-1,i);return r.getMonth()===t-1&&r.getDate()===i?r:null}var oi=/\s+(?:to|through|thru|until|til|till)\s+/g,si=/[-–—]/g;function ai(n){let e=[];for(let t of[oi,si]){t.lastIndex=0;let i=t.exec(n);for(;i!==null;)e.push([n.slice(0,i.index),n.slice(i.index+i[0].length)]),i=t.exec(n)}return e}function Y(n,e={}){if(!n)return null;let t=new Set,i=null;for(let[r,o]of ai(n.trim())){let s=W(r.trim(),e);if(!s)continue;let a=W(o.trim(),e);!a||a<s||(t.add(`${s}|${a}`),i={start:s,end:a})}return t.size===1?i:null}function qt(n){let e=$t(n.start),t=$t(n.end);return!e||!t?"":n.start===n.end?Q(e):`${Q(e)}${Vt}${Q(t)}`}function Kt(n,e){let t=ee(n,e);return{text:qt(t),is_tappable:!0,kind:null,metadata:{[et]:t.start,[tt]:t.end}}}function te(n,e={}){let t=n?.metadata?.[et],i=n?.metadata?.[tt];return typeof t=="string"&&typeof i=="string"&&Ze.test(t)&&Ze.test(i)?ee(t,i):Y(n?.text,e)}function P(n){return n==="date"||n==="date-range"}var li=new Set(["date","dates"]),di=new Set(["range","ranges","span","period","window"]),Ut=3;function ci(n){let e={single:0,range:0};if(!n)return e;for(let t of n)t.is_tappable&&(Y(t.text)!==null?e.range+=1:W(t.text)!==null&&(e.single+=1));return e}function G(n){if(!n)return"options";let e=n.formatType;if(e==="date"||e==="options"||e==="date-range")return e;let t=ci(n.options);if(t.single+t.range>=Ut&&t.range>t.single)return"date-range";let i=qe(n.type);return i.some(r=>li.has(r))?i.some(r=>di.has(r))?"date-range":"date":t.single>=Ut?"date":"options"}var me=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 ui="https://api.ai-autocomplete.com",fe=`${ui}/api/suggest`,Qt=new WeakMap;function ne(n){return n?.type==="accessToken"}function pi(n){if(!(!n||ne(n)))return n}function ge(n){let e=Qt.get(n.getAccessToken);return e||(e=new me(n),Qt.set(n.getAccessToken,e)),e}function he(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function be(n){let e=pi(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 Yt="skipped";function re(n,e){if(e.length===0)return n;let t=new Set(n.map(r=>r.type)),i=e.filter(r=>!t.has(r.type)).map(r=>({placeholder:"",type:r.type,text:Yt,kind:null}));return i.length>0?[...n,...i]:n}var mi="0.19.0",jt=!1;function fi(){return crypto.randomUUID()}function gi(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.text},kind:n.kind}}function hi(n,e,t,i,r,o,s,a){let l=e.find(c=>c.type==="contact"&&c.metadata?.contact_account_count)?.metadata?.contact_account_count,d=typeof l=="number"?l:void 0;return{data:{raw_query:n,completed_params:re(e.map(c=>gi(c,t)),s??[]),...r&&r.length>0&&{identified_params:ie(r)},...o&&o.length>0&&{recently_suggested:o},...d!=null&&{contact_account_count:d},...a!==void 0&&{additional_context:a}},meta:{request_id:fi(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:mi,session_id:i}}}async function zt(n,e,t,i,r){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:r})}async function Xt(n,e,t){let i=t.apiConfig,r=!t.maskCompletedText,o=hi(n,e,r,t.sessionId,t.identifiedParams,t.recentlySuggested,t.skippedParams,t.additionalContext),s=he(i),a=i?.endpoint??fe,l=JSON.stringify(o);if(ne(i)){let u=ge(i),f=await u.getToken(),g=await zt(a,s,f,l,t.signal);if(g.status===401){let h=await u.getToken(!0);g=await zt(a,s,h,l,t.signal)}if(!g.ok)throw new Error(`API error: ${g.status} ${g.statusText}`);return g.json()}let d=be(i);!d&&!jt&&(jt=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),d&&(s.Authorization=d);let c=await fetch(a,{method:"POST",headers:s,body:l,signal:t.signal});if(!c.ok)throw new Error(`API error: ${c.status} ${c.statusText}`);return c.json()}function T(n,e){let t=n,i={},r=[],o=[],s=0;for(let a of e){let l=(i[a.type]??0)+1;i[a.type]=l;let c=`{{${a.type.toUpperCase().replace(/\s+/g,"_")}_${l}}}`,u=g=>{let h=t.indexOf(a.text,g);for(;h!==-1&&o.some(x=>h<x.end&&h+a.text.length>x.start);)h=t.indexOf(a.text,h+1);return h},f=u(s);if(f===-1&&(f=u(0)),f!==-1){t=t.slice(0,f)+c+t.slice(f+a.text.length);let g=c.length-a.text.length;for(let h of o)h.start>=f+a.text.length&&(h.start+=g,h.end+=g);o.push({start:f,end:f+c.length}),s=f>=s?f+c.length:s+g}r.push({...a,placeholder:c})}return{rawQuery:t,completedParams:r}}function _(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function ye(n,e,t){return e===0&&n.length>0&&t.length>0&&t.toLowerCase().startsWith(n.toLowerCase())}function $(n,e,t){let i=n.slice(e);if(t||e===0||n[e-1]===" ")return i;let r=i.indexOf(" ");return r===-1?"":i.slice(r+1)}function Jt(n,e){let t=n.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let i=t.split(" "),r=e.toLowerCase();for(let o=0;o<i.length;o++){let s=i.slice(o).join(" ");if(r.startsWith(s.toLowerCase())){let a=t.length-s.length;return n.length-a}}return 0}function V(n,e){if(!n)return[];let t=e.trimStart();if(!t)return n;let i=t.toLowerCase();return n.filter(r=>!r.is_tappable||r.text.toLowerCase().includes(i))}function j(n,e){if(!n)return null;let t=e.trim();if(!t)return null;let i=t.toLowerCase();return n.find(r=>r.is_tappable&&r.text.toLowerCase()===i)??null}function Zt(n,e){return e?n.map(t=>e[t.type]?{...t,options:[]}:t):n}function en(n,e){let t=0,i=e;for(let r of n)t+=r.value.length,r.type!=="text"&&(i=Math.max(i,t));return i}function tn(n,e){let t=0;for(let i of n){let r=t+i.value.length;if(i.type==="text"&&r>e&&i.value.slice(Math.max(e-t,0)).trim().length>0)return!1;t=r}return!0}function nn(n,e){let t=[],i=new Set;for(let r of[...n,...e])r.type==="placeholder"||i.has(r.type)||(i.add(r.type),t.push({type:r.type,text:r.text}));return t}function rn(n,e,t){if(n===e)return t;let i=Math.min(n.length,e.length),r=0;for(;r<i&&n[r]===e[r];)r++;if(r>=t)return t;let o=0;for(;o<i-r&&n[n.length-1-o]===e[e.length-1-o];)o++;return n.length-o<=t?t+(e.length-n.length):null}function nt(n,e){let t=[],i=[],r=0;for(let o of e){let s=n.indexOf(o.text,r);if(s===-1){i.push(o);continue}t.push({start:s,end:s+o.text.length,param:o}),r=s+o.text.length}return{located:t,missing:i}}function on(n,e,t){let i=[],r=[],o=0;for(let s of t){let a=n.indexOf(s.text,o);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){r.push(s);continue}i.push({start:a,end:a+s.text.length,param:s}),o=a+s.text.length}return{located:i,missing:r}}function sn(n,e,t=[]){let i=nt(n,e).located,r=on(n,i,t).located,o=[...i.map(d=>({start:d.start,end:d.end,segment:{type:"completed",value:d.param.text,param:d.param}})),...r.map(d=>({start:d.start,end:d.end,segment:{type:"identified",value:d.param.text,param:d.param}}))].sort((d,c)=>d.start-c.start),s=[],a=0;for(let d of o)d.start>a&&s.push({type:"text",value:n.slice(a,d.start)}),s.push(d.segment),a=d.end;let l=n.slice(a);return l&&s.push({type:"text",value:l}),s}function an(n,e){let{located:t,missing:i}=nt(n,e);return{valid:t.map(r=>r.param),invalid:i}}function xe(n,e,t){let i=nt(n,e).located,{located:r,missing:o}=on(n,i,t);return{valid:r.map(s=>s.param),invalid:o}}function bi(n){if(n instanceof Error)return n;try{return new Error(String(n))}catch{return new Error("Unknown error")}}var yi=100,xi=300,Si=2,Se=class{constructor(e,t,i,r,o,s,a,l={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=r;this.getOnError=o;this.getSessionId=s;this.getAdditionalContext=a;this.callbacks=l;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null}start(){this.doFetch("",[]);let e=this.store.get().text,t=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(i=>{(i.text!==e||i.completedParams!==t)&&(e=i.text,t=i.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let i=new AbortController;this.abortController=i;let r=++this.fetchVersion,o=this.store.get().text.length;try{this.callbacks.onRequest?.({query:this.store.get().text,signal:i.signal,isCurrent:()=>r===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 Xt(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig(),identifiedParams:s.identifiedParams,recentlySuggested:a,skippedParams:s.skippedParams,additionalContext:this.getAdditionalContext()});if(r!==this.fetchVersion)return;let d=(l.data.input??[]).filter(b=>b.source==="identified").map(b=>({id:crypto.randomUUID(),type:b.type,text:b.text})),c=Zt(l.data.suggestions??[],this.getOptionOverrides()),u=l.data.input??[],f=u[u.length-1],g=this.store.get().text,h,x;if(f?.state==="in_progress"){x=!0;let b=g.toLowerCase().lastIndexOf(f.text.toLowerCase());h=b!==-1?b:o}else x=!1,h=o;let p=c.filter(b=>b.type!=="placeholder")[0],m=null;if(p&&!P(G(p))){let b=$(g,h,x),y=j(p.options,b);y&&(m={id:crypto.randomUUID(),placeholder:"",type:p.type,text:y.text,kind:y.kind,suggestionType:p.type,suggestionPlaceholder:p.text,options:p.options??[],metadata:y.metadata},c=c.filter(v=>v!==p),this.callbacks.onAutoMatch?.({active:p,matched:y,rawQuery:e}))}this.store.set(b=>{let y=m?[...b.completedParams,m]:b.completedParams,v=xe(b.text,y,d).valid,A=new Set(s.skippedParams.map(E=>E.id)),k=new Set(b.skippedParams.filter(E=>!A.has(E.id)).map(E=>E.type));return{suggestions:k.size>0?c.filter(E=>E.type==="placeholder"||!k.has(E.type)):c,isLoading:!1,isReady:l.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:h,filterInProgress:x,identifiedParams:v,...m?{completedParams:y}:{}}}),this.callbacks.onResponse?.()}catch(s){let a=bi(s);r===this.fetchVersion&&(this.store.set({error:a,isLoading:!1}),this.getOnError()?.(a))}finally{if(r===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(Si)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},yi),this.slowDebounceTimer=setTimeout(()=>this.attemptFetch(1),xi)}attemptFetch(e,t=!1){let i=this.store.get();if(!i.text&&i.completedParams.length===0)return this.doFetch("",[]),!0;let r=this.callbacks.consumerTick?.(i,e)??"no";if(r==="asked")return!0;if(r==="owns")return!1;let o=i.suggestions.filter(y=>y.type==="placeholder").map(y=>y.text).join(" "),s=_(i.text,i.filterBase,o),a=$(i.text,s,i.filterInProgress),d=i.suggestions.filter(y=>y.type!=="placeholder")[0],c=P(i.activeFormatType),f=(d&&!c?V(d.options,a):[]).filter(y=>y.is_tappable),g=d&&!c?j(d.options,a)!==null:!1,h=a.trim().length>0;if(f.length>0&&!g&&h||ye(i.text,i.completedParams.length,o))return!1;let{rawQuery:x,completedParams:S}=T(i.text,i.completedParams),p=x.length<i.lastRawQuery.length,m=Math.abs(x.length-i.lastRawQuery.length),b=t&&x!==i.lastRawQuery;return p||m>=e||b?(this.doFetch(x,S),!0):!1}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};function vi(n){return n.nodeType===Node.DOCUMENT_NODE?!0:n.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in n}function ve(n){let e=typeof n.getRootNode=="function"?n.getRootNode():null;return e&&vi(e)?e:n.ownerDocument??n}function C(n){return n.ownerDocument??n}function M(n){let t=ve(n).getSelection?.();return t||(C(n).getSelection?.()??null)}function Pe(n,e){let t=n?ve(n):typeof document<"u"?document:null;return t?typeof t.getElementById=="function"?t.getElementById(e):typeof document<"u"?document.getElementById(e):null:null}var Ee=2,Pi="magicx-aia";function ln(n){return n==="auto"||n==="scroll"||n==="hidden"||n==="overlay"}function Ei(n){let e=C(n),t=e.defaultView;if(!t?.getComputedStyle)return null;let i=n;for(;i&&i!==e.body&&i!==e.documentElement;){let r=i.scrollWidth>i.clientWidth,o=i.scrollHeight>i.clientHeight;if(r||o){let s=t.getComputedStyle(i);if(r&&ln(s.overflowX)||o&&ln(s.overflowY))return i}if(i.classList.contains(Pi))return null;i=i.parentElement}return null}function it(n){let e=M(n);if(!e||e.rangeCount===0)return;let t=e.getRangeAt(0);if(!t.collapsed||!n.contains(t.startContainer))return;let i=Ei(n);if(!i||typeof t.getBoundingClientRect!="function")return;let r=t.getBoundingClientRect();if(r.height===0)return;let o=i.getBoundingClientRect();if(i.scrollWidth>i.clientWidth){let s=o.left+i.clientLeft,a=s+i.clientWidth;r.right>a?i.scrollLeft+=r.right-a+Ee:r.left<s&&(i.scrollLeft-=s-r.left+Ee)}if(i.scrollHeight>i.clientHeight){let s=o.top+i.clientTop,a=s+i.clientHeight;r.bottom>a?i.scrollTop+=r.bottom-a+Ee:r.top<s&&(i.scrollTop-=s-r.top+Ee)}}var un='[contenteditable="false"]',wi="strong[data-param-id]",z;function Ti(){if(z!==void 0)return z;let n=globalThis.Intl.Segmenter;if(!n)return z=null,null;try{z=new n(void 0,{granularity:"grapheme"})}catch{z=null}return z??null}function we(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(un))return!0;t=t.parentNode}return!1}function Te(n){return C(n).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return we(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function Ae(n){let e=Te(n),t="",i=e.nextNode();for(;i;)t+=i.data,i=e.nextNode();return t}function rt(n){let e=Te(n),t=0,i=e.nextNode();for(;i;)t+=i.data.length,i=e.nextNode();return t}function R(n){let e=M(n);if(!e||e.rangeCount===0)return null;let t=e.anchorNode,i=e.anchorOffset;if(!t||!n.contains(t))return null;if(t.nodeType===Node.ELEMENT_NODE){let r=t;if(we(r,n)&&r!==n)return null;let o=0;for(let s=0;s<i&&s<r.childNodes.length;s++)o+=pn(r.childNodes[s],n);return o+dn(r,n)}return t.nodeType!==Node.TEXT_NODE||we(t,n)?null:dn(t,n)+i}function pn(n,e){if(n.nodeType===Node.TEXT_NODE)return we(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(un))return 0;let i=0;for(let r of Array.from(t.childNodes))i+=pn(r,e);return i}function dn(n,e){let t=Te(e),i=0,r=t.nextNode();for(;r;){if(r===n||n.nodeType===Node.ELEMENT_NODE&&n.contains(r))return i;i+=r.data.length,r=t.nextNode()}return i}function O(n,e){let t=C(n),i=M(n);if(!i)return;let r=Math.max(0,Math.min(e,rt(n))),o=Te(n),s=0,a=null,l=0,d=o.nextNode(),c=null;for(;d;){let f=d.data.length;if(r<s+f){a=d,l=r-s;break}if(r===s+f){let g=o.nextNode();g?(a=g,l=0):(a=d,l=f);break}s+=f,c=d,d=o.nextNode()}let u=t.createRange();if(a){let f=a.parentElement?.closest('strong[data-seg="completed"]');f&&f!==n&&n.contains(f)?l===0?u.setStartBefore(f):l===a.data.length?u.setStartAfter(f):u.setStart(a,l):u.setStart(a,l)}else c?u.setStart(c,c.data.length):u.setStart(n,0);u.collapse(!0),i.removeAllRanges(),i.addRange(u),Ai(n,i,u,r),it(n)}function cn(n,e){if(!n||!e.contains(n))return null;let i=(n.nodeType===Node.ELEMENT_NODE?n:n.parentElement)?.closest(wi)??null;return i&&e.contains(i)?i:null}function Ai(n,e,t,i){let r=cn(e.anchorNode,n);if(r&&r!==cn(t.startContainer,n)){n.dataset.aiaCaretEscapedChip=`${i}:${r.dataset.paramId}`;return}delete n.dataset.aiaCaretEscapedChip}function mn(n,e){let t=n.dataset.aiaCaretEscapedChip;if(!t)return!1;let i=R(n);return i!==null&&t===`${i}:${e}`}function ot(n){let e=R(n);return e==null?!1:e>=rt(n)}function st(n,e){if(e<=0)return 0;let t=Ti();if(!t)return e-1;let i=n.slice(0,e),r=0;for(let{index:o}of t.segment(i))o<e&&(r=o);return r}function q(n,e,t=[],i={}){let{rawQuery:r,completedParams:o}=T(n,e);return{query:n.trim(),raw_query:r,completed_params:re(o,t),identified_params:ie(i.identifiedParams??[]),is_ready:i.isReady??!1}}function at(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")?ot(n):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function lt(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?R(n):null}var Ce=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:r}=this.ctx,o=e.target instanceof Node?e.target:null,s=this.getEffectiveColumns(o),a=r(),l=this.getTappableIndices(s);if((e.shiftKey||e.metaKey||e.ctrlKey||e.altKey)&&(e.key==="ArrowDown"||e.key==="ArrowUp"||e.key==="ArrowLeft"||e.key==="ArrowRight"))return;let d=this.ctx.getOptionsPosition()==="above";switch(e.key){case"ArrowDown":{let c=at(e.target,t),u=!!t.editingParam;if(!c&&!u&&t.activeDropdownIndex<0)break;if(t.activeDropdownIndex<0){if(d)break;e.preventDefault();let h=P(t.activeFormatType)?this.dateEntryIndex(t,!1):l[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:h});break}if(l.length===0)return;this.store.set({activeDropdownIndex:h});break}if(e.preventDefault(),l.length===0)return;if(P(t.activeFormatType)){this.stepDateWeek(t,7);break}if(t.filteredOptions.length>0){let h=Math.floor((t.filteredOptions.length-1)/s);if(Math.floor(t.activeDropdownIndex/s)===h){this.store.set({activeDropdownIndex:-1});break}}let f=l.indexOf(t.activeDropdownIndex),g=f<l.length-1?f+1:0;this.store.set({activeDropdownIndex:l[g]});break}case"ArrowUp":{if(t.activeDropdownIndex<0){if(!d)break;let f=at(e.target,t),g=!!t.editingParam;if(!f&&!g)break;e.preventDefault();let h=P(t.activeFormatType)?this.dateEntryIndex(t,!0):this.firstTappableInBottomRow(s)??l[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:h});break}if(l.length===0)return;this.store.set({activeDropdownIndex:h});break}if(l.length===0)break;if(e.preventDefault(),P(t.activeFormatType)){this.stepDateWeek(t,-7);break}if(t.activeDropdownIndex<s){this.store.set({activeDropdownIndex:-1});break}let c=l.indexOf(t.activeDropdownIndex),u=c>0?c-1:l.length-1;this.store.set({activeDropdownIndex:l[u]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),P(t.activeFormatType)){this.stepDateDay(t,1);break}if(t.activeDropdownIndex%s<s-1){let f=t.activeDropdownIndex+1;f<t.filteredOptions.length&&t.filteredOptions[f]?.is_tappable&&this.store.set({activeDropdownIndex:f})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let u=e.target.closest("[data-aia-input]")??e.target,f=t.editingTail;this.ctx.exitEditMode?.(),O(u,f);break}at(e.target,t)&&t.actionableSuggestions.length>=1&&(e.preventDefault(),this.ctx.skipActivePill());break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),P(t.activeFormatType)){this.stepDateDay(t,-1);break}if(t.activeDropdownIndex%s>0){let c=t.activeDropdownIndex-1;c>=0&&t.filteredOptions[c]?.is_tappable&&this.store.set({activeDropdownIndex:c});break}if(!t.editingParam&&this.ctx.startEditingParamAtCaret){let c=lt(e.target);c!=null&&this.ctx.startEditingParamAtCaret(c)}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let c=e.target.closest("[data-aia-input]")??e.target,u=t.editingAnchor;this.ctx.exitEditMode?.(),O(c,u);break}if(this.ctx.startEditingParamAtCaret){let c=lt(e.target);c!=null&&this.ctx.startEditingParamAtCaret(c)&&e.preventDefault()}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let c=lt(e.target);if(c==null)break;this.ctx.removeParamAtCaret(c)&&e.preventDefault();break}case"Enter":{e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable?this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i,o):a&&a(q(t.text,t.completedParams,t.skippedParams,{identifiedParams:t.identifiedParams,isReady:t.isReady}))&&this.ctx.afterSubmit?.();break}case"Tab":{let c=t.filteredOptions.map((g,h)=>g.is_tappable?h:-1).filter(g=>g!==-1);if(c.length===0)break;if(!t.isDropdownOpen){if(t.actionableSuggestions.length===0)break;e.preventDefault();let g=e.shiftKey?c[c.length-1]:c[0];this.store.set({pillTapped:!0,activeDropdownIndex:g});break}e.preventDefault();let u=c.indexOf(t.activeDropdownIndex),f;if(u<0)f=e.shiftKey?c.length-1:0;else{let g=e.shiftKey?-1:1;f=(u+g+c.length)%c.length}this.store.set({activeDropdownIndex:c[f]});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 c=e.target.closest("[data-aia-input]")??e.target,u=t.editingTail;this.ctx.exitEditMode?.(),O(c,u)}this.store.set({activeDropdownIndex:-1});break}}}firstTappableInBottomRow(e){let t=this.store.get();if(t.filteredOptions.length===0)return null;let r=Math.floor((t.filteredOptions.length-1)/e)*e;for(let o=r;o<t.filteredOptions.length;o++)if(t.filteredOptions[o]?.is_tappable)return o;return null}dateEntryIndex(e,t){let i=I(new Date),r=e.filteredOptions.findIndex(s=>L(s)===i);if(r>=0)return r;let o=e.filteredOptions.map((s,a)=>s.is_tappable?a:-1).filter(s=>s!==-1);return(t?o[o.length-1]:o[0])??0}stepDateDay(e,t){for(let i=e.activeDropdownIndex+t;i>=0&&i<e.filteredOptions.length;i+=t)if(e.filteredOptions[i]?.is_tappable){this.store.set({activeDropdownIndex:i});return}}stepDateWeek(e,t){let i=e.activeDropdownIndex+t;this.store.set({activeDropdownIndex:e.filteredOptions[i]?.is_tappable?i:-1})}getTappableIndices(e){let i=this.store.get().filteredOptions.map((o,s)=>o.is_tappable?s:-1).filter(o=>o!==-1),r=Array.from({length:e},()=>[]);for(let o of i)r[o%e].push(o);return r.flat()}getEffectiveColumns(e){let t=Pe(e,this.ctx.listboxId);if(!t)return this.ctx.columns;let r=Pe(e,`${this.ctx.listboxId}-option-0`)?.parentElement??null;for(;r;){let o=getComputedStyle(r).gridTemplateColumns;if(o&&o!=="none"){let s=o.split(" ").filter(Boolean).length;if(s>0)return s}if(r===t)break;r=r.parentElement}return this.ctx.columns}clickOrSelect(e,t,i,r){let o=Pe(r,`${i}-option-${e}`);o?o.click():this.ctx.selectOption(t[e])}};var Oe=class{constructor(e,t,i={}){this.store=e;this.getOverrides=t;this.callbacks=i;this.unsubscribe=null;this.current=null;this.version=0;this.lastMiss=null;this.hasLoggedError=!1}start(){this.unsubscribe=this.store.subscribe(e=>this.sync(e)),this.sync(this.store.get())}dispose(){this.unsubscribe?.(),this.unsubscribe=null,this.cancel(),this.current=null}reset(){this.cancel(),this.current=null,this.lastMiss=null}refresh(){this.reset(),this.sync(this.store.get())}hasOverride(e){return!!this.getOverrides()?.[e]}owns(e,t){return this.hasOverride(e)&&!this.missCovers(e,t)}tick(e,t){let i=this.resolveTarget(e);if(!i||this.missCovers(i.type,i.query))return"no";let r=this.current;if(r&&r.key===i.key){if(r.query===i.query)return"owns";let o=Math.abs(i.query.length-r.query.length),s=i.query.length<r.query.length;if(t>1&&!s&&o<t)return"owns"}return this.ask(i),"asked"}sync(e){let t=this.resolveTarget(e);if(!t){this.current&&(this.cancel(),this.current=null),e.optionSearch&&this.store.set({optionSearch:null});return}this.current&&this.current.key===t.key||this.ask(t)}resolveTarget(e){if(P(e.activeFormatType)||e.editingIdentified)return null;let t=e.editingParam;if(t&&e.editingAnchor!=null)return this.hasOverride(t.suggestionType)?{mode:"edit",key:t.id,type:t.suggestionType,suggestion:{type:t.suggestionType,text:t.suggestionPlaceholder,required:!0,options:t.options},query:e.optionQuery}:null;let i=e.actionableSuggestions[0];return!i||!this.hasOverride(i.type)?null:{mode:"pill",key:i,type:i.type,suggestion:i,query:e.optionQuery}}missCovers(e,t){return this.lastMiss!=null&&this.lastMiss.type===e&&this.lastMiss.query===t}ask(e){this.cancel();let t=this.getOverrides()?.[e.type],i=++this.version;if(!t||this.missCovers(e.type,e.query)){this.current={key:e.key,type:e.type,query:e.query,abort:null},this.setSearch(e,"done");return}let r=new AbortController;this.current={key:e.key,type:e.type,query:e.query,abort:r};let o;try{o=t(e.query,r.signal,e.suggestion)}catch(s){this.logOnce(s),this.commit(e,[],i);return}if(Array.isArray(o)){this.commit(e,o,i);return}this.setSearch(e,"loading"),this.await(e,o,r.signal,i)}async await(e,t,i,r){let o;try{let s=await t;if(i.aborted||r!==this.version)return;o=Array.isArray(s)?s:[]}catch(s){if(i.aborted||r!==this.version||Ci(s))return;this.logOnce(s),o=[]}this.commit(e,o,r)}commit(e,t,i){if(i!==this.version)return;let r=this.resolveTarget(this.store.get());if(!r||r.key!==e.key)return;t.length===0?this.lastMiss={type:e.type,query:e.query}:this.lastMiss?.type===e.type&&(this.lastMiss=null);let o={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:o}));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:o}))}t.length===0?this.callbacks.onMiss?.(e.mode,e.query):this.callbacks.onAnswer?.(e.mode,e.query)}setSearch(e,t){let i=this.store.get().optionSearch;i&&i.type===e.type&&i.query===e.query&&i.status===t||this.store.set({optionSearch:{type:e.type,query:e.query,status:t}})}cancel(){this.current?.abort?.abort(),this.version++}logOnce(e){this.hasLoggedError||(this.hasLoggedError=!0,console.warn("[AIAutocomplete] an optionOverrides entry threw or rejected \u2014 treated as no options. Later failures on this instance are not logged.",e))}};function Ci(n){return n instanceof Error&&n.name==="AbortError"}var Ie=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),i=t.suggestions.filter(d=>d.type!=="placeholder");if(e<0||e>=i.length)return;let r=i[e],o=i.filter((d,c)=>c!==e),s=t.suggestions.filter(d=>d.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:d}=T(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:d,selectedPill:r.text,otherPills:o.map(c=>c.text)})}let a=[...s,r,...o],l=this.store.peek({suggestions:a}).filteredOptions.findIndex(d=>d.is_tappable);this.store.set({suggestions:a,pillTapped:!0,activeDropdownIndex:l})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};var De=class{constructor(e,t){this.store=e;this.getConfig=t;this.hasLoggedError=!1}async run(e,t,i){let r=this.getConfig();if(r){if(e.trim().length===0){this.clear(i);return}try{let o=await r.fetch(e,t);if(t.aborted||!i())return;let s=r.transform(o),a=Array.isArray(s)?s:[],l=r.limit!=null?a.slice(0,r.limit):a;if(t.aborted||!i())return;this.commit(l)}catch(o){if(t.aborted||Oi(o))return;this.logOnce(o),this.clear(i)}}}clearNow(){this.commit([])}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 Oi(n){return n instanceof Error&&n.name==="AbortError"}var Me="(max-width: 768px)";var Ii="var(--aia-option-row-height, 37px)",Di="var(--aia-grid-scroll-top, 0px) + var(--aia-grid-scroll-bottom, 0px)";function fn(n,e){return e?dt(1,Math.min(n,5)):dt(1,Math.min(n,4))}function dt(n,e){return{cols:n,rows:e,maxHeight:`calc(${e} * ${Ii} + ${Di})`}}function ct(n,e){return!e&&n>=5}function ut(n,e,t,i){if(!(!e&&n>=5&&Mi(t,i))){let a=fn(n,e);return{...a,template:hn(a.cols),scrollHintIndices:!e&&n>a.rows?[a.rows-1]:[]}}let[o]=gn(t),s=6;return{...dt(2,3),template:`${o}px minmax(0,1fr)`,scrollHintIndices:n>s?[s-2,s-1]:[]}}function gn(n){let e=0,t=0;return n.forEach((i,r)=>{r%2===0?e=Math.max(e,i):t=Math.max(t,i)}),[Math.ceil(e),Math.ceil(t)]}function Mi(n,e){if(!n||n.length===0||e==null||e<=0||n.some(r=>r<=0))return!1;let[t,i]=gn(n);return t+i<=e}function pt(n){if(typeof document>"u")return null;let e=Array.from(n.querySelectorAll("[data-aia-option]"));if(e.length===0)return null;let t=document.createElement("div");t.style.cssText="position:absolute;visibility:hidden;left:-9999px;top:0;";for(let s of e){let a=s.cloneNode(!0);a.removeAttribute("id"),a.removeAttribute("role"),a.removeAttribute("aria-selected"),a.style.whiteSpace="nowrap",a.style.width="max-content",t.appendChild(a)}n.appendChild(t);let i=Array.from(t.children).map(s=>s.offsetWidth);t.remove();let r=getComputedStyle(n),o=n.clientWidth-(Number.parseFloat(r.paddingLeft)||0)-(Number.parseFloat(r.paddingRight)||0)-(Number.parseFloat(r.columnGap)||0);return{rowWidths:i,gridWidth:o}}function hn(n){return Array.from({length:n},()=>"minmax(0,1fr)").join(" ")}function mt(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(Me).matches}function bn(n,e){let t=e.dropdownTrigger??"auto",i=e.closeDropdownOnBlur??!0,s=n.filteredOptionsLength>0||n.activePillHasNoOptions||n.hasProducts;if(n.inEditMode){let a=i?n.isFocused:!0;return s&&a}if(t==="auto"){let a=i?n.isFocused:!0,l=n.text.replace(/\s+$/,"").length,d=n.caretOffset==null||n.caretOffset>=l;return(s||n.isLoading)&&a&&d}return t==="manual"?(s||n.isLoading)&&n.pillTapped:!1}function oe(n){if(n.editingIdentified){let{type:t,anchor:i}=n.editingIdentified;return`identified:${t}@${i}`}return n.editingParam!=null&&n.editingAnchor!=null?`edit:${n.editingParam?.id}`:`pill:${n.actionableSuggestions[0]?.type??""}`}function yn(n){if(!n)return Qe();let[e,t]=n.split("-").map(Number);return{year:e,month:t-1}}function Ri(n){let e=ue(n);return e?Bt(e):Qe()}function xn(n,e){let t=sn(n.text,n.completedParams,n.identifiedParams),i=n.suggestions.filter(w=>w.type!=="placeholder"),r=i[0],o=n.suggestions.filter(w=>w.type==="placeholder").map(w=>w.text).join(" "),s=_(n.text,Math.min(n.filterBase,n.text.length),o),l=s===0&&ye(n.text,n.completedParams.length,o)?"":$(n.text,s,n.filterInProgress),d=r?.options??[],c=n.editingParam!=null&&n.editingAnchor!=null,u,f,g,h;if(c&&n.editingParam&&n.editingAnchor!=null){let w=n.editingParam.id,K=n.completedParams.some(ti=>ti.id===w),Z=n.caretOffset??n.editingAnchor,Rt=K?"":n.text.slice(n.editingAnchor,Z);f=Rt.trim(),g=n.editingParam.options,h=n.editingParam.suggestionType,u=V(n.editingParam.options,Rt)}else f=l.trim(),g=d,h=r?.type,u=V(d,l);let x=n.optionSearch,S=x!=null&&h!=null&&x.type===h;S&&x.status==="done"&&x.query===f&&(u=g);let p=S&&x.status==="loading",m=e.showNonTappableOptions===!1;m&&(u=u.filter(w=>w.is_tappable));let b=n.editingIdentified,y=c?n.editingParam&&{type:n.editingParam.suggestionType,options:n.editingParam.options}:r,v=b?b.format:G(y),A=c&&P(v)?te(n.editingParam):null;A&&(v="date-range");let k=null,H=null;if(P(v)){let w=oe({...n,actionableSuggestions:i}),K=n.dateViewMonth;k=K&&K.key===w?{year:K.year,month:K.month}:b?yn(b.iso):A?yn(A.start):Ri(n.editingParam?.text),u=je(k);let Z=n.pendingRangeStart;v==="date-range"&&Z&&Z.key===w&&(H=Z.iso)}let E=w=>m?w.is_tappable:!0,F;if(c){let w=n.editingParam?.options??[];F=n.editingParam!=null&&w.filter(E).length===0}else F=r!=null&&d.filter(E).length===0;let de=bn({inEditMode:c||b!=null,filteredOptionsLength:u.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading||p,pillTapped:n.pillTapped,activePillHasNoOptions:F,hasProducts:n.products.length>0},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),D=de&&n.activeDropdownIndex>=0&&!!u[n.activeDropdownIndex]?.is_tappable;return{segments:t,actionableSuggestions:i,filteredOptions:u,activeFormatType:v,dateView:k,dateRangeStart:H,placeholderText:o,optionQuery:f,isSearchingOptions:p,isDropdownOpen:de,isActivePillSelected:D}}function Re(n){return n.mode==="fresh"?Li(n):ki(n)}function Li(n){let{text:e,completedParams:t,suggestions:i,filterBase:r,filterInProgress:o}=n,a=i.filter(y=>y.type!=="placeholder")[0];if(!a?.options)return null;let l=i.filter(y=>y.type==="placeholder").map(y=>y.text).join(" "),d=_(e,r,l),c=$(e,d,o),u=j(a.options,c);if(!u)return null;let f=u.text.toLowerCase(),g=e.toLowerCase().lastIndexOf(f),h=g>=0?g:Math.max(0,e.length-u.text.length),x=h+u.text.length,S=e.slice(h,x),m=x<e.length&&e[x]===" "?x+1:x,b={id:crypto.randomUUID(),placeholder:"",type:a.type,text:S,kind:u.kind,suggestionType:a.type,suggestionPlaceholder:a.text,options:a.options??[],metadata:u.metadata};return{patch:{text:e,completedParams:[...t,b],suggestions:i.filter(y=>y!==a),filterBase:m,newParamId:b.id,caretOffset:m,activeDropdownIndex:-1},caretPos:m}}function ki(n){let{text:e,completedParams:t,editingParam:i,editingAnchor:r,editingTail:o}=n;if(t.some(b=>b.id===i.id))return null;let s=e.slice(r,o),a=j(i.options,s);if(!a)return null;let l=a.text.toLowerCase(),d=s.toLowerCase().lastIndexOf(l),c=r+Math.max(0,d),u=c+a.text.length,f=e.slice(c,u),g=u<e.length&&e[u]===" "?u+1:u,h=e.length,x={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:f,kind:a.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:a.metadata},S=t.length,p=0;for(let b=0;b<t.length;b++){let y=e.indexOf(t[b].text,p);if(y!==-1){if(y>=g){S=b;break}p=y+t[b].text.length}}let m=[...t];return m.splice(S,0,x),{patch:{text:e,completedParams:m,newParamId:x.id,filterBase:h,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:h,activeDropdownIndex:-1},caretPos:h}}function Le(n,e,t){let i=n.slice(0,e),r=n.slice(t),o=(i===""||i.endsWith(" "))&&r.startsWith(" ");return o&&(r=r.slice(1)),{text:i+r,removed:t-e+(o?1:0)}}var ke=class{constructor(e){this.deps=e}start(e){let t=this.deps.store.get();if(t.editingParam?.id===e)return;let i=t.completedParams.find(s=>s.id===e);if(!i)return;let r=0,o=-1;for(let s of t.completedParams){let a=t.text.indexOf(s.text,r);if(a!==-1){if(s.id===e){o=a;break}r=a+s.text.length}}o<0||this.deps.store.set({editingParam:i,editingAnchor:o,editingTail:o+i.text.length,caretOffset:o+i.text.length,activeDropdownIndex:-1,editingIdentified:null})}exit(){this.deps.store.get().editingParam&&this.deps.store.set({editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1})}replaceRange(e){let t=this.deps.store.get(),i=t.editingParam,r=t.editingAnchor,o=t.editingTail;if(!i||r==null||o==null||!t.completedParams.some(l=>l.id===i.id))return!1;let{text:s}=e===""?Le(t.text,r,o):{text:t.text.slice(0,r)+e+t.text.slice(o)},a=r+e.length;return this.deps.store.set(l=>({text:s,completedParams:l.completedParams.filter(d=>d.id!==i.id),editingTail:a,caretOffset:a,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(a),this.promoteIfExact(),!0}caretAfterInput(e){let t=this.deps.store.get(),i={caretOffset:e};t.editingParam&&t.editingAnchor!=null&&e!=null&&(e<t.editingAnchor?(i.editingParam=null,i.editingAnchor=null,i.editingTail=null,i.activeDropdownIndex=-1):t.editingTail!=null&&(i.editingTail=Math.max(t.editingTail,e))),this.deps.store.set(i),this.promoteIfExact()}caretMove(e){let t=this.deps.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null&&e!=null&&(e<t.editingAnchor||e>t.editingTail)){this.deps.store.set({caretOffset:e,editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1});return}this.deps.store.set({caretOffset:e})}selectOption(e){let t=this.deps.store.get(),i=t.editingParam,r=t.editingAnchor,o=t.editingTail;if(!i||r==null||o==null)return;this.deps.fireTelemetry("option",{raw_query:T(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:i.options.filter(p=>p.text!==e.text).map(p=>p.text)});let s=t.text.slice(0,r),a=t.text.slice(o),l=r===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,c=a.length===0||a[0]!==" "?`${l} `:l,u=s+c+a,f=u.length,g={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:l,kind:e.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:e.metadata},h=t.completedParams.findIndex(p=>p.id===i.id),x=t.completedParams.filter(p=>p.id!==i.id),S=h>=0?Math.min(h,x.length):x.length;x.splice(S,0,g),this.deps.store.set({text:u,completedParams:x,newParamId:g.id,filterBase:f,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:f,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.deps.startSelectionAnimationTimer(),this.deps.scheduleSetCursor(f),this.deps.fetchNow()}promoteIfExact(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let t=Re({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 _i=33,Ni=70,Hi=120,Fi=50,X="data-aia-placeholder-leaving",J=new WeakMap;function _e(n){n.timer!==null&&(clearTimeout(n.timer),n.timer=null)}function Bi(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function vn(n,e,t){e.shown=t,n.dataset.placeholder=e.target.slice(0,t)}function Pn(n,e){if(e.timer=null,!n.isConnected||e.shown>=e.target.length||(vn(n,e,e.shown+1),e.shown>=e.target.length))return;let t=e.target[e.shown-1],i=t===" "||t==="-"?70:0;e.timer=setTimeout(()=>Pn(n,e),33+i)}function Sn(n,e){vn(n,e,0),e.timer=setTimeout(()=>Pn(n,e),33)}function En(n,e){let t=J.get(n);if(e===""){t&&(_e(t),J.delete(n)),n.removeAttribute(X),delete n.dataset.placeholder;return}if(t?.target===e)return;if(Bi(n)){t&&_e(t),n.removeAttribute(X),J.set(n,{target:e,shown:e.length,timer:null}),n.dataset.placeholder=e;return}let i={target:e,shown:0,timer:null},r=t&&t.shown>0?t:null;if(t&&_e(t),J.set(n,i),r){n.setAttribute(X,""),i.timer=setTimeout(()=>{i.timer=null,n.removeAttribute(X),n.isConnected&&Sn(n,i)},170);return}n.removeAttribute(X),Sn(n,i)}function wn(n){let e=J.get(n);e&&(_e(e),J.delete(n))}var Tn="https://ai-autocomplete.com";function ft(n=Tn){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 gt(n,e){return n?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}var Wi={selectedIso:null,selectedRange:null,rangeStart:null};function se(n){if(!P(n.activeFormatType))return Wi;let e=n.editingIdentified;if(e){let{iso:i,isoEnd:r}=e;return{selectedIso:r?null:i,selectedRange:i&&r?ee(i,r):null,rangeStart:n.dateRangeStart}}let t=te(n.editingParam);return{selectedIso:t?null:ze(n.editingParam?.text),selectedRange:t,rangeStart:n.dateRangeStart}}function ht(n){return n.pendingStart?ee(n.pendingStart,n.highlightedIso??n.pendingStart):n.selected}function bt(n,e){if(n==null)return{selected:!1,inRange:!1};let{selectedIso:t,range:i}=e,r=n===t||i!=null&&(n===i.start||n===i.end),o=i!=null&&n>i.start&&n<i.end;return{selected:r,inRange:o}}var An="data-aia-key";function N(n,e,t){let i=new Map;for(let s of Array.from(n.children)){let a=s.getAttribute(An);a!=null&&i.set(a,s)}let r=new Set,o=[];for(let s=0;s<e.length;s++){let a=e[s],l=t.keyOf(a,s);r.add(l);let d=i.get(l);d||(d=t.create(a,s),d.setAttribute(An,l)),t.update?.(d,a,s),n.children[s]!==d&&n.insertBefore(d,n.children[s]??null),o.push(d)}for(let[s,a]of i)r.has(s)||a.remove();return o}function On(n,e,t,i,r,o,s){let a=n.querySelector(".magicx-aia-datepicker");if(!r||e.length===0){a?.remove();return}a||(a=Vi(),n.appendChild(a));let l=a.querySelector(".magicx-aia-datepicker-month");l&&(l.textContent=Ue(r));let d=a.querySelector("[data-aia-date-prev]"),c=a.querySelector("[data-aia-date-next]");d&&(d.onclick=()=>s.onPreviousMonth()),c&&(c.onclick=()=>s.onNextMonth());let u=a.querySelector(".magicx-aia-datepicker-grid");u&&Gi(u,e,t,i,o,s)}function Gi(n,e,t,i,r,o){let s=I(new Date),a=ht({pendingStart:r.rangeStart,highlightedIso:L(e[t]),selected:r.selectedRange});N(n,e,{keyOf:(l,d)=>L(l)??`pad-${d}`,create:l=>$i(l),update:(l,d,c)=>{let u=L(d),f=bt(u,{selectedIso:r.selectedIso,range:a}),g=c===t&&d.is_tappable;l.id=`${i}-option-${c}`,l.dataset.aiaIndex=String(c),l.setAttribute("aria-selected",String(g)),l.classList.toggle("magicx-aia-date-cell--past",u!=null&&u<s),l.classList.toggle("magicx-aia-date-cell--highlighted",g),l.classList.toggle("magicx-aia-date-cell--today",u!=null&&u===s),l.classList.toggle("magicx-aia-date-cell--selected",f.selected),l.classList.toggle("magicx-aia-date-cell--in-range",f.inRange),d.is_tappable?(l.onclick=()=>{l.classList.add("magicx-aia-date-cell--pressed"),o.onSelect(d),setTimeout(()=>l.classList.remove("magicx-aia-date-cell--pressed"),170)},l.onmouseenter=()=>{let h=Number.parseInt(l.dataset.aiaIndex??"-1",10);h>=0&&o.onHighlight(h)}):(l.onclick=null,l.onmouseenter=null)}})}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=Xe(n);if(t==null)return e.className="magicx-aia-date-cell magicx-aia-date-cell--blank",e.setAttribute("aria-hidden","true"),e.tabIndex=-1,e;e.className="magicx-aia-date-cell magicx-aia-date-cell--day",e.tabIndex=0,e.setAttribute("aria-label",n.text);let i=document.createElement("span");return i.className="magicx-aia-date-cell-number",i.textContent=String(t),e.appendChild(i),e}function Vi(){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(Cn("prev","Previous month","\u2039"),t,Cn("next","Next month","\u203A"));let i=document.createElement("div");i.className="magicx-aia-datepicker-weekdays",i.setAttribute("aria-hidden","true");for(let o of ce){let s=document.createElement("span");s.className="magicx-aia-datepicker-weekday",s.textContent=o,i.appendChild(s)}let r=document.createElement("div");return r.className="magicx-aia-datepicker-grid",r.setAttribute("data-aia-date-grid",""),n.append(e,i,r),n}function Cn(n,e,t){let i=document.createElement("button");return i.type="button",i.tabIndex=-1,i.className="magicx-aia-datepicker-nav",i.setAttribute(`data-aia-date-${n}`,""),i.setAttribute("aria-label",e),i.textContent=t,i.addEventListener("mousedown",r=>r.preventDefault()),i}var In=[125,69];function Dn(n,e){return e?1:n===0?.7:n===1?.4:.2}function Ne(n,e,t,i,r=!1,o=!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)),o&&e.length===0){a.setAttribute("data-aia-pill-list-loading",""),a.innerHTML="";for(let l=0;l<In.length;l++){let d=In[l],c=document.createElement("span");c.setAttribute("data-aia-pill-skeleton",""),c.className=`magicx-aia-pill magicx-aia-pill--skeleton${r?" magicx-aia-pill--rounded":""}`,c.style.width=`${d}px`,c.style.opacity=String(Dn(l,!1)),a.appendChild(c)}return}o?a.setAttribute("data-aia-pill-list-loading",""):a.removeAttribute("data-aia-pill-list-loading");for(let l of a.querySelectorAll("[data-aia-pill-skeleton]"))l.remove();N(a,e,{keyOf:l=>`${l.type}-${l.text}`,create:l=>{let d=document.createElement("button");return d.type="button",d.tabIndex=-1,d.setAttribute("data-aia-pill",""),d.setAttribute("contenteditable","false"),d.textContent=l.text,d.addEventListener("mousedown",c=>c.preventDefault()),d},update:(l,d,c)=>{let u=l,f=s&&c===t&&!o,g=["magicx-aia-pill"];r&&g.push("magicx-aia-pill--rounded"),o&&g.push("magicx-aia-pill--skeleton"),u.className=g.join(" "),u.style.width="",u.style.opacity=String(Dn(c,f)),o?(u.setAttribute("data-aia-loading",""),u.disabled=!0,u.onclick=null):(u.removeAttribute("data-aia-loading"),u.disabled=!1,u.onclick=()=>i(c))}})}function yt(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var qi="Products";function Mn(n,e,t,i,r){let o=n.querySelector(".magicx-aia-products");if(e.length===0){o?.remove();return}if(!o){o=document.createElement("section"),o.className="magicx-aia-products",o.setAttribute("data-aia-products",""),o.setAttribute("role","group"),o.setAttribute("aria-labelledby",`${t}-products-label`);let a=document.createElement("div");a.className="magicx-aia-products-label",a.id=`${t}-products-label`,a.textContent=qi;let l=document.createElement("div");l.className="magicx-aia-products-row",l.setAttribute("data-aia-products-row",""),o.append(a,l),n.appendChild(o)}let s=o.querySelector(".magicx-aia-products-row");s&&N(s,e,{keyOf:a=>Ki(a),create:a=>Ui(a,i,r),update:(a,l,d)=>{a.id=`${t}-product-${d}`,a.dataset.aiaIndex=String(d)}})}function xt(n,e){let t=n.querySelectorAll("[data-aia-product]");for(let i of t)i.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 Ui(n,e,t){let i=document.createElement("a");i.className="magicx-aia-product",i.setAttribute("data-aia-product",""),i.setAttribute("role","option"),i.setAttribute("aria-selected","false"),i.href=n.url,i.tabIndex=0;let r=document.createElement("span");if(r.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",r.appendChild(a)}else r.setAttribute("data-aia-product-placeholder","");i.appendChild(r);let o=document.createElement("span");if(o.className="magicx-aia-product-body",n.vendor){let a=document.createElement("span");a.className="magicx-aia-product-vendor",a.textContent=n.vendor,o.appendChild(a)}let s=document.createElement("span");if(s.className="magicx-aia-product-title",s.textContent=n.title,o.appendChild(s),n.price){let a=document.createElement("span");a.className="magicx-aia-product-price",a.textContent=n.price,o.appendChild(a)}return i.appendChild(o),i.addEventListener("click",a=>{a.metaKey||a.ctrlKey||a.shiftKey||a.altKey||a.button!==0||(a.preventDefault(),e(n))}),i.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),e(n))}),i.addEventListener("focus",()=>t(!0)),i.addEventListener("blur",a=>{a.relatedTarget?.closest("[data-aia-dropdown]")||t(!1)}),i}var Qi=80,Yi=150,ji=280,zi=16,St="--aia-option-enter-delay";function vt(n,e,t,i="below"){let r=Math.max(1,Math.floor(e)),o=Math.floor(Math.max(0,n)/r);if(i!=="above")return o*80;let s=Math.max(1,Math.ceil(Math.max(0,t)/r));return Math.max(0,s-1-o)*80}function Pt(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 Xi(n,e,t){let i=mt(),r=!t&&ct(e,i)?pt(n):null,o=ut(e,i,r?.rowWidths??null,r?.gridWidth??null);return n.style.gridTemplateColumns=o.template,n.style.setProperty("--aia-grid-max-height",o.maxHeight),n.querySelectorAll("[data-aia-option]").forEach((s,a)=>{s.classList.toggle("magicx-aia-option--scroll-hint",!t&&o.scrollHintIndices.includes(a))}),o.cols}function Rn(n,e,t,i,r,o,s,a="",l="below"){let d=n.querySelector(".aia-grid");if(e.length===0){d?.remove();return}d||(d=document.createElement("div"),d.className="aia-grid magicx-aia-grid",d.setAttribute("data-scroll",""),d.style.setProperty("--aia-grid-min","250px"),d.style.setProperty("--aia-grid-max","1fr"),d.style.setProperty("--aia-grid-gap","0"),n.appendChild(d));let c=d.dataset.aiaGroup!==a;d.dataset.aiaGroup=a,Ji(d,e,t,i,r,o,s);let u=Xi(d,e.length,s);Zi(d,e.length,u,s,l),c&&(d.scrollTop=0)}function Ji(n,e,t,i,r,o,s){let a=s?"1":"0",l=n.dataset.aiaGroup??"";N(n,e,{keyOf:d=>`${d.text}\0${a}\0${l}`,create:(d,c)=>{let u=er(d,s);return s||(u.dataset.aiaEntering=""),u},update:(d,c,u)=>{let f=u===t&&!s;d.id=`${o}-option-${u}`,d.dataset.aiaIndex=String(u),d.setAttribute("aria-selected",String(f)),d.classList.toggle("magicx-aia-option--highlighted",f),!s&&c.is_tappable?(d.onclick=()=>{d.classList.add("magicx-aia-option--pressed"),i(c),setTimeout(()=>d.classList.remove("magicx-aia-option--pressed"),170)},d.onmouseenter=()=>{let g=Number.parseInt(d.dataset.aiaIndex??"-1",10);g>=0&&r(g)}):(d.onclick=null,d.onmouseenter=null)}})}function Zi(n,e,t,i,r){for(let o of n.querySelectorAll("[data-aia-entering]")){if(!i){let s=Number.parseInt(o.dataset.aiaIndex??"-1",10);s>=0&&o.style.setProperty(St,`${vt(s,t,e,r)}ms`)}delete o.dataset.aiaEntering}}function er(n,e){let t=document.createElement("div");t.setAttribute("role","option"),t.setAttribute("data-aia-option",""),e&&t.setAttribute("data-aia-loading",""),t.tabIndex=e||!n.is_tappable?-1:0;let i=["magicx-aia-option"];n.is_tappable?i.push("magicx-aia-option--tappable"):i.push("magicx-aia-option--non-tappable"),t.className=i.join(" ");let r=document.createElement("span");r.className="magicx-aia-option-content";let o=document.createElement("span");if(o.className="magicx-aia-option-text",o.textContent=n.icon?`${n.icon} ${n.text}`:n.text,r.appendChild(o),n.tag){let s=document.createElement("span");s.className="magicx-aia-option-tag",s.textContent=n.tag,r.appendChild(s)}return t.appendChild(r),t}var Ln="magicx-aia-scroll-arrow",kn="data-aia-scroll-arrow",ae="data-aia-visible",He="data-aia-leaving",_n=240,Nn="--aia-scroll-arrow-bottom",Hn="Scroll down for more options",tr=4,nr=8,ir=240;function rr(n,e,t,i){let r=n.scrollTop,o=t?.requestAnimationFrame,s=n.ownerDocument?.visibilityState==="hidden";if(!o||s||Et(n)){n.scrollTop=r+e,i();return}let a=t.performance?.now?.()??Date.now(),l=()=>t.performance?.now?.()??Date.now(),d=()=>{let c=Math.min(1,(l()-a)/ir),u=1-(1-c)*(1-c);n.scrollTop=r+e*u,c<1?o.call(t,d):i()};o.call(t,d)}function or(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","14"),t.setAttribute("height","14"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.75"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let i=n.createElementNS(e,"path");return i.setAttribute("d","M4 6.5 8 10.5l4-4"),t.appendChild(i),t}function Fn(n=document){let e=n.createElement("button");return e.type="button",e.tabIndex=-1,e.className=Ln,e.setAttribute(kn,""),e.setAttribute("aria-label",Hn),e.setAttribute("aria-hidden","true"),e.appendChild(or(n)),e}function sr(n){let e=n.style.gridTemplateColumns.trim();return e?Math.max(1,e.split(/\s+/).length):1}function Et(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 i=e.ownerDocument?.defaultView??(typeof window<"u"?window:null),r=!1,o=null,s=null,a=null,l=()=>{a!==null&&clearTimeout(a),a=null,t.removeAttribute(He)},d=p=>{if(p){l(),t.setAttribute(ae,""),t.setAttribute("aria-hidden","false");return}let m=t.hasAttribute(ae);t.removeAttribute(ae),t.setAttribute("aria-hidden","true"),!(!m||Et(t))&&(t.setAttribute(He,""),a=setTimeout(()=>{a=null,t.removeAttribute(He)},_n))},c=()=>{let p=0,m=e;for(;m&&m!==n;)p+=m.offsetTop,m=m.offsetParent instanceof HTMLElement?m.offsetParent:null;let b=i&&Number.parseFloat(i.getComputedStyle(e).paddingBottom)||0,y=n.clientHeight-(p+e.offsetHeight)+(b>0?0:nr);t.style.setProperty(Nn,`${Math.max(0,Math.round(y))}px`)},u=()=>{if(r||s!==null)return;let p=e.querySelector("[data-aia-option][data-aia-loading]")!==null,m=e.scrollHeight-e.clientHeight-e.scrollTop;d(!p&&m>tr)},f=()=>{if(r)return;c();let p=e.getAttribute("data-aia-group")??"";if(p!==o){o=p,d(!1),s!==null&&clearTimeout(s);let m=e.querySelectorAll("[data-aia-option]").length,b=Et(e)?0:Pt(m,sr(e));s=setTimeout(()=>{s=null,u()},b);return}u()},g=()=>u();e.addEventListener("scroll",g,{passive:!0});let h=p=>p.preventDefault(),x=()=>{let p=i?(Number.parseFloat(i.getComputedStyle(e).paddingTop)||0)+(Number.parseFloat(i.getComputedStyle(e).paddingBottom)||0):0,m=Math.max(1,e.clientHeight-p);rr(e,m,i,u)};t.addEventListener("mousedown",h),t.addEventListener("click",x);let S=null;return i&&typeof i.ResizeObserver=="function"&&(S=new i.ResizeObserver(()=>{c(),u()}),S.observe(e)),f(),{update:f,destroy(){r||(r=!0,s!==null&&clearTimeout(s),s=null,e.removeEventListener("scroll",g),t.removeEventListener("mousedown",h),t.removeEventListener("click",x),S?.disconnect(),l(),t.removeAttribute(ae),t.setAttribute("aria-hidden","true"))}}}var ar=[159,119,164];function Be(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 Fe=new WeakMap;function lr(n,e){let t=Fe.get(n);if(t||(t={button:Fn(n.ownerDocument),grid:null,controller:null},n.appendChild(t.button),Fe.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 Tt(n){let e=Fe.get(n);e&&(e.controller?.destroy(),Fe.delete(n))}function We(n,e){let{filteredOptions:t,activeIndex:i,isOpen:r,isLoading:o,pills:s,showPills:a,isActivePillSelected:l,onSelect:d,onHighlight:c,onPillClick:u,onSkip:f}=e,g=s.length>0,h=a&&g,x=t.length>0,S=e.products.length>0,p=r&&(x||h||o||S);if(p?n.classList.add("magicx-aia-dropdown--visible"):n.classList.remove("magicx-aia-dropdown--visible"),o?n.setAttribute("data-aia-loading",""):n.removeAttribute("data-aia-loading"),!p){xt(n,!1);return}S?n.setAttribute("data-aia-has-products",""):n.removeAttribute("data-aia-has-products");let m=n.querySelector(".aia-stack");m||(m=document.createElement("div"),m.className="aia-stack",m.style.setProperty("--aia-stack-space","8px"),n.appendChild(m));let b=e.showSkipButton&&g&&!e.isInputEmpty,y=h||o&&a||b,v=m.querySelector(".magicx-aia-pill-bar");if(y){v||(v=document.createElement("div"),v.className="magicx-aia-pill-bar aia-cluster",v.setAttribute("data-nowrap",""),v.setAttribute("data-aia-pillbar",""),m.insertBefore(v,m.firstChild));let D=v.querySelector(".magicx-aia-pill-scroll");D||(D=document.createElement("span"),D.className="magicx-aia-pill-scroll",D.setAttribute("data-aia-pill-scroll",""),v.insertBefore(D,v.firstChild)),Ne(D,a?s:[],0,u,!0,o&&a,l),cr(v,b,o||e.skipDisabled,s[0],f)}else v&&v.remove();let A=e.suggestions[0],k=A?`${A.type} ${A.text}`:"",H=P(e.formatType);Rn(m,H?[]:t,i,d,c,e.listboxId,o,k,e.optionsPosition??"below"),lr(n,m.querySelector(".aia-grid")),On(m,H?t:[],i,e.listboxId,H?e.dateView:null,{selectedIso:e.selectedDateIso,selectedRange:e.selectedDateRange,rangeStart:e.dateRangeStart},{onSelect:d,onHighlight:c,onPreviousMonth:e.onPreviousMonth,onNextMonth:e.onNextMonth});let E=m.querySelector(".magicx-aia-skeleton-bars");if(o&&!x){if(!E){E=document.createElement("div"),E.className="magicx-aia-skeleton-bars",E.setAttribute("data-aia-skeleton-bars","");for(let D of ar){let w=document.createElement("span");w.className="magicx-aia-skeleton-bar",w.style.width=`${D}px`,E.appendChild(w)}m.appendChild(E)}}else E&&E.remove();Mn(m,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange),xt(n,!0);let F=m.querySelector(".magicx-aia-footer")??pr(),de=i>=0&&!!t[i]?.is_tappable;ur(F,gt(de,e.isInputEmpty)),F.isConnected||m.appendChild(F),dr(m,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-datepicker",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"])}function dr(n,e){let t=e.map(i=>n.querySelector(`:scope > ${i}`)).filter(i=>i!==null);for(let i=0;i<t.length;i++)n.children[i]!==t[i]&&n.insertBefore(t[i],n.children[i]??null)}function cr(n,e,t,i,r){let o=n.querySelector(".magicx-aia-skip");if(!e){o?.remove();return}o||(o=document.createElement("button"),o.type="button",o.tabIndex=-1,o.className="magicx-aia-skip",o.setAttribute("data-aia-skip",""),o.textContent="skip",o.addEventListener("mousedown",s=>s.preventDefault()),n.appendChild(o)),o.setAttribute("aria-label",i?`Skip ${i.text}`:"Skip"),o.disabled=t,o.onclick=t?null:()=>r()}function ur(n,{key:e,hint:t}){let i=n.querySelector(".magicx-aia-footer-key"),r=n.querySelector(".magicx-aia-footer-hint");!i||!r||(i.textContent!==e&&(i.textContent=e),r.textContent!==t&&(r.textContent=t))}function pr(){let n=document.createElement("footer");n.className="magicx-aia-footer",n.setAttribute("data-aia-footer","");let e=document.createElement("div");e.className="aia-cluster magicx-aia-footer-row",e.setAttribute("data-align","center"),e.setAttribute("data-justify","between"),e.setAttribute("data-nowrap","");let t=document.createElement("div");t.className="aia-cluster magicx-aia-footer-hint-group",t.setAttribute("data-align","center"),t.style.setProperty("--aia-cluster-gap","5px");let i=document.createElement("kbd");i.className="magicx-aia-footer-key",i.textContent="tab";let r=document.createElement("span");r.className="magicx-aia-footer-hint",r.textContent="to select",t.append(i,r);let o=document.createElement("a");o.className="aia-cluster magicx-aia-footer-brand-link",o.setAttribute("data-align","center"),o.href=ft(),o.target="_blank",o.rel="noopener noreferrer",o.style.setProperty("--aia-cluster-gap","2px");let s=document.createElement("span");s.className="magicx-aia-footer-brand",s.textContent="AI";let a=document.createElement("span");return a.className="magicx-aia-footer-badge",a.textContent="Autocomplete",o.append(s,a),e.append(t,o),n.append(e),n}function Bn(n,e){let t=Be(e.listboxId);return n.appendChild(t),{dropdown:t}}function At(n,e,t){let i=se(e);We(n.dropdown,{suggestions:e.editingIdentified?[{type:e.editingIdentified.type,text:B(e.editingIdentified.type),required:!0,options:e.filteredOptions}]:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation||e.isSearchingOptions,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,showSkipButton:t.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:i.selectedIso,selectedDateRange:i.selectedRange,dateRangeStart:i.rangeStart,optionsPosition:t.optionsPosition??"below",onSelect:t.selectOption,onHighlight:r=>t.store.set({activeDropdownIndex:r}),onPillClick:t.setActivePill,onSkip:t.skipActivePill,onPreviousMonth:t.showPreviousMonth,onNextMonth:t.showNextMonth,onProductSelect:t.selectProduct,onProductFocusChange:r=>t.store.set({isFocused:r})})}var mr=6,fr=.3;function Wn(n){return n<=0?"0px":`${(-Math.min(fr,2*mr/n)).toFixed(3)}px`}function Ct(n){let{input:e,segments:t,newParamId:i,editingParamId:r,placeholderText:o,isFocused:s}=n,a=t.length===0;e.dataset.aiaEmpty=a?"true":"false",En(e,a?o:"");let l=t.map(S=>`${S.type}:${S.value}`).join("\0"),d=e.dataset.segKey??"",c=e.dataset.newParamId??"",u=e.dataset.editingParamId??"";if(l===d&&(i??"")===c&&(r??"")===u)return;let f=s?R(e):null;e.dataset.segKey=l,e.dataset.newParamId=i??"",e.dataset.editingParamId=r??"";let g=C(e),h=g.createDocumentFragment(),x=0;for(let S of t)if(x+=S.value.length,S.type==="completed"){let p=g.createElement("strong");p.dataset.seg="completed",p.dataset.paramId=S.param.id;let m=S.param.id===i,b=S.param.id===r,y=["magicx-aia-segment","magicx-aia-segment--completed"];m&&y.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),b&&y.push("magicx-aia-segment--editing"),p.className=y.join(" "),p.style.letterSpacing=Wn(S.value.length),p.textContent=S.value,h.appendChild(p)}else if(S.type==="identified"){let p=g.createElement("strong");p.dataset.seg="identified",p.dataset.paramId=S.param.id;let m=["magicx-aia-segment","magicx-aia-segment--completed"];S.param.id===r&&m.push("magicx-aia-segment--editing"),p.className=m.join(" "),p.style.letterSpacing=Wn(S.value.length),p.textContent=S.value,h.appendChild(p)}else h.appendChild(g.createTextNode(S.value));e.replaceChildren(h),e.dataset.aiaTextLength=String(x),f!=null&&O(e,Math.max(0,Math.min(f,x)))}var gr='<svg width="18" height="18" viewBox="0 0 18 18" fill="none" role="img" aria-label="Submit"><path d="M9 14V4M9 4L4 9M9 4L14 9" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';function Gn(){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=gr,n}function hr(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function $n(n,e){let t=e.firstElementChild;if(!t){e.removeAttribute("data-aia-pill-wrapped");return}let i=t.getBoundingClientRect(),r=n.getBoundingClientRect();i.top>=r.bottom-2?e.setAttribute("data-aia-pill-wrapped",""):e.removeAttribute("data-aia-pill-wrapped")}function Vn(n,e){let{listboxId:t}=e,i=Be(t);n.appendChild(i);let r=document.createElement("div");r.className="magicx-aia-input-wrapper",n.appendChild(r);let o=document.createElement("div");o.className="magicx-aia-editor",o.setAttribute("data-aia-editor",""),r.appendChild(o);let s=document.createElement("div");s.className="magicx-aia-input",s.setAttribute("data-aia-input",""),s.setAttribute("contenteditable",hr()?"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"),o.appendChild(s);let a=document.createElement("span");a.className="magicx-aia-pill-list-container",a.setAttribute("data-aia-pill-list-container",""),o.appendChild(a);let l=null,d=null;e.submitButton===void 0?(l=Gn(),r.appendChild(l),d=l):e.submitButton!==null&&(d=e.submitButton,d.hasAttribute("data-aia-submit")||d.setAttribute("data-aia-submit",""),r.appendChild(d));let c=new AbortController,{signal:u}=c,f=!1,g=0,h=()=>{let p=Ae(s),b=p.length>0&&p[0]!==p[0].toUpperCase()?p[0].toUpperCase()+p.slice(1):p;e.handleChange(b)},x=()=>{let p=M(s);if(!p||p.rangeCount===0)return null;let m=p.anchorNode;if(!m||!s.contains(m))return null;let v=(m.nodeType===Node.ELEMENT_NODE?m:m.parentElement)?.closest("strong[data-param-id]")?.dataset.paramId??null;return v&&mn(s,v)?null:v};if(r.addEventListener("click",p=>{p.target?.closest("[data-aia-pill]")||s.focus()},{signal:u}),s.addEventListener("input",()=>{f||(g=performance.now(),h(),e.handleCaretAfterInput(R(s)))},{signal:u}),C(s).addEventListener("selectionchange",()=>{let p=M(s);if(!p||p.rangeCount===0||!s.contains(p.anchorNode))return;let m=p.isCollapsed?x():null,b=e.store.get(),y=b.editingParam?.id??b.editingIdentified?.id??null;if(m&&m!==y){e.startEditingParam(m);return}performance.now()-g<50||e.handleCaretMove(R(s))},{signal:u}),s.addEventListener("compositionstart",()=>{f=!0},{signal:u}),s.addEventListener("compositionend",()=>{f=!1,h()},{signal:u}),s.addEventListener("beforeinput",p=>{let m=p,b=m.inputType;if(b==="insertParagraph"||b==="insertLineBreak"||b==="insertFromDrop"){p.preventDefault();return}if(b.startsWith("insert")||b.startsWith("delete")){let y=b.startsWith("delete")?"":m.data??"";e.replaceEditingRange(y)&&p.preventDefault()}},{signal:u}),s.addEventListener("paste",p=>{p.preventDefault();let m=(p.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!m)return;let b=C(s),y=M(s);if(!y||y.rangeCount===0)return;let v=y.getRangeAt(0);if(!s.contains(v.startContainer))return;v.deleteContents();let A=b.createTextNode(m);v.insertNode(A),v.setStartAfter(A),v.collapse(!0),y.removeAllRanges(),y.addRange(v),h()},{signal:u}),s.addEventListener("keydown",p=>e.handleKeyDown(p),{signal:u}),s.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:u}),s.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:u}),d&&d.addEventListener("click",p=>{let m=e.store.get();if(!(!!m.text||m.completedParams.length>0)||!e.onSubmit)return;p.stopPropagation(),e.onSubmit(q(m.text,m.completedParams,m.skippedParams,{identifiedParams:m.identifiedParams,isReady:m.isReady}))&&e.afterSubmit?.()},{signal:u}),e.autoFocus!==!1){s.focus();let p=C(s),m=M(s),b=m&&m.rangeCount>0&&s.contains(m.anchorNode);if(m&&!b){let y=p.createRange();y.selectNodeContents(s),y.collapse(!0),m.removeAllRanges(),m.addRange(y)}}if(typeof ResizeObserver<"u"){let p=new ResizeObserver(()=>$n(s,a));p.observe(s),c.signal.addEventListener("abort",()=>p.disconnect(),{once:!0})}return{input:s,inlinePillContainer:a,dropdown:i,submitButton:l,abort:c}}function Ot(n,e,t){let{input:i,inlinePillContainer:r,dropdown:o,submitButton:s}=n,{pillPlacement:a,setActivePill:l,selectOption:d,store:c}=t;i.setAttribute("aria-expanded",String(e.isDropdownOpen));let u=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(u?i.setAttribute("aria-activedescendant",u):i.removeAttribute("aria-activedescendant"),s){let p=!!e.text||e.completedParams.length>0;s.disabled=!p}let f=i.dataset.newParamId??"",g=e.newParamId!==null&&e.newParamId!==f;if(Ct({input:i,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused}),a==="inline"){let p=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;p||e.actionableSuggestions.length>0?Ne(r,e.actionableSuggestions,0,l,!1,p,e.isActivePillSelected):yt(r)}else yt(r);$n(i,r),g?(i.focus(),O(i,e.caretOffset??e.text.length)):e.isFocused&&Ae(i)!==e.text&&O(i,e.text.length);let h=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:e.editingIdentified?{type:e.editingIdentified.type,text:B(e.editingIdentified.type),required:!0,options:[]}:null,x=h??e.actionableSuggestions[0],S=se(e);We(o,{suggestions:x?[{...x,options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation||e.isSearchingOptions,listboxId:t.listboxId,pills:h?[h]:e.actionableSuggestions,showPills:a==="dropdown",showSkipButton:t.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:S.selectedIso,selectedDateRange:S.selectedRange,dateRangeStart:S.rangeStart,optionsPosition:t.optionsPosition??"below",onSelect:d,onHighlight:p=>c.set({activeDropdownIndex:p}),onPillClick:l,onSkip:t.skipActivePill,onPreviousMonth:t.showPreviousMonth,onNextMonth:t.showNextMonth,onProductSelect:t.selectProduct,onProductFocusChange:p=>c.set({isFocused:p})})}function qn(n,e){let t=n.actionableSuggestions[0];if(!t)return null;let i=n.filterBase,r=n.text.slice(0,i),o=r.length===0&&n.text.length===0,s=r.length===0&&n.text.length>0&&n.placeholderText.length>0&&n.placeholderText.toLowerCase().startsWith(n.text.toLowerCase());(o||s)&&n.placeholderText&&(r=`${n.placeholderText} `);let a=Jt(r,e.text);a>0&&(r=r.slice(0,r.length-a));let l=r.length>0&&r[r.length-1]!==" ",d=`${r}${l?" ":""}${e.text} `,c=(o||s)&&d.length>0?d[0].toUpperCase()+d.slice(1):d,u=c.toLowerCase().lastIndexOf(e.text.toLowerCase()),f=u>=0?c.slice(u,u+e.text.length):e.text,g={id:crypto.randomUUID(),placeholder:"",type:t.type,text:f,kind:e.kind,suggestionType:t.type,suggestionPlaceholder:t.text,options:t.options??[],metadata:e.metadata},h=n.actionableSuggestions.length-1;return{patch:{text:c,filterBase:c.length,completedParams:[...n.completedParams,g],newParamId:g.id,caretOffset:c.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:!0,inSelectionAnimation:!0,pendingSpan:null},telemetry:{selectedOption:e.text,otherOptions:n.filteredOptions.filter(x=>x.text!==e.text).map(x=>x.text)},consumedSuggestion:t,remainingActionable:h}}function It(n){let e=n,t=new Set,i=[],r=!1;return{get:()=>e,set:o=>{let s=typeof o=="function"?o(e):o,a=e;if(e={...e,...s},i.push([e,a]),!r){r=!0;try{let l=0;for(let d=i.shift();d;d=i.shift()){if(++l>1e4)throw i.length=0,new Error("createStore: notifications did not settle after 10000 deliveries \u2014 a listener is likely calling set() on every notification");let[c,u]=d;for(let f of t)f(c,u)}}catch(l){throw i.length=0,l}finally{r=!1}}},subscribe:o=>(t.add(o),()=>{t.delete(o)})}}function Kn(n,e){let t,i,r=o=>(o!==t&&(t=o,i=e(o)),i);return{get:()=>{let o=n.get();return{...o,...r(o)}},set:o=>{typeof o=="function"?n.set(s=>{let a={...s,...r(s)};return o(a)}):n.set(o)},peek:o=>{let s={...n.get(),...o};return{...s,...e(s)}},subscribe:o=>n.subscribe((s,a)=>{let l={...a,...r(a)},d={...s,...r(s)};o(d,l)})}}var Dt=new WeakSet,Un=new WeakMap;function Yn(n){return n.nodeType===Node.DOCUMENT_NODE}function br(n){return Yn(n)?n:n.ownerDocument}function yr(n){let e=Un.get(n);if(e)return e;let t=n.defaultView?.CSSStyleSheet;if(typeof t!="function")return null;try{let i=new t;return typeof i.replaceSync!="function"?null:(i.replaceSync(zn),Un.set(n,i),i)}catch{return null}}function Qn(n,e){if(e.querySelector("style[data-magicx-aia]"))return;let t=n.createElement("style");t.setAttribute("data-magicx-aia",""),t.textContent=zn,e.appendChild(t)}function jn(n){if(typeof document>"u")return;let e=n??document;if(Dt.has(e))return;let t=br(e);if(Yn(e)){let o=e.head??e.documentElement;if(!o)return;Qn(t,o),Dt.add(e);return}let i=yr(t),r=e.adoptedStyleSheets;i&&Array.isArray(r)?r.includes(i)||(e.adoptedStyleSheets=[...r,i]):Qn(t,e),Dt.add(e)}var zn=`@layer layout {
|
|
2
2
|
.aia-stack {
|
|
3
3
|
display: flex;
|
|
4
4
|
flex-direction: column;
|
|
@@ -1258,6 +1258,13 @@ function Ne(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9
|
|
|
1258
1258
|
var(--aia-date-today-ring, var(--aia-option-color, var(--aia-color-text-muted, #c1c4cb)));
|
|
1259
1259
|
}
|
|
1260
1260
|
|
|
1261
|
+
/* Between the two ends of a picked span. The band sits on the CELL, not on the
|
|
1262
|
+
number square inside it, so consecutive days join into one continuous strip
|
|
1263
|
+
instead of a row of separate pills \u2014 the ends stay the two filled squares. */
|
|
1264
|
+
.magicx-aia-date-cell--in-range {
|
|
1265
|
+
background: var(--aia-date-range-bg, rgba(var(--aia-streak-rgb, 255, 255, 255), 0.06));
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1261
1268
|
.magicx-aia-date-cell--selected .magicx-aia-date-cell-number {
|
|
1262
1269
|
color: var(--aia-option-color-selected, var(--aia-color-text-default, #fff));
|
|
1263
1270
|
background: var(--aia-date-selected-bg, rgba(var(--aia-streak-rgb, 255, 255, 255), 0.12));
|
|
@@ -1606,5 +1613,5 @@ function Ne(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9
|
|
|
1606
1613
|
background: var(--aia-surface, #ffffff);
|
|
1607
1614
|
}
|
|
1608
1615
|
}
|
|
1609
|
-
`;var ke=class{constructor(){this.reported=new Set}run(e,t){try{return t()}catch(i){this.report(e,i,e);return}}runListener(e,t,i=e){try{return t(),!0}catch(r){return this.report(e,r,i),!1}}report(e,t,i){this.reported.has(i)||(this.reported.add(i),console.error(`[AIAutocomplete] "${e}" threw. The error is contained \u2014 SDK state is unaffected. Later failures of "${e}" on this instance are not logged.`,t))}};var Re=class{constructor(e){this.boundary=e;this.listeners={};this.keys=new WeakMap;this.registrationCount=0}on(e,t){let i=`${String(e)}#${++this.registrationCount}`,r=(...s)=>t(...s);this.keys.set(r,i);let o=this.listeners[e];return o||(o=new Set,this.listeners[e]=o),o.add(r),()=>{this.listeners[e]?.delete(r)}}emit(e,...t){let i=this.listeners[e];if(!i)return!0;let r=!0;for(let o of i)this.boundary.runListener(String(e),()=>o(...t),this.keys.get(o)??String(e))||(r=!1);return r}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var _e=class{constructor(){this.timers=new Map}schedule(e,t,i){this.clear(e);let r=setTimeout(()=>{this.timers.delete(e),t()},i);this.timers.set(e,r)}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 ee=class{constructor(e,t="auto",i){this.container=e;this.mode=t;this.onResolve=i;this.mediaQuery=null;this.onSystemChange=e=>{this.setResolved(e.matches?"dark":"light")};this.apply()}setMode(e){this.detachListener(),this.mode=e,this.apply()}destroy(){this.detachListener()}apply(){this.mode==="auto"?(this.mediaQuery??(this.mediaQuery=window.matchMedia("(prefers-color-scheme: dark)")),this.mediaQuery.addEventListener("change",this.onSystemChange),this.setResolved(this.mediaQuery.matches?"dark":"light")):this.setResolved(this.mode)}setResolved(e){this.container.dataset.mode=e,this.onResolve?.(e)}detachListener(){this.mediaQuery?.removeEventListener("change",this.onSystemChange)}};function Xi(n){return(n??se).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function Ji(n){return z(n)?`Bearer ${await ae(n).getToken()}`:de(n)}async function kn(n){try{let e=Xi(n.apiConfig?.endpoint),t=le(n.apiConfig),i=await Ji(n.apiConfig);i&&(t.Authorization=i);let r=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:r})}catch{}}var Zi="newParam",Rn="suggestionRemoval",er="selectionAnimation",tr=650,nr=0;function ir(){return`:ac-${++nr}:`}var _n=170;function Nn(){return{text:"",completedParams:[],identifiedParams:[],skippedParams:[],pendingSpan:null,suggestions:[],products:[],optionSearch:null,activeDropdownIndex:-1,newParamId:null,isLoading:!1,isReady:!1,error:null,filterBase:0,filterInProgress:!1,pillTapped:!1,skipNextFetch:!1,lastRawQuery:"",isFocused:!1,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:null,inSelectionAnimation:!1,dateViewMonth:null,editingIdentified:null}}var yt=class{constructor(e,t={}){this.inputStore=ht(Nn());this._listboxId=ir();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new _e;this.boundary=new ke;this.subscriberCount=0;this.emitter=new Re(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=An(this.inputStore,i=>en(i,this.opts)),t.onSubmit&&this.emitter.on("submit",t.onSubmit),t.onResult&&this.emitter.on("result",t.onResult),t.onError&&this.emitter.on("error",t.onError),t.onChange&&this.emitter.on("change",t.onChange),t.onParamsChange&&this.emitter.on("paramsChange",t.onParamsChange),t.onStateChange&&this.emitter.on("stateChange",t.onStateChange),t.onFocus&&this.emitter.on("focus",t.onFocus),t.onBlur&&this.emitter.on("blur",t.onBlur),t.onProductSelect&&this.emitter.on("productSelect",t.onProductSelect),t.value!==void 0&&this.store.set({text:t.value}),t.completedParams!==void 0&&this.store.set({completedParams:t.completedParams}),this.pillsController=new ve(this.store,{onPillSelected:({rawQuery:i,selectedPill:r,otherPills:o})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:r,other_pills:o})}}),this.reEdit=new Ce({store:this.store,scheduleSetCursor:i=>this.scheduleSetCursor(i),fireTelemetry:(i,r)=>this.fireTelemetry(i,r),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer(),fetchNow:()=>this.fetchNow()}),this.productsController=new Pe(this.store,()=>this.opts.products),this.optionSource=new Se(this.store,()=>this.opts.optionOverrides,{onAnswer:i=>{i==="edit"?this.reEdit.promoteIfExact():this.maybePromoteExactMatch(this.store.get().text)},onMiss:(i,r)=>{i==="pill"&&r.length>0&&this.fetchController.attemptNow()}}),this.fetchController=new pe(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.emitter.hasListeners("error")?this.emitError:void 0,()=>this.sessionId,()=>this.opts.additionalContext,{onRequest:({query:i,signal:r,isCurrent:o})=>{this.productsController.run(i,r,o).catch(()=>{})},onAutoMatch:({active:i,matched:r,rawQuery:o})=>{this.fireTelemetry("option",{raw_query:o,selected_option:r.text,other_options:(i.options??[]).filter(s=>s.text!==r.text).map(s=>s.text)})},onResponse:()=>{this.emitter.hasListeners("result")&&this.emitter.emit("result",this.buildResult())},consumerTick:(i,r)=>this.optionSource.tick(i,r)}),this.keyboardController=new xe(this.store,{columns:t.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.emitter.hasListeners("submit")?this.emitSubmit:void 0,getOptionsPosition:()=>this.opts.optionsPosition??"below",afterSubmit:this.renderMode==="full"?()=>this.reset():void 0,selectOption:i=>this.selectOption(i),removeParamAtCaret:i=>this.removeParamAtCaret(i),startEditingParamAtCaret:i=>this.startEditingParamAtCaret(i),exitEditMode:()=>this.exitEditMode(),exitEditingIdentified:()=>this.exitEditingIdentified(),skipActivePill:()=>this.skipActivePill()}),this.unsubscribers.push(this.store.subscribe((i,r)=>{i.text!==r.text&&this.emitter.emit("change",i.text),i.completedParams!==r.completedParams&&this.emitter.emit("paramsChange",i.completedParams),i.isFocused!==r.isFocused&&(i.isFocused?this.emitter.emit("focus"):this.emitter.emit("blur")),this.emitter.emit("stateChange",i)})),this.unsubscribers.push(this.store.subscribe(()=>this.maybeExitReEditOnNoMatch())),this.unsubscribers.push(this.store.subscribe((i,r)=>{if(i.text===r.text&&i.completedParams===r.completedParams||i.identifiedParams.length===0)return;let{valid:o,invalid:s}=ue(i.text,i.completedParams,i.identifiedParams);s.length>0&&this.store.set({identifiedParams:o})})),this.unsubscribers.push(this.store.subscribe((i,r)=>{if(i.identifiedParams===r.identifiedParams)return;let o=i.editingIdentified;if(!o||i.identifiedParams.some(d=>d.id===o.id))return;let s=0,a;for(let d of i.segments){if(d.type==="identified"&&s===o.anchor&&d.value===o.text){a=d.param;break}s+=d.value.length}if(a){this.store.set({editingIdentified:{...o,id:a.id}});return}this.store.set({editingIdentified:null,activeDropdownIndex:-1})})),this.unsubscribers.push(this.store.subscribe((i,r)=>{let o=i.pendingSpan;if(!o||i.text===r.text&&i.completedParams===r.completedParams&&i.identifiedParams===r.identifiedParams)return;let s=o.anchor;if(i.text!==r.text){let d=Wt(r.text,i.text,s);if(d===null){this.store.set({pendingSpan:null});return}s=d}i.text.slice(s).trim().length===0||Ft(i.segments,s)?this.store.set({pendingSpan:null}):s!==o.anchor&&this.store.set({pendingSpan:{anchor:s,snapshot:o.snapshot}})})),this.renderMode!=="headless"&&(Ln(this.opts.styleRoot??me(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({...Nn(),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&&(sn(this.domRefs.input),pt(this.domRefs.dropdown)),this.dropdownRefs&&pt(this.dropdownRefs.dropdown),this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}setValue(e){let t=this.store.get();if(t.editingIdentified&&e!==t.text){this.store.set({text:e,editingIdentified:null,activeDropdownIndex:-1});return}this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e);let t=this.store.get().text.length;this.store.set({caretOffset:t,isFocused:!0}),this.scheduleSetCursor(t)}removeLastParam(){this.pillsController.removeLastParam()}findChipSpanAt(e){let t=0;for(let i of this.store.get().segments){let r=t;if(t+=i.value.length,i.type!=="text"&&e>r&&e<=t)return{kind:i.type,param:i.param,start:r,end:t}}return null}withoutChip(e,t){return t.kind==="completed"?{completedParams:e.completedParams.filter(i=>i.id!==t.param.id)}:{identifiedParams:e.identifiedParams.filter(i=>i.id!==t.param.id)}}removeParamAtCaret(e){let t=this.findChipSpanAt(e);if(!t)return!1;let{text:i}=this.store.get(),{start:r,end:o}=t;if(e===o){let{text:d,removed:l}=Te(i,r,o);return this.store.set(c=>({text:d,filterBase:Math.min(c.filterBase>r?Math.max(r,c.filterBase-l):c.filterBase,d.length),...this.withoutChip(c,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(r),!0}let s=Ye(i,e),a=i.slice(0,s)+i.slice(e);return this.store.set(d=>({text:a,filterBase:Math.min(d.filterBase,a.length),...this.withoutChip(d,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(),O(t.input,e);else{let i=this.opts.setCursor;i&&this.boundary.runListener("setCursor",()=>i(e))}})}clearNewParamId(){this.store.set({newParamId:null})}startEditingIdentified(e){let t=this.store.get();if(t.editingIdentified?.id===e)return!0;let i=t.identifiedParams.find(a=>a.id===e);if(!i||H(i)!=="date")return!1;let r=0,o=-1;for(let a of t.segments){if(a.type!=="text"&&a.param.id===e){o=r;break}r+=a.value.length}if(o<0)return!1;let s=o+i.text.length;return this.store.set({editingIdentified:{id:e,type:i.type,anchor:o,tail:s,text:i.text,iso:qe(i)},editingParam:null,editingAnchor:null,editingTail:null,caretOffset:s,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(t.activeFormatType!=="date"||!t.dateView)return;let i=We(t.dateView,e);this.store.set({dateViewMonth:{...i,key:nt(t)},activeDropdownIndex:-1})}skipActivePill(){let e=this.store.get();if(e.editingParam||e.inSelectionAnimation)return;let t=e.suggestions.filter(a=>a.type==="placeholder"),i=e.suggestions.filter(a=>a.type!=="placeholder");if(i.length===0)return;let r=i[0],o=i.slice(1),s=e.skippedParams.some(a=>a.type===r.type);this.store.set({suggestions:[...t,...o],pillTapped:o.length>0,activeDropdownIndex:-1,...s?{}:{skippedParams:[...e.skippedParams,{id:crypto.randomUUID(),type:r.type,suggestionPlaceholder:r.text}]}}),o.length===0&&this.fetchNow()}handleKeyDown(e){this.keyboardController.handleKeyDown(e)}setFocused(e){this.store.get().isFocused!==e&&this.store.set({isFocused:e})}subscribe(e){let t=`subscribe#${++this.subscriberCount}`;return this.store.subscribe(i=>{this.boundary.runListener("subscribe",()=>e(i),t)})}getState(){return this.store.get()}getResult(){return this.buildResult()}buildResult(){let e=this.store.get();return W(e.text,e.completedParams,e.skippedParams,{identifiedParams:e.identifiedParams,isReady:e.isReady})}get listboxId(){return this._listboxId}get isReady(){return this.store.get().isReady}on(e,t){return this.emitter.on(e,t)}update(e){let t=this.opts.products,i=this.opts.optionOverrides;Object.assign(this.opts,e),"optionOverrides"in e&&e.optionOverrides!==i&&this.optionSource.refresh(),"products"in e&&e.products!==t&&this.productsController.clearNow(),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)&&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.editingIdentified){this.commitIdentifiedDate(e);return}if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null){this.reEdit.selectOption(e);return}let i=Cn(t,e);if(i){if(this.fireTelemetry("option",{raw_query:T(t.text,t.completedParams).rawQuery,selected_option:i.telemetry.selectedOption,other_options:t.activeFormatType==="date"?[]:i.telemetry.otherOptions}),this.store.set(i.patch),this.startSelectionAnimationTimer(),this.timers.clear(Rn),i.remainingActionable>0){let r=i.consumedSuggestion;this.timers.schedule(Rn,()=>{this.store.get().suggestions.includes(r)&&this.store.set(o=>({suggestions:o.suggestions.filter(s=>s!==r)}))},_n)}this.fetchNow()}}startSelectionAnimationTimer(){this.timers.schedule(er,()=>this.store.set({inSelectionAnimation:!1}),_n)}fireTelemetry(e,t){let i=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");kn({source:i,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}setupContainer(){this.container.classList.add("magicx-aia"),this.container.dataset.pillPlacement=this.renderMode==="dropdown"?"dropdown":this.opts.pillPlacement??"dropdown",this.container.dataset.optionsPosition=this.opts.optionsPosition??"below",this.container.dataset.animations=this.opts.animations??!0?"on":"off",this.modeController=new ee(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 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:r=>this.selectOption(r),setActivePill:r=>this.pillsController.setActivePill(r),skipActivePill:()=>this.skipActivePill(),selectProduct:r=>this.selectProduct(r),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth(),handleKeyDown:r=>this.keyboardController.handleKeyDown(r),handleChange:r=>this.handleChange(r),startEditingParam:r=>this.startEditingParam(r),handleCaretAfterInput:r=>this.handleCaretAfterInput(r),handleCaretMove:r=>this.handleCaretMove(r),replaceEditingRange:r=>this.replaceEditingRange(r)};this.domRefs=Tn(this.container,t);let i=()=>{this.domRefs&>(this.domRefs,this.store.get(),t)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),gt(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 optionsPosition(){return e.opts.optionsPosition??"below"},selectOption:r=>this.selectOption(r),setActivePill:r=>this.pillsController.setActivePill(r),skipActivePill:()=>this.skipActivePill(),selectProduct:r=>this.selectProduct(r),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth()};this.dropdownRefs=vn(this.container,t);let i=()=>{this.dropdownRefs&&mt(this.dropdownRefs,this.store.get(),t)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),mt(this.dropdownRefs,this.store.get(),t),this.subscribeNewParamTimer()}subscribeViewportBreakpoint(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;let t=window.matchMedia(Ee),i=()=>e();t.addEventListener("change",i),this.unsubscribers.push(()=>t.removeEventListener("change",i))}subscribeBatchedRender(e){let t=!1;this.unsubscribers.push(this.store.subscribe(()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,t)=>{e.newParamId&&e.newParamId!==t.newParamId&&this.timers.schedule(Zi,()=>this.store.set({newParamId:null}),tr)}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:r}=qt(e,t.completedParams);r.length>0&&this.store.set({completedParams:i}),this.maybePromoteExactMatch(e),this.maybeOpenPendingSpan()}maybeOpenPendingSpan(){let e=this.store.get();if(e.pendingSpan||e.actionableSuggestions.length===0)return;let t=k(e.text,Math.min(e.filterBase,e.text.length),e.placeholderText),i=Ht(e.segments,t);e.text.slice(i).trim().length!==0&&this.store.set({pendingSpan:{anchor:i,snapshot:e.actionableSuggestions}})}maybeExitReEditOnNoMatch(){let e=this.store.get();if(!e.editingParam||e.editingAnchor==null||e.completedParams.some(o=>o.id===e.editingParam?.id)||this.optionSource.owns(e.editingParam.suggestionType,e.optionQuery))return;let t=e.caretOffset??e.editingAnchor,i=e.text.slice(e.editingAnchor,t);B(e.editingParam.options,i).some(o=>o.is_tappable)||(this.reEdit.exit(),this.fetchNow())}fetchNow(){let e=this.store.get(),{rawQuery:t,completedParams:i}=T(e.text,e.completedParams);this.fetchController.doFetch(t,i)}commitIdentifiedDate(e){let t=this.store.get(),i=t.editingIdentified;if(!i)return;if(t.text.slice(i.anchor,i.tail)!==i.text){this.store.set({editingIdentified:null,activeDropdownIndex:-1});return}let r=t.text.slice(0,i.anchor),o=t.text.slice(i.tail),s=i.anchor===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,d=o.length===0||o[0]!==" "?`${s} `:s,l=r+d+o,c=l.length,u={id:crypto.randomUUID(),placeholder:"",type:i.type,text:s,kind:e.kind,suggestionType:i.type,suggestionPlaceholder:N(i.type),options:[],metadata:e.metadata};this.fireTelemetry("option",{raw_query:T(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:[]}),this.store.set({text:l,completedParams:[...t.completedParams,u],identifiedParams:t.identifiedParams.filter(f=>f.id!==i.id),newParamId:u.id,filterBase:c,caretOffset:c,editingIdentified:null,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.startSelectionAnimationTimer(),this.scheduleSetCursor(c),this.fetchNow()}maybePromoteExactMatch(e){let t=this.store.get();if(t.activeFormatType==="date")return;let i=we({mode:"fresh",text:e,completedParams:t.completedParams,suggestions:t.suggestions,filterBase:t.filterBase,filterInProgress:t.filterInProgress});i&&this.store.set(i.patch)}};export{yt as AIAutocomplete,an as ATTRIBUTION_URL,ee as ModeController,Ee as OPTIONS_GRID_MOBILE_QUERY,at as OPTION_ENTER_DELAY_VAR,Ci as OPTION_ENTER_FADE_MS,Ai as OPTION_ENTER_RISE_MS,Oi as OPTION_ENTER_RISE_PX,Ti as OPTION_ENTER_STAGGER_MS,hi as PLACEHOLDER_FADE_OUT_MS,K as PLACEHOLDER_LEAVING_ATTR,bi as PLACEHOLDER_SWAP_GAP_MS,fi as PLACEHOLDER_TYPE_MS,gi as PLACEHOLDER_WORD_PAUSE_MS,hn as SCROLL_ARROW_ATTR,yn as SCROLL_ARROW_BOTTOM_VAR,gn as SCROLL_ARROW_CLASS,xn as SCROLL_ARROW_LABEL,bn as SCROLL_ARROW_LEAVE_MS,Ie as SCROLL_ARROW_LEAVING_ATTR,Z as SCROLL_ARROW_VISIBLE_ATTR,Lt as SKIPPED_PARAM_TEXT,te as WEEKDAY_LABELS,We as addMonths,ut as attachScrollArrow,it as buildAttributionUrl,Ge as buildDateOptions,T as buildQuery,W as buildSubmitResult,Ve as cellDay,V as cellIso,zt as computeOptionsGridLayout,ht as createStore,Qe as cursorIsAtEnd,ye as extractPlainText,Tt as formatDate,L as getCursorOffset,rt as getFooterHint,N as identifiedParamLabel,tt as isOptionsGridMobileViewport,I as isoDate,et as measureOptionsGrid,Fe as monthLabel,Je as needsOptionsGridMeasurement,lt as optionEnterDelayMs,dt as optionsEntranceDurationMs,Jt as optionsGridTemplateColumns,ne as parseDate,re as parseLooseDate,Ue as plainTextLength,Ze as planOptionsGrid,Ye as previousGraphemeBoundary,ft as renderEditableContent,H as resolveFormatType,qe as resolveIdentifiedDate,Ke as scrollCaretIntoView,j as selectedIsoFromText,O as setCursorOffset,X as toWireIdentifiedParams,J as withSkippedParams};
|
|
1616
|
+
`;var Ge=class{constructor(){this.reported=new Set}run(e,t){try{return t()}catch(i){this.report(e,i,e);return}}runListener(e,t,i=e){try{return t(),!0}catch(r){return this.report(e,r,i),!1}}report(e,t,i){this.reported.has(i)||(this.reported.add(i),console.error(`[AIAutocomplete] "${e}" threw. The error is contained \u2014 SDK state is unaffected. Later failures of "${e}" on this instance are not logged.`,t))}};var $e=class{constructor(e){this.boundary=e;this.listeners={};this.keys=new WeakMap;this.registrationCount=0}on(e,t){let i=`${String(e)}#${++this.registrationCount}`,r=(...s)=>t(...s);this.keys.set(r,i);let o=this.listeners[e];return o||(o=new Set,this.listeners[e]=o),o.add(r),()=>{this.listeners[e]?.delete(r)}}emit(e,...t){let i=this.listeners[e];if(!i)return!0;let r=!0;for(let o of i)this.boundary.runListener(String(e),()=>o(...t),this.keys.get(o)??String(e))||(r=!1);return r}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var Ve=class{constructor(){this.timers=new Map}schedule(e,t,i){this.clear(e);let r=setTimeout(()=>{this.timers.delete(e),t()},i);this.timers.set(e,r)}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 le=class{constructor(e,t="auto",i){this.container=e;this.mode=t;this.onResolve=i;this.mediaQuery=null;this.onSystemChange=e=>{this.setResolved(e.matches?"dark":"light")};this.apply()}setMode(e){this.detachListener(),this.mode=e,this.apply()}destroy(){this.detachListener()}apply(){this.mode==="auto"?(this.mediaQuery??(this.mediaQuery=window.matchMedia("(prefers-color-scheme: dark)")),this.mediaQuery.addEventListener("change",this.onSystemChange),this.setResolved(this.mediaQuery.matches?"dark":"light")):this.setResolved(this.mode)}setResolved(e){this.container.dataset.mode=e,this.onResolve?.(e)}detachListener(){this.mediaQuery?.removeEventListener("change",this.onSystemChange)}};function xr(n){return(n??fe).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function Sr(n){return ne(n)?`Bearer ${await ge(n).getToken()}`:be(n)}async function Xn(n){try{let e=xr(n.apiConfig?.endpoint),t=he(n.apiConfig),i=await Sr(n.apiConfig);i&&(t.Authorization=i);let r=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:r})}catch{}}var vr="newParam",Jn="suggestionRemoval",Pr="selectionAnimation",Er=650,wr=0;function Tr(){return`:ac-${++wr}:`}var Zn=170;function ei(){return{text:"",completedParams:[],identifiedParams:[],skippedParams:[],pendingSpan:null,suggestions:[],products:[],optionSearch:null,activeDropdownIndex:-1,newParamId:null,isLoading:!1,isReady:!1,error:null,filterBase:0,filterInProgress:!1,pillTapped:!1,skipNextFetch:!1,lastRawQuery:"",isFocused:!1,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:null,inSelectionAnimation:!1,dateViewMonth:null,pendingRangeStart:null,editingIdentified:null}}var Mt=class{constructor(e,t={}){this.inputStore=It(ei());this._listboxId=Tr();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new Ve;this.boundary=new Ge;this.subscriberCount=0;this.emitter=new $e(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=Kn(this.inputStore,i=>xn(i,this.opts)),t.onSubmit&&this.emitter.on("submit",t.onSubmit),t.onResult&&this.emitter.on("result",t.onResult),t.onError&&this.emitter.on("error",t.onError),t.onChange&&this.emitter.on("change",t.onChange),t.onParamsChange&&this.emitter.on("paramsChange",t.onParamsChange),t.onStateChange&&this.emitter.on("stateChange",t.onStateChange),t.onFocus&&this.emitter.on("focus",t.onFocus),t.onBlur&&this.emitter.on("blur",t.onBlur),t.onProductSelect&&this.emitter.on("productSelect",t.onProductSelect),t.value!==void 0&&this.store.set({text:t.value}),t.completedParams!==void 0&&this.store.set({completedParams:t.completedParams}),this.pillsController=new Ie(this.store,{onPillSelected:({rawQuery:i,selectedPill:r,otherPills:o})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:r,other_pills:o})}}),this.reEdit=new ke({store:this.store,scheduleSetCursor:i=>this.scheduleSetCursor(i),fireTelemetry:(i,r)=>this.fireTelemetry(i,r),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer(),fetchNow:()=>this.fetchNow()}),this.productsController=new De(this.store,()=>this.opts.products),this.optionSource=new Oe(this.store,()=>this.opts.optionOverrides,{onAnswer:i=>{i==="edit"?this.reEdit.promoteIfExact():this.maybePromoteExactMatch(this.store.get().text)},onMiss:(i,r)=>{i==="pill"&&r.length>0&&this.fetchController.attemptNow()}}),this.fetchController=new Se(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.emitter.hasListeners("error")?this.emitError:void 0,()=>this.sessionId,()=>this.opts.additionalContext,{onRequest:({query:i,signal:r,isCurrent:o})=>{this.productsController.run(i,r,o).catch(()=>{})},onAutoMatch:({active:i,matched:r,rawQuery:o})=>{this.fireTelemetry("option",{raw_query:o,selected_option:r.text,other_options:(i.options??[]).filter(s=>s.text!==r.text).map(s=>s.text)})},onResponse:()=>{this.emitter.hasListeners("result")&&this.emitter.emit("result",this.buildResult())},consumerTick:(i,r)=>this.optionSource.tick(i,r)}),this.keyboardController=new Ce(this.store,{columns:t.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.emitter.hasListeners("submit")?this.emitSubmit:void 0,getOptionsPosition:()=>this.opts.optionsPosition??"below",afterSubmit:this.renderMode==="full"?()=>this.reset():void 0,selectOption:i=>this.selectOption(i),removeParamAtCaret:i=>this.removeParamAtCaret(i),startEditingParamAtCaret:i=>this.startEditingParamAtCaret(i),exitEditMode:()=>this.exitEditMode(),exitEditingIdentified:()=>this.exitEditingIdentified(),skipActivePill:()=>this.skipActivePill()}),this.unsubscribers.push(this.store.subscribe((i,r)=>{i.text!==r.text&&this.emitter.emit("change",i.text),i.completedParams!==r.completedParams&&this.emitter.emit("paramsChange",i.completedParams),i.isFocused!==r.isFocused&&(i.isFocused?this.emitter.emit("focus"):this.emitter.emit("blur")),this.emitter.emit("stateChange",i)})),this.unsubscribers.push(this.store.subscribe(()=>this.maybeExitReEditOnNoMatch())),this.unsubscribers.push(this.store.subscribe((i,r)=>{if(i.text===r.text&&i.completedParams===r.completedParams||i.identifiedParams.length===0)return;let{valid:o,invalid:s}=xe(i.text,i.completedParams,i.identifiedParams);s.length>0&&this.store.set({identifiedParams:o})})),this.unsubscribers.push(this.store.subscribe((i,r)=>{if(i.identifiedParams===r.identifiedParams)return;let o=i.editingIdentified;if(!o||i.identifiedParams.some(l=>l.id===o.id))return;let s=0,a;for(let l of i.segments){if(l.type==="identified"&&s===o.anchor&&l.value===o.text){a=l.param;break}s+=l.value.length}if(a){this.store.set({editingIdentified:{...o,id:a.id}});return}this.store.set({editingIdentified:null,activeDropdownIndex:-1})})),this.unsubscribers.push(this.store.subscribe(i=>{let r=i.pendingRangeStart;!r||r.key===oe(i)||this.store.set({pendingRangeStart:null})})),this.unsubscribers.push(this.store.subscribe((i,r)=>{let o=i.pendingSpan;if(!o||i.text===r.text&&i.completedParams===r.completedParams&&i.identifiedParams===r.identifiedParams)return;let s=o.anchor;if(i.text!==r.text){let l=rn(r.text,i.text,s);if(l===null){this.store.set({pendingSpan:null});return}s=l}i.text.slice(s).trim().length===0||tn(i.segments,s)?this.store.set({pendingSpan:null}):s!==o.anchor&&this.store.set({pendingSpan:{anchor:s,snapshot:o.snapshot}})})),this.renderMode!=="headless"&&(jn(this.opts.styleRoot??ve(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({...ei(),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&&(wn(this.domRefs.input),Tt(this.domRefs.dropdown)),this.dropdownRefs&&Tt(this.dropdownRefs.dropdown),this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}setValue(e){let t=this.store.get();if(t.editingIdentified&&e!==t.text){this.store.set({text:e,editingIdentified:null,activeDropdownIndex:-1});return}this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e);let t=this.store.get().text.length;this.store.set({caretOffset:t,isFocused:!0}),this.scheduleSetCursor(t)}removeLastParam(){this.pillsController.removeLastParam()}findChipSpanAt(e){let t=0;for(let i of this.store.get().segments){let r=t;if(t+=i.value.length,i.type!=="text"&&e>r&&e<=t)return{kind:i.type,param:i.param,start:r,end:t}}return null}withoutChip(e,t){return t.kind==="completed"?{completedParams:e.completedParams.filter(i=>i.id!==t.param.id)}:{identifiedParams:e.identifiedParams.filter(i=>i.id!==t.param.id)}}removeParamAtCaret(e){let t=this.findChipSpanAt(e);if(!t)return!1;let{text:i}=this.store.get(),{start:r,end:o}=t;if(e===o){let{text:l,removed:d}=Le(i,r,o);return this.store.set(c=>({text:l,filterBase:Math.min(c.filterBase>r?Math.max(r,c.filterBase-d):c.filterBase,l.length),...this.withoutChip(c,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(r),!0}let s=st(i,e),a=i.slice(0,s)+i.slice(e);return this.store.set(l=>({text:a,filterBase:Math.min(l.filterBase,a.length),...this.withoutChip(l,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(s),!0}startEditingParamAtCaret(e){let t=this.findChipSpanAt(e);return!t||t.kind!=="completed"||t.end!==e?!1:(this.reEdit.start(t.param.id),this.store.get().editingParam?.id===t.param.id)}scheduleSetCursor(e){queueMicrotask(()=>{let t=this.domRefs;if(t)t.input.focus(),O(t.input,e);else{let i=this.opts.setCursor;i&&this.boundary.runListener("setCursor",()=>i(e))}})}clearNewParamId(){this.store.set({newParamId:null})}startEditingIdentified(e){let t=this.store.get();if(t.editingIdentified?.id===e)return!0;let i=t.identifiedParams.find(c=>c.id===e);if(!i)return!1;let r=G(i);if(!P(r))return!1;let o=Y(i.text),s=r==="date-range"||o?"date-range":"date",a=0,l=-1;for(let c of t.segments){if(c.type!=="text"&&c.param.id===e){l=a;break}a+=c.value.length}if(l<0)return!1;let d=l+i.text.length;return this.store.set({editingIdentified:{id:e,type:i.type,anchor:l,tail:d,text:i.text,iso:o?o.start:Je(i),isoEnd:o?o.end:null,format:s},editingParam:null,editingAnchor:null,editingTail:null,caretOffset:d,activeDropdownIndex:-1,pillTapped:!0}),!0}exitEditingIdentified(){this.store.get().editingIdentified&&this.store.set({editingIdentified:null,activeDropdownIndex:-1})}startEditingParam(e){this.reEdit.start(e),this.store.get().editingParam?.id!==e&&this.startEditingIdentified(e)}replaceEditingRange(e){return this.reEdit.replaceRange(e)}exitEditMode(){this.reEdit.exit()}handleCaretAfterInput(e){this.reEdit.caretAfterInput(e)}handleCaretMove(e){let t=this.store.get().editingIdentified;t&&e!=null&&(e<t.anchor||e>t.tail)&&this.store.set({editingIdentified:null,activeDropdownIndex:-1}),this.reEdit.caretMove(e)}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}selectProduct(e){this.emitter.emit("productSelect",e)}handleTextChange(e){this.store.get().editingIdentified&&this.store.set({editingIdentified:null,activeDropdownIndex:-1}),this.handleChange(e)}showPreviousMonth(){this.pageDateView(-1)}showNextMonth(){this.pageDateView(1)}pageDateView(e){let t=this.store.get();if(!P(t.activeFormatType)||!t.dateView)return;let i=Ye(t.dateView,e);this.store.set({dateViewMonth:{...i,key:oe(t)},activeDropdownIndex:-1})}skipActivePill(){let e=this.store.get();if(e.editingParam||e.inSelectionAnimation)return;let t=e.suggestions.filter(a=>a.type==="placeholder"),i=e.suggestions.filter(a=>a.type!=="placeholder");if(i.length===0)return;let r=i[0],o=i.slice(1),s=e.skippedParams.some(a=>a.type===r.type);this.store.set({suggestions:[...t,...o],pillTapped:o.length>0,activeDropdownIndex:-1,...s?{}:{skippedParams:[...e.skippedParams,{id:crypto.randomUUID(),type:r.type,suggestionPlaceholder:r.text}]}}),o.length===0&&this.fetchNow()}handleKeyDown(e){this.keyboardController.handleKeyDown(e)}setFocused(e){this.store.get().isFocused!==e&&this.store.set({isFocused:e})}subscribe(e){let t=`subscribe#${++this.subscriberCount}`;return this.store.subscribe(i=>{this.boundary.runListener("subscribe",()=>e(i),t)})}getState(){return this.store.get()}getResult(){return this.buildResult()}buildResult(){let e=this.store.get();return q(e.text,e.completedParams,e.skippedParams,{identifiedParams:e.identifiedParams,isReady:e.isReady})}get listboxId(){return this._listboxId}get isReady(){return this.store.get().isReady}on(e,t){return this.emitter.on(e,t)}update(e){let t=this.opts.products,i=this.opts.optionOverrides;Object.assign(this.opts,e),"optionOverrides"in e&&e.optionOverrides!==i&&this.optionSource.refresh(),"products"in e&&e.products!==t&&this.productsController.clearNow(),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)&&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 r=L(e);if(r){let o=t.dateRangeStart;if(!o){this.store.set({pendingRangeStart:{iso:r,key:oe(t)}});return}this.store.set({pendingRangeStart:null}),this.selectOption(Kt(o,r));return}}if(t.editingIdentified){this.commitIdentifiedDate(e);return}if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null){this.reEdit.selectOption(e);return}let i=qn(t,e);if(i){if(this.fireTelemetry("option",{raw_query:T(t.text,t.completedParams).rawQuery,selected_option:i.telemetry.selectedOption,other_options:P(t.activeFormatType)?[]:i.telemetry.otherOptions}),this.store.set(i.patch),this.startSelectionAnimationTimer(),this.timers.clear(Jn),i.remainingActionable>0){let r=i.consumedSuggestion;this.timers.schedule(Jn,()=>{this.store.get().suggestions.includes(r)&&this.store.set(o=>({suggestions:o.suggestions.filter(s=>s!==r)}))},Zn)}this.fetchNow()}}startSelectionAnimationTimer(){this.timers.schedule(Pr,()=>this.store.set({inSelectionAnimation:!1}),Zn)}fireTelemetry(e,t){let i=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");Xn({source:i,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}setupContainer(){this.container.classList.add("magicx-aia"),this.container.dataset.pillPlacement=this.renderMode==="dropdown"?"dropdown":this.opts.pillPlacement??"dropdown",this.container.dataset.optionsPosition=this.opts.optionsPosition??"below",this.container.dataset.animations=this.opts.animations??!0?"on":"off",this.modeController=new le(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 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:r=>this.selectOption(r),setActivePill:r=>this.pillsController.setActivePill(r),skipActivePill:()=>this.skipActivePill(),selectProduct:r=>this.selectProduct(r),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth(),handleKeyDown:r=>this.keyboardController.handleKeyDown(r),handleChange:r=>this.handleChange(r),startEditingParam:r=>this.startEditingParam(r),handleCaretAfterInput:r=>this.handleCaretAfterInput(r),handleCaretMove:r=>this.handleCaretMove(r),replaceEditingRange:r=>this.replaceEditingRange(r)};this.domRefs=Vn(this.container,t);let i=()=>{this.domRefs&&Ot(this.domRefs,this.store.get(),t)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),Ot(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 optionsPosition(){return e.opts.optionsPosition??"below"},selectOption:r=>this.selectOption(r),setActivePill:r=>this.pillsController.setActivePill(r),skipActivePill:()=>this.skipActivePill(),selectProduct:r=>this.selectProduct(r),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth()};this.dropdownRefs=Bn(this.container,t);let i=()=>{this.dropdownRefs&&At(this.dropdownRefs,this.store.get(),t)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),At(this.dropdownRefs,this.store.get(),t),this.subscribeNewParamTimer()}subscribeViewportBreakpoint(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;let t=window.matchMedia(Me),i=()=>e();t.addEventListener("change",i),this.unsubscribers.push(()=>t.removeEventListener("change",i))}subscribeBatchedRender(e){let t=!1;this.unsubscribers.push(this.store.subscribe(()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,t)=>{e.newParamId&&e.newParamId!==t.newParamId&&this.timers.schedule(vr,()=>this.store.set({newParamId:null}),Er)}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:r}=an(e,t.completedParams);r.length>0&&this.store.set({completedParams:i}),this.maybePromoteExactMatch(e),this.maybeOpenPendingSpan()}maybeOpenPendingSpan(){let e=this.store.get();if(e.pendingSpan||e.actionableSuggestions.length===0)return;let t=_(e.text,Math.min(e.filterBase,e.text.length),e.placeholderText),i=en(e.segments,t);e.text.slice(i).trim().length!==0&&this.store.set({pendingSpan:{anchor:i,snapshot:e.actionableSuggestions}})}maybeExitReEditOnNoMatch(){let e=this.store.get();if(!e.editingParam||e.editingAnchor==null||e.completedParams.some(o=>o.id===e.editingParam?.id)||this.optionSource.owns(e.editingParam.suggestionType,e.optionQuery))return;let t=e.caretOffset??e.editingAnchor,i=e.text.slice(e.editingAnchor,t);V(e.editingParam.options,i).some(o=>o.is_tappable)||(this.reEdit.exit(),this.fetchNow())}fetchNow(){let e=this.store.get(),{rawQuery:t,completedParams:i}=T(e.text,e.completedParams);this.fetchController.doFetch(t,i)}commitIdentifiedDate(e){let t=this.store.get(),i=t.editingIdentified;if(!i)return;if(t.text.slice(i.anchor,i.tail)!==i.text){this.store.set({editingIdentified:null,activeDropdownIndex:-1});return}let r=t.text.slice(0,i.anchor),o=t.text.slice(i.tail),s=i.anchor===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,l=o.length===0||o[0]!==" "?`${s} `:s,d=r+l+o,c=d.length,u={id:crypto.randomUUID(),placeholder:"",type:i.type,text:s,kind:e.kind,suggestionType:i.type,suggestionPlaceholder:B(i.type),options:[],metadata:e.metadata};this.fireTelemetry("option",{raw_query:T(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:[]}),this.store.set({text:d,completedParams:[...t.completedParams,u],identifiedParams:t.identifiedParams.filter(f=>f.id!==i.id),newParamId:u.id,filterBase:c,caretOffset:c,editingIdentified:null,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.startSelectionAnimationTimer(),this.scheduleSetCursor(c),this.fetchNow()}maybePromoteExactMatch(e){let t=this.store.get();if(P(t.activeFormatType))return;let i=Re({mode:"fresh",text:e,completedParams:t.completedParams,suggestions:t.suggestions,filterBase:t.filterBase,filterInProgress:t.filterInProgress});i&&this.store.set(i.patch)}};export{Mt as AIAutocomplete,Tn as ATTRIBUTION_URL,tt as DATE_RANGE_META_END,et as DATE_RANGE_META_START,le as ModeController,Me as OPTIONS_GRID_MOBILE_QUERY,St as OPTION_ENTER_DELAY_VAR,Yi as OPTION_ENTER_FADE_MS,ji as OPTION_ENTER_RISE_MS,zi as OPTION_ENTER_RISE_PX,Qi as OPTION_ENTER_STAGGER_MS,Hi as PLACEHOLDER_FADE_OUT_MS,X as PLACEHOLDER_LEAVING_ATTR,Fi as PLACEHOLDER_SWAP_GAP_MS,_i as PLACEHOLDER_TYPE_MS,Ni as PLACEHOLDER_WORD_PAUSE_MS,Vt as RANGE_SEPARATOR,kn as SCROLL_ARROW_ATTR,Nn as SCROLL_ARROW_BOTTOM_VAR,Ln as SCROLL_ARROW_CLASS,Hn as SCROLL_ARROW_LABEL,_n as SCROLL_ARROW_LEAVE_MS,He as SCROLL_ARROW_LEAVING_ATTR,ae as SCROLL_ARROW_VISIBLE_ATTR,Yt as SKIPPED_PARAM_TEXT,ce as WEEKDAY_LABELS,Ye as addMonths,wt as attachScrollArrow,ft as buildAttributionUrl,je as buildDateOptions,T as buildQuery,q as buildSubmitResult,Xe as cellDay,L as cellIso,fn as computeOptionsGridLayout,It as createStore,ot as cursorIsAtEnd,bt as dateCellMarks,se as dateSelectionFor,Ae as extractPlainText,Q as formatAbsoluteDate,Ft as formatDate,qt as formatDateRange,R as getCursorOffset,gt as getFooterHint,B as identifiedParamLabel,P as isCalendarFormat,mt as isOptionsGridMobileViewport,I as isoDate,pt as measureOptionsGrid,Ue as monthLabel,ct as needsOptionsGridMeasurement,vt as optionEnterDelayMs,Pt as optionsEntranceDurationMs,hn as optionsGridTemplateColumns,ue as parseDate,W as parseLooseDate,Y as parseLooseDateRange,rt as plainTextLength,ut as planOptionsGrid,st as previousGraphemeBoundary,Ct as renderEditableContent,G as resolveFormatType,Je as resolveIdentifiedDate,it as scrollCaretIntoView,ze as selectedIsoFromText,te as selectedRangeFor,O as setCursorOffset,ie as toWireIdentifiedParams,ht as visibleDateRange,re as withSkippedParams};
|
|
1610
1617
|
//# sourceMappingURL=index.mjs.map
|