@magicx-eng/ai-autocomplete-vanilla 0.13.0 → 0.14.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 +99 -3
- package/dist/index.d.mts +242 -14
- package/dist/index.d.ts +242 -14
- package/dist/index.js +145 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +145 -2
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var ve=Object.defineProperty;var ft=Object.getOwnPropertyDescriptor;var ht=Object.getOwnPropertyNames;var bt=Object.prototype.hasOwnProperty;var xt=(n,e)=>{for(var t in e)ve(n,t,{get:e[t],enumerable:!0})},St=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ht(e))!bt.call(n,r)&&r!==t&&ve(n,r,{get:()=>e[r],enumerable:!(i=ft(e,r))||i.enumerable});return n};var yt=n=>St(ve({},"__esModule",{value:!0}),n);var ln={};xt(ln,{AIAutocomplete:()=>ye,ATTRIBUTION_URL:()=>Ae,ModeController:()=>B,OPTIONS_GRID_MOBILE_QUERY:()=>K,SKIPPED_PARAM_TEXT:()=>Ce,buildAttributionUrl:()=>ce,buildQuery:()=>v,buildSubmitResult:()=>N,computeOptionsGridLayout:()=>re,createStore:()=>he,cursorIsAtEnd:()=>Z,extractPlainText:()=>F,getCursorOffset:()=>T,getFooterHint:()=>pe,isOptionsGridMobileViewport:()=>se,optionsGridTemplateColumns:()=>oe,plainTextLength:()=>J,previousGraphemeBoundary:()=>ee,renderEditableContent:()=>fe,setCursorOffset:()=>C,withSkippedParams:()=>M});module.exports=yt(ln);var $=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 Pt="https://api.ai-autocomplete.com",G=`${Pt}/api/suggest`,De=new WeakMap;function H(n){return n?.type==="accessToken"}function vt(n){if(!(!n||H(n)))return n}function q(n){let e=De.get(n.getAccessToken);return e||(e=new $(n),De.set(n.getAccessToken,e)),e}function Q(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function W(n){let e=vt(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}var Ce="skipped";function M(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:Ce,kind:null}));return i.length>0?[...n,...i]:n}var Ct="0.13.0",Re=!1;function wt(){return crypto.randomUUID()}function Et(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.text},kind:n.kind}}function Tt(n,e,t,i,r,o,a,s,d){let l=e.find(c=>c.type==="contact"&&c.metadata?.contact_account_count)?.metadata?.contact_account_count,p=typeof l=="number"?l:void 0;return{data:{raw_query:n,completed_params:M(e.map(c=>Et(c,t)),a??[]),...r&&r.length>0&&{identified_params:r.map(c=>({type:c.type,value:c.text}))},...o&&o.length>0&&{recently_suggested:o},...p!=null&&{contact_account_count:p},...s!==void 0&&{additional_context:s},...d!==void 0&&{generate_starting_state_options:d}},meta:{request_id:wt(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:Ct,session_id:i}}}async function Ne(n,e,t,i,r){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:r})}async function _e(n,e,t){let i=t.apiConfig,r=!t.maskCompletedText,o=Tt(n,e,r,t.sessionId,t.identifiedParams,t.recentlySuggested,t.skippedParams,t.additionalContext,t.generateStartingStateOptions),a=Q(i),s=i?.endpoint??G,d=JSON.stringify(o);if(H(i)){let c=q(i),m=await c.getToken(),f=await Ne(s,a,m,d,t.signal);if(f.status===401){let h=await c.getToken(!0);f=await Ne(s,a,h,d,t.signal)}if(!f.ok)throw new Error(`API error: ${f.status} ${f.statusText}`);return f.json()}let l=W(i);!l&&!Re&&(Re=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),l&&(a.Authorization=l);let p=await fetch(s,{method:"POST",headers:a,body:d,signal:t.signal});if(!p.ok)throw new Error(`API error: ${p.status} ${p.statusText}`);return p.json()}function v(n,e){let t=n,i={},r=[],o=[],a=0;for(let s of e){let d=(i[s.type]??0)+1;i[s.type]=d;let p=`{{${s.type.toUpperCase().replace(/\s+/g,"_")}_${d}}}`,c=f=>{let h=t.indexOf(s.text,f);for(;h!==-1&&o.some(S=>h<S.end&&h+s.text.length>S.start);)h=t.indexOf(s.text,h+1);return h},m=c(a);if(m===-1&&(m=c(0)),m!==-1){t=t.slice(0,m)+p+t.slice(m+s.text.length);let f=p.length-s.text.length;for(let h of o)h.start>=m+s.text.length&&(h.start+=f,h.end+=f);o.push({start:m,end:m+p.length}),a=m>=a?m+p.length:a+f}r.push({...s,placeholder:p})}return{rawQuery:t,completedParams:r}}function O(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function V(n,e,t){return e===0&&n.length>0&&t.length>0&&t.toLowerCase().startsWith(n.toLowerCase())}function k(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 Be(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 a=i.slice(o).join(" ");if(r.startsWith(a.toLowerCase())){let s=t.length-a.length;return n.length-s}}return 0}function L(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 D(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 He(n,e){return e?n.map(t=>{let i=e[t.type];if(!i)return t;let r=i("");return r?{...t,options:r}:t}):n}function Fe(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 Ke(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 Ue(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 $e(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 we(n,e){let t=[],i=[],r=0;for(let o of e){let a=n.indexOf(o.text,r);if(a===-1){i.push(o);continue}t.push({start:a,end:a+o.text.length,param:o}),r=a+o.text.length}return{located:t,missing:i}}function Ge(n,e,t){let i=[],r=[],o=0;for(let a of t){let s=n.indexOf(a.text,o);for(;s!==-1&&e.some(d=>s<d.end&&s+a.text.length>d.start);)s=n.indexOf(a.text,s+1);if(s===-1){r.push(a);continue}i.push({start:s,end:s+a.text.length,param:a}),o=s+a.text.length}return{located:i,missing:r}}function qe(n,e,t=[]){let i=we(n,e).located,r=Ge(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,p)=>l.start-p.start),a=[],s=0;for(let l of o)l.start>s&&a.push({type:"text",value:n.slice(s,l.start)}),a.push(l.segment),s=l.end;let d=n.slice(s);return d&&a.push({type:"text",value:d}),a}function Qe(n,e){let{located:t,missing:i}=we(n,e);return{valid:t.map(r=>r.param),invalid:i}}function j(n,e,t){let i=we(n,e).located,{located:r,missing:o}=Ge(n,i,t);return{valid:r.map(a=>a.param),invalid:o}}function At(n){if(n instanceof Error)return n;try{return new Error(String(n))}catch{return new Error("Unknown error")}}var It=100,Ot=300,kt=2,X=class{constructor(e,t,i,r,o,a,s,d,l={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=r;this.getOnError=o;this.getSessionId=a;this.getAdditionalContext=s;this.getGenerateStartingStateOptions=d;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 a=this.store.get(),s=a.pendingSpan?Ue(a.pendingSpan.snapshot,a.actionableSuggestions):void 0,d=await _e(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig(),identifiedParams:a.identifiedParams,recentlySuggested:s,skippedParams:a.skippedParams,additionalContext:this.getAdditionalContext(),generateStartingStateOptions:this.getGenerateStartingStateOptions()});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})),p=He(d.data.suggestions??[],this.getOptionOverrides()),c=d.data.input??[],m=c[c.length-1],f=this.store.get().text,h,S;if(m?.state==="in_progress"){S=!0;let b=f.toLowerCase().lastIndexOf(m.text.toLowerCase());h=b!==-1?b:o}else S=!1,h=o;let g=p.filter(b=>b.type!=="placeholder")[0],u=null;if(g){let b=k(f,h,S),y=D(g.options,b);y&&(u={id:crypto.randomUUID(),placeholder:"",type:g.type,text:y.text,kind:y.kind,suggestionType:g.type,suggestionPlaceholder:g.text,options:g.options??[],metadata:y.metadata},p=p.filter(P=>P!==g),this.callbacks.onAutoMatch?.({active:g,matched:y,rawQuery:e}))}this.store.set(b=>{let y=u?[...b.completedParams,u]:b.completedParams,P=j(b.text,y,l).valid,E=new Set(a.skippedParams.map(w=>w.id)),U=new Set(b.skippedParams.filter(w=>!E.has(w.id)).map(w=>w.type));return{suggestions:U.size>0?p.filter(w=>w.type==="placeholder"||!U.has(w.type)):p,isLoading:!1,isReady:d.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:h,filterInProgress:S,identifiedParams:P,...u?{completedParams:y}:{}}})}catch(a){let s=At(a);r===this.fetchVersion&&(this.store.set({error:s,isLoading:!1}),this.getOnError()?.(s))}finally{if(r===this.fetchVersion&&this.store.get().isLoading)try{this.store.set({isLoading:!1})}catch{}}}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}let t=i=>{let r=this.store.get();if(!r.text&&r.completedParams.length===0)return this.doFetch("",[]),!0;let o=r.suggestions.filter(u=>u.type==="placeholder").map(u=>u.text).join(" "),a=O(r.text,r.filterBase,o),s=k(r.text,a,r.filterInProgress),l=r.suggestions.filter(u=>u.type!=="placeholder")[0],c=(l?L(l.options,s):[]).filter(u=>u.is_tappable),m=l?D(l.options,s)!==null:!1,f=s.trim().length>0;if(c.length>0&&!m&&f||V(r.text,r.completedParams.length,o))return!1;let{rawQuery:h,completedParams:S}=v(r.text,r.completedParams),x=h.length<r.lastRawQuery.length,g=Math.abs(h.length-r.lastRawQuery.length);return x||g>=i?(this.doFetch(h,S),!0):!1};this.debounceTimer=setTimeout(()=>{t(kt)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},It),this.slowDebounceTimer=setTimeout(()=>t(1),Ot)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var Ve='[contenteditable="false"]',R;function Lt(){if(R!==void 0)return R;let n=globalThis.Intl.Segmenter;if(!n)return R=null,null;try{R=new n(void 0,{granularity:"grapheme"})}catch{R=null}return R??null}function z(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(Ve))return!0;t=t.parentNode}return!1}function Y(n){return(n.ownerDocument??document).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return z(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function F(n){let e=Y(n),t="",i=e.nextNode();for(;i;)t+=i.data,i=e.nextNode();return t}function J(n){let e=Y(n),t=0,i=e.nextNode();for(;i;)t+=i.data.length,i=e.nextNode();return t}function T(n){let e=(n.ownerDocument??document).getSelection();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(z(r,n)&&r!==n)return null;let o=0;for(let a=0;a<i&&a<r.childNodes.length;a++)o+=je(r.childNodes[a],n);return o+We(r,n)}return t.nodeType!==Node.TEXT_NODE||z(t,n)?null:We(t,n)+i}function je(n,e){if(n.nodeType===Node.TEXT_NODE)return z(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(Ve))return 0;let i=0;for(let r of Array.from(t.childNodes))i+=je(r,e);return i}function We(n,e){let t=Y(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 C(n,e){let t=n.ownerDocument??document,i=t.getSelection();if(!i)return;let r=Math.max(0,Math.min(e,J(n))),o=Y(n),a=0,s=null,d=0,l=o.nextNode(),p=null;for(;l;){let m=l.data.length;if(r<a+m){s=l,d=r-a;break}if(r===a+m){let f=o.nextNode();f?(s=f,d=0):(s=l,d=m);break}a+=m,p=l,l=o.nextNode()}let c=t.createRange();if(s){let m=s.parentElement?.closest('strong[data-seg="completed"]');m&&m!==n&&n.contains(m)?d===0?c.setStartBefore(m):d===s.data.length?c.setStartAfter(m):c.setStart(s,d):c.setStart(s,d)}else p?c.setStart(p,p.data.length):c.setStart(n,0);c.collapse(!0),i.removeAllRanges(),i.addRange(c)}function Z(n){let e=T(n);return e==null?!1:e>=J(n)}function ee(n,e){if(e<=0)return 0;let t=Lt();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 N(n,e,t=[]){let{rawQuery:i,completedParams:r}=v(n,e);return{query:n.trim(),raw_query:i,completed_params:M(r,t)}}function Ee(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")?Z(n):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function Te(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?T(n):null}var te=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:r}=this.ctx,o=this.getEffectiveColumns(),a=r(),s=this.getTappableIndices(o);if((e.shiftKey||e.metaKey||e.ctrlKey||e.altKey)&&(e.key==="ArrowDown"||e.key==="ArrowUp"||e.key==="ArrowLeft"||e.key==="ArrowRight"))return;let d=this.ctx.getOptionsPosition()==="above";switch(e.key){case"ArrowDown":{let l=Ee(e.target,t),p=!!t.editingParam;if(!l&&!p&&t.activeDropdownIndex<0)break;if(t.activeDropdownIndex<0){if(d)break;if(e.preventDefault(),!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:s[0]??0});break}if(s.length===0)return;this.store.set({activeDropdownIndex:s[0]});break}if(e.preventDefault(),s.length===0)return;if(t.filteredOptions.length>0){let f=Math.floor((t.filteredOptions.length-1)/o);if(Math.floor(t.activeDropdownIndex/o)===f){this.store.set({activeDropdownIndex:-1});break}}let c=s.indexOf(t.activeDropdownIndex),m=c<s.length-1?c+1:0;this.store.set({activeDropdownIndex:s[m]});break}case"ArrowUp":{if(t.activeDropdownIndex<0){if(!d)break;let c=Ee(e.target,t),m=!!t.editingParam;if(!c&&!m)break;e.preventDefault();let f=this.firstTappableInBottomRow(o)??s[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:f});break}if(s.length===0)return;this.store.set({activeDropdownIndex:f});break}if(s.length===0)break;if(e.preventDefault(),t.activeDropdownIndex<o){this.store.set({activeDropdownIndex:-1});break}let l=s.indexOf(t.activeDropdownIndex),p=l>0?l-1:s.length-1;this.store.set({activeDropdownIndex:s[p]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%o<o-1){let c=t.activeDropdownIndex+1;c<t.filteredOptions.length&&t.filteredOptions[c]?.is_tappable&&this.store.set({activeDropdownIndex:c})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let p=e.target.closest("[data-aia-input]")??e.target,c=t.editingTail;this.ctx.exitEditMode?.(),C(p,c);break}Ee(e.target,t)&&t.actionableSuggestions.length>=1&&(e.preventDefault(),this.ctx.skipActivePill());break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%o>0){let l=t.activeDropdownIndex-1;l>=0&&t.filteredOptions[l]?.is_tappable&&this.store.set({activeDropdownIndex:l});break}if(!t.editingParam&&this.ctx.startEditingParamAtCaret){let l=Te(e.target);l!=null&&this.ctx.startEditingParamAtCaret(l)}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let l=e.target.closest("[data-aia-input]")??e.target,p=t.editingAnchor;this.ctx.exitEditMode?.(),C(l,p);break}if(this.ctx.startEditingParamAtCaret){let l=Te(e.target);l!=null&&this.ctx.startEditingParamAtCaret(l)&&e.preventDefault()}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let l=Te(e.target);if(l==null)break;this.ctx.removeParamAtCaret(l)&&e.preventDefault();break}case"Enter":{e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable?this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i):a&&a(N(t.text,t.completedParams,t.skippedParams))&&this.ctx.afterSubmit?.();break}case"Tab":{let l=t.filteredOptions.map((m,f)=>m.is_tappable?f:-1).filter(m=>m!==-1);if(l.length===0)break;if(!t.isDropdownOpen){if(t.actionableSuggestions.length===0)break;e.preventDefault();let m=e.shiftKey?l[l.length-1]:l[0];this.store.set({pillTapped:!0,activeDropdownIndex:m});break}e.preventDefault();let p=l.indexOf(t.activeDropdownIndex),c;if(p<0)c=e.shiftKey?l.length-1:0;else{let m=e.shiftKey?-1:1;c=(p+m+l.length)%l.length}this.store.set({activeDropdownIndex:l[c]});break}case"Escape":{if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){let l=e.target.closest("[data-aia-input]")??e.target,p=t.editingTail;this.ctx.exitEditMode?.(),C(l,p)}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}getTappableIndices(e){let i=this.store.get().filteredOptions.map((o,a)=>o.is_tappable?a:-1).filter(o=>o!==-1),r=Array.from({length:e},()=>[]);for(let o of i)r[o%e].push(o);return r.flat()}getEffectiveColumns(){let e=document.getElementById(this.ctx.listboxId);if(!e)return this.ctx.columns;let i=document.getElementById(`${this.ctx.listboxId}-option-0`)?.parentElement??null;for(;i;){let r=getComputedStyle(i).gridTemplateColumns;if(r&&r!=="none"){let o=r.split(" ").filter(Boolean).length;if(o>0)return o}if(i===e)break;i=i.parentElement}return this.ctx.columns}clickOrSelect(e,t,i){let r=document.getElementById(`${i}-option-${e}`);r?r.click():this.ctx.selectOption(t[e])}};var ne=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,p)=>p!==e),a=t.suggestions.filter(l=>l.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:l}=v(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:l,selectedPill:r.text,otherPills:o.map(p=>p.text)})}let s=[...a,r,...o],d=this.store.peek({suggestions:s}).filteredOptions.findIndex(l=>l.is_tappable);this.store.set({suggestions:s,pillTapped:!0,activeDropdownIndex:d})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};var ie=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 a=r.transform(o),s=Array.isArray(a)?a:[],d=r.limit!=null?s.slice(0,r.limit):s;if(t.aborted||!i())return;this.commit(d)}catch(o){if(t.aborted||Mt(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 Mt(n){return n instanceof Error&&n.name==="AbortError"}var K="(max-width: 768px)";var Dt="var(--aia-option-row-height, 37px)",Rt="var(--aia-grid-scroll-top, 0px) + var(--aia-grid-scroll-bottom, 0px)";function re(n,e){let t=(i,r)=>({cols:i,rows:r,maxHeight:`calc(${r} * ${Dt} + ${Rt})`});return e?t(1,Math.min(n,5)):n>=5&&n<=6?t(2,Math.ceil(n/2)):t(1,Math.min(n,4))}function oe(n){return Array.from({length:n},()=>"minmax(0,1fr)").join(" ")}function se(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(K).matches}function Xe(n,e){let t=e.dropdownTrigger??"auto",i=e.closeDropdownOnBlur??!0,a=n.filteredOptionsLength>0||n.activePillHasNoOptions||n.hasProducts;if(n.inEditMode){let s=i?n.isFocused:!0;return a&&s}if(t==="auto"){let s=i?n.isFocused:!0,d=n.text.replace(/\s+$/,"").length,l=n.caretOffset==null||n.caretOffset>=d;return(a||n.isLoading)&&s&&l}return t==="manual"?(a||n.isLoading)&&n.pillTapped:!1}function ze(n,e){let t=qe(n.text,n.completedParams,n.identifiedParams),i=n.suggestions.filter(u=>u.type!=="placeholder"),r=i[0],o=r?e.optionOverrides?.[r.type]:void 0,a=n.suggestions.filter(u=>u.type==="placeholder").map(u=>u.text).join(" "),s=O(n.text,Math.min(n.filterBase,n.text.length),a),l=s===0&&V(n.text,n.completedParams.length,a)?"":k(n.text,s,n.filterInProgress),p=r?o?o(l.trim())??r.options??[]:r.options??[]:[],c=n.editingParam!=null&&n.editingAnchor!=null,m;if(c&&n.editingParam&&n.editingAnchor!=null){let u=n.editingParam.id,b=n.completedParams.some(E=>E.id===u),y=n.caretOffset??n.editingAnchor,P=b?"":n.text.slice(n.editingAnchor,y);m=L(n.editingParam.options,P)}else m=L(p,l);let f=e.showNonTappableOptions===!1;f&&(m=m.filter(u=>u.is_tappable));let h=u=>f?u.is_tappable:!0,S;if(c){let u=n.editingParam?.options??[];S=n.editingParam!=null&&u.filter(h).length===0}else{let u=r?o?o("")??r.options??[]:r.options??[]:[];S=r!=null&&u.filter(h).length===0}let x=Xe({inEditMode:c,filteredOptionsLength:m.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading,pillTapped:n.pillTapped,activePillHasNoOptions:S,hasProducts:n.products.length>0},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),g=x&&n.activeDropdownIndex>=0&&!!m[n.activeDropdownIndex]?.is_tappable;return{segments:t,actionableSuggestions:i,filteredOptions:m,placeholderText:a,isDropdownOpen:x,isActivePillSelected:g}}function ae(n){return n.mode==="fresh"?Nt(n):_t(n)}function Nt(n){let{text:e,completedParams:t,suggestions:i,filterBase:r,filterInProgress:o}=n,s=i.filter(y=>y.type!=="placeholder")[0];if(!s?.options)return null;let d=i.filter(y=>y.type==="placeholder").map(y=>y.text).join(" "),l=O(e,r,d),p=k(e,l,o),c=D(s.options,p);if(!c)return null;let m=c.text.toLowerCase(),f=e.toLowerCase().lastIndexOf(m),h=f>=0?f:Math.max(0,e.length-c.text.length),S=h+c.text.length,x=e.slice(h,S),u=S<e.length&&e[S]===" "?S+1:S,b={id:crypto.randomUUID(),placeholder:"",type:s.type,text:x,kind:c.kind,suggestionType:s.type,suggestionPlaceholder:s.text,options:s.options??[],metadata:c.metadata};return{patch:{text:e,completedParams:[...t,b],suggestions:i.filter(y=>y!==s),filterBase:u,newParamId:b.id,caretOffset:u,activeDropdownIndex:-1},caretPos:u}}function _t(n){let{text:e,completedParams:t,editingParam:i,editingAnchor:r,editingTail:o}=n;if(t.some(b=>b.id===i.id))return null;let a=e.slice(r,o),s=D(i.options,a);if(!s)return null;let d=s.text.toLowerCase(),l=a.toLowerCase().lastIndexOf(d),p=r+Math.max(0,l),c=p+s.text.length,m=e.slice(p,c),h=c<e.length&&e[c]===" "?c+1:c,S={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:m,kind:s.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:s.metadata},x=t.length,g=0;for(let b=0;b<t.length;b++){let y=e.indexOf(t[b].text,g);if(y!==-1){if(y>=h){x=b;break}g=y+t[b].text.length}}let u=[...t];return u.splice(x,0,S),{patch:{text:e,completedParams:u,newParamId:S.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 de=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(a=>a.id===e);if(!i)return;let r=0,o=-1;for(let a of t.completedParams){let s=t.text.indexOf(a.text,r);if(s!==-1){if(a.id===e){o=s;break}r=s+a.text.length}}o<0||this.deps.store.set({editingParam:i,editingAnchor:o,editingTail:o+i.text.length,caretOffset:o+i.text.length,activeDropdownIndex:-1})}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:a}=e===""?le(t.text,r,o):{text:t.text.slice(0,r)+e+t.text.slice(o)},s=r+e.length;return this.deps.store.set(d=>({text:a,completedParams:d.completedParams.filter(l=>l.id!==i.id),editingTail:s,caretOffset:s,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(s),this.tryPromote(),!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.tryPromote()}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:v(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:i.options.filter(g=>g.text!==e.text).map(g=>g.text)});let a=t.text.slice(0,r),s=t.text.slice(o),d=r===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,l=s.length===0||s[0]!==" ",p=l?`${d} `:d,c=a+p+s,m=r+p.length+(l?0:1),f={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(g=>g.id===i.id),S=t.completedParams.filter(g=>g.id!==i.id),x=h>=0?Math.min(h,S.length):S.length;S.splice(x,0,f),this.deps.store.set({text:c,completedParams:S,newParamId:f.id,filterBase:m,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:m,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.deps.startSelectionAnimationTimer(),this.deps.scheduleSetCursor(m),this.deps.fetchNow()}tryPromote(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let t=ae({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 Ae="https://ai-autocomplete.com";function ce(n=Ae){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 pe(n,e){return n?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}var Ye="data-aia-key";function _(n,e,t){let i=new Map;for(let a of Array.from(n.children)){let s=a.getAttribute(Ye);s!=null&&i.set(s,a)}let r=new Set,o=[];for(let a=0;a<e.length;a++){let s=e[a],d=t.keyOf(s,a);r.add(d);let l=i.get(d);l||(l=t.create(s,a),l.setAttribute(Ye,d)),t.update?.(l,s,a),n.children[a]!==l&&n.insertBefore(l,n.children[a]??null),o.push(l)}for(let[a,s]of i)r.has(a)||s.remove();return o}var Je=[125,69];function Ze(n,e){return e?1:n===0?.7:n===1?.4:.2}function ue(n,e,t,i,r=!1,o=!1,a=!1){let s=n.querySelector(".magicx-aia-pill-list");if(s||(s=document.createElement("span"),s.className="magicx-aia-pill-list",n.appendChild(s)),o&&e.length===0){s.setAttribute("data-aia-pill-list-loading",""),s.innerHTML="";for(let d=0;d<Je.length;d++){let l=Je[d],p=document.createElement("span");p.setAttribute("data-aia-pill-skeleton",""),p.className=`magicx-aia-pill magicx-aia-pill--skeleton${r?" magicx-aia-pill--rounded":""}`,p.style.width=`${l}px`,p.style.opacity=String(Ze(d,!1)),s.appendChild(p)}return}o?s.setAttribute("data-aia-pill-list-loading",""):s.removeAttribute("data-aia-pill-list-loading");for(let d of s.querySelectorAll("[data-aia-pill-skeleton]"))d.remove();_(s,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",p=>p.preventDefault()),l},update:(d,l,p)=>{let c=d,m=a&&p===t&&!o,f=["magicx-aia-pill"];r&&f.push("magicx-aia-pill--rounded"),o&&f.push("magicx-aia-pill--skeleton"),c.className=f.join(" "),c.style.width="",c.style.opacity=String(Ze(p,m)),o?(c.setAttribute("data-aia-loading",""),c.disabled=!0,c.onclick=null):(c.removeAttribute("data-aia-loading"),c.disabled=!1,c.onclick=()=>i(p))}})}function Ie(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var Bt="Products";function et(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 s=document.createElement("div");s.className="magicx-aia-products-label",s.id=`${t}-products-label`,s.textContent=Bt;let d=document.createElement("div");d.className="magicx-aia-products-row",d.setAttribute("data-aia-products-row",""),o.append(s,d),n.appendChild(o)}let a=o.querySelector(".magicx-aia-products-row");a&&_(a,e,{keyOf:s=>Ht(s),create:s=>Ft(s,i,r),update:(s,d,l)=>{s.id=`${t}-product-${l}`,s.dataset.aiaIndex=String(l)}})}function Oe(n,e){let t=n.querySelectorAll("[data-aia-product]");for(let i of t)i.tabIndex=e?0:-1}function Ht(n){return[n.id,n.title,n.url,n.imageUrl,n.price,n.vendor].map(e=>e??"").join("\0")}function Ft(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 s=document.createElement("img");s.className="magicx-aia-product-image",s.src=n.imageUrl,s.alt="",s.loading="lazy",s.decoding="async",r.appendChild(s)}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 s=document.createElement("span");s.className="magicx-aia-product-vendor",s.textContent=n.vendor,o.appendChild(s)}let a=document.createElement("span");if(a.className="magicx-aia-product-title",a.textContent=n.title,o.appendChild(a),n.price){let s=document.createElement("span");s.className="magicx-aia-product-price",s.textContent=n.price,o.appendChild(s)}return i.appendChild(o),i.addEventListener("click",s=>{s.metaKey||s.ctrlKey||s.shiftKey||s.altKey||s.button!==0||(s.preventDefault(),e(n))}),i.addEventListener("keydown",s=>{s.key!=="Enter"&&s.key!==" "||(s.preventDefault(),e(n))}),i.addEventListener("focus",()=>t(!0)),i.addEventListener("blur",s=>{s.relatedTarget?.closest("[data-aia-dropdown]")||t(!1)}),i}function Kt(n,e){let{cols:t,maxHeight:i}=re(e,se());n.style.gridTemplateColumns=oe(t),n.style.setProperty("--aia-grid-max-height",i)}function tt(n,e,t,i,r,o,a,s=""){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)),Kt(d,e.length),$t(d,e,t,i,r,o,a),Ut(d,s)}function Ut(n,e){n.dataset.aiaGroup!==e&&(n.dataset.aiaGroup=e,n.scrollTop=0)}function $t(n,e,t,i,r,o,a){let s=a?"1":"0";_(n,e,{keyOf:d=>`${d.text}\0${s}`,create:d=>Gt(d,a),update:(d,l,p)=>{let c=p===t&&!a;d.id=`${o}-option-${p}`,d.dataset.aiaIndex=String(p),d.setAttribute("aria-selected",String(c)),d.classList.toggle("magicx-aia-option--highlighted",c),!a&&l.is_tappable?(d.onclick=()=>{d.classList.add("magicx-aia-option--pressed"),i(l),setTimeout(()=>d.classList.remove("magicx-aia-option--pressed"),500)},d.onmouseenter=()=>{let m=Number.parseInt(d.dataset.aiaIndex??"-1",10);m>=0&&r(m)}):(d.onclick=null,d.onmouseenter=null)}})}function Gt(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("div");r.className="magicx-aia-streaks",t.appendChild(r);let o=document.createElement("div");o.className="magicx-aia-streaks-vert",t.appendChild(o);let a=document.createElement("span");a.className="magicx-aia-option-content";let s=document.createElement("span");if(s.className="magicx-aia-option-text",s.textContent=n.icon?`${n.icon} ${n.text}`:n.text,a.appendChild(s),n.tag){let d=document.createElement("span");d.className="magicx-aia-option-tag",d.textContent=n.tag,a.appendChild(d)}return t.appendChild(a),t}var qt=[159,119,164];function me(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}function ge(n,e){let{filteredOptions:t,activeIndex:i,isOpen:r,isLoading:o,pills:a,showPills:s,isActivePillSelected:d,onSelect:l,onHighlight:p,onPillClick:c,onSkip:m}=e,f=a.length>0,h=s&&f,S=t.length>0,x=e.products.length>0,g=r&&(S||h||o||x);if(g?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"),!g){Oe(n,!1);return}x?n.setAttribute("data-aia-has-products",""):n.removeAttribute("data-aia-has-products");let u=n.querySelector(".aia-stack");u||(u=document.createElement("div"),u.className="aia-stack",u.style.setProperty("--aia-stack-space","8px"),n.appendChild(u));let b=e.showSkipButton&&f&&!e.isInputEmpty,y=h||o&&s||b,P=u.querySelector(".magicx-aia-pill-bar");if(y){P||(P=document.createElement("div"),P.className="magicx-aia-pill-bar aia-cluster",P.setAttribute("data-nowrap",""),P.setAttribute("data-aia-pillbar",""),u.insertBefore(P,u.firstChild));let I=P.querySelector(".magicx-aia-pill-scroll");I||(I=document.createElement("span"),I.className="magicx-aia-pill-scroll",I.setAttribute("data-aia-pill-scroll",""),P.insertBefore(I,P.firstChild)),ue(I,s?a:[],0,c,!0,o&&s,d),Wt(P,b,o||e.skipDisabled,a[0],m)}else P&&P.remove();let E=e.suggestions[0],U=E?`${E.type} ${E.text}`:"";tt(u,t,i,l,p,e.listboxId,o,U);let A=u.querySelector(".magicx-aia-skeleton-bars");if(o&&!S){if(!A){A=document.createElement("div"),A.className="magicx-aia-skeleton-bars",A.setAttribute("data-aia-skeleton-bars","");for(let I of qt){let Pe=document.createElement("span");Pe.className="magicx-aia-skeleton-bar",Pe.style.width=`${I}px`,A.appendChild(Pe)}u.appendChild(A)}}else A&&A.remove();et(u,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange),Oe(n,!0);let w=u.querySelector(".magicx-aia-footer")??jt(),gt=i>=0&&!!t[i]?.is_tappable;Vt(w,pe(gt,e.isInputEmpty)),w.isConnected||u.appendChild(w),Qt(u,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"])}function Qt(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 Wt(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",a=>a.preventDefault()),n.appendChild(o)),o.setAttribute("aria-label",i?`Skip ${i.text}`:"Skip"),o.disabled=t,o.onclick=t?null:()=>r()}function Vt(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 jt(){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=ce(),o.target="_blank",o.rel="noopener noreferrer",o.style.setProperty("--aia-cluster-gap","2px");let a=document.createElement("span");a.className="magicx-aia-footer-brand",a.textContent="AI";let s=document.createElement("span");return s.className="magicx-aia-footer-badge",s.textContent="Autocomplete",o.append(a,s),e.append(t,o),n.append(e),n}function nt(n,e){let t=me(e.listboxId);return n.appendChild(t),{dropdown:t}}function ke(n,e,t){ge(n.dropdown,{suggestions: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,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,showSkipButton:t.showSkipButton&&!e.editingParam,skipDisabled:e.inSelectionAnimation,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,onSelect:t.selectOption,onHighlight:i=>t.store.set({activeDropdownIndex:i}),onPillClick:t.setActivePill,onSkip:t.skipActivePill,onProductSelect:t.selectProduct,onProductFocusChange:i=>t.store.set({isFocused:i})})}var Xt=6,zt=.3;function it(n){return n<=0?"0px":`${(-Math.min(zt,2*Xt/n)).toFixed(3)}px`}function fe(n){let{input:e,segments:t,newParamId:i,editingParamId:r,placeholderText:o,isFocused:a}=n,s=t.length===0;e.dataset.aiaEmpty=s?"true":"false",s&&o?e.dataset.placeholder=o:delete e.dataset.placeholder;let d=t.map(x=>`${x.type}:${x.value}`).join("\0"),l=e.dataset.segKey??"",p=e.dataset.newParamId??"",c=e.dataset.editingParamId??"";if(d===l&&(i??"")===p&&(r??"")===c)return;let m=a?T(e):null;e.dataset.segKey=d,e.dataset.newParamId=i??"",e.dataset.editingParamId=r??"";let f=e.ownerDocument??document,h=f.createDocumentFragment(),S=0;for(let x of t)if(S+=x.value.length,x.type==="completed"){let g=f.createElement("strong");g.dataset.seg="completed",g.dataset.paramId=x.param.id;let u=x.param.id===i,b=x.param.id===r,y=["magicx-aia-segment","magicx-aia-segment--completed"];u&&y.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),b&&y.push("magicx-aia-segment--editing"),g.className=y.join(" "),g.style.letterSpacing=it(x.value.length),g.textContent=x.value,h.appendChild(g)}else if(x.type==="identified"){let g=f.createElement("strong");g.dataset.seg="identified",g.dataset.paramId=x.param.id,g.className="magicx-aia-segment magicx-aia-segment--completed",g.style.letterSpacing=it(x.value.length),g.textContent=x.value,h.appendChild(g)}else h.appendChild(f.createTextNode(x.value));e.replaceChildren(h),e.dataset.aiaTextLength=String(S),m!=null&&C(e,Math.max(0,Math.min(m,S)))}var Yt='<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 rt(){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=Yt,n}function Jt(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function ot(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 st(n,e){let{listboxId:t}=e,i=me(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 a=document.createElement("div");a.className="magicx-aia-input",a.setAttribute("data-aia-input",""),a.setAttribute("contenteditable",Jt()?"plaintext-only":"true"),a.setAttribute("role","combobox"),a.setAttribute("aria-autocomplete","list"),a.setAttribute("aria-haspopup","listbox"),a.setAttribute("aria-controls",t),a.setAttribute("aria-expanded","false"),a.setAttribute("spellcheck","true"),a.setAttribute("enterkeyhint","send"),o.appendChild(a);let s=document.createElement("span");s.className="magicx-aia-pill-list-container",s.setAttribute("data-aia-pill-list-container",""),o.appendChild(s);let d=null,l=null;e.submitButton===void 0?(d=rt(),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 p=new AbortController,{signal:c}=p,m=!1,f=0,h=()=>{let g=F(a),b=g.length>0&&g[0]!==g[0].toUpperCase()?g[0].toUpperCase()+g.slice(1):g;e.handleChange(b)},S=()=>{let g=(a.ownerDocument??document).getSelection();if(!g||g.rangeCount===0)return null;let u=g.anchorNode;return!u||!a.contains(u)?null:(u.nodeType===Node.ELEMENT_NODE?u:u.parentElement)?.closest('strong[data-seg="completed"][data-param-id]')?.dataset.paramId??null};r.addEventListener("click",g=>{g.target?.closest("[data-aia-pill]")||a.focus()},{signal:c}),a.addEventListener("input",()=>{m||(f=performance.now(),h(),e.handleCaretAfterInput(T(a)))},{signal:c});let x=a.ownerDocument??document;if(x.addEventListener("selectionchange",()=>{let g=x.getSelection();if(!g||g.rangeCount===0||!a.contains(g.anchorNode))return;let u=g.isCollapsed?S():null,b=e.store.get().editingParam?.id??null;if(u&&u!==b){e.startEditingParam(u);return}performance.now()-f<50||e.handleCaretMove(T(a))},{signal:c}),a.addEventListener("compositionstart",()=>{m=!0},{signal:c}),a.addEventListener("compositionend",()=>{m=!1,h()},{signal:c}),a.addEventListener("beforeinput",g=>{let u=g,b=u.inputType;if(b==="insertParagraph"||b==="insertLineBreak"||b==="insertFromDrop"){g.preventDefault();return}if(b.startsWith("insert")||b.startsWith("delete")){let y=b.startsWith("delete")?"":u.data??"";e.replaceEditingRange(y)&&g.preventDefault()}},{signal:c}),a.addEventListener("paste",g=>{g.preventDefault();let u=(g.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!u)return;let b=a.ownerDocument??document,y=b.getSelection();if(!y||y.rangeCount===0)return;let P=y.getRangeAt(0);if(!a.contains(P.startContainer))return;P.deleteContents();let E=b.createTextNode(u);P.insertNode(E),P.setStartAfter(E),P.collapse(!0),y.removeAllRanges(),y.addRange(P),h()},{signal:c}),a.addEventListener("keydown",g=>e.handleKeyDown(g),{signal:c}),a.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:c}),a.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:c}),l&&l.addEventListener("click",g=>{let u=e.store.get();if(!(!!u.text||u.completedParams.length>0)||!e.onSubmit)return;g.stopPropagation(),e.onSubmit(N(u.text,u.completedParams,u.skippedParams))&&e.afterSubmit?.()},{signal:c}),e.autoFocus!==!1){a.focus();let g=a.ownerDocument??document,u=g.getSelection(),b=u&&u.rangeCount>0&&a.contains(u.anchorNode);if(u&&!b){let y=g.createRange();y.selectNodeContents(a),y.collapse(!0),u.removeAllRanges(),u.addRange(y)}}if(typeof ResizeObserver<"u"){let g=new ResizeObserver(()=>ot(a,s));g.observe(a),p.signal.addEventListener("abort",()=>g.disconnect(),{once:!0})}return{input:a,inlinePillContainer:s,dropdown:i,submitButton:d,abort:p}}function Le(n,e,t){let{input:i,inlinePillContainer:r,dropdown:o,submitButton:a}=n,{pillPlacement:s,setActivePill:d,selectOption:l,store:p}=t;i.setAttribute("aria-expanded",String(e.isDropdownOpen));let c=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(c?i.setAttribute("aria-activedescendant",c):i.removeAttribute("aria-activedescendant"),a){let x=!!e.text||e.completedParams.length>0;a.disabled=!x}let m=i.dataset.newParamId??"",f=e.newParamId!==null&&e.newParamId!==m;if(fe({input:i,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused}),s==="inline"){let x=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;x||e.actionableSuggestions.length>0?ue(r,e.actionableSuggestions,0,d,!1,x,e.isActivePillSelected):Ie(r)}else Ie(r);ot(i,r),f?(i.focus(),C(i,e.caretOffset??e.text.length)):e.isFocused&&F(i)!==e.text&&C(i,e.text.length);let h=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:null,S=h??e.actionableSuggestions[0];ge(o,{suggestions:S?[{...S,options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation,listboxId:t.listboxId,pills:h?[h]:e.actionableSuggestions,showPills:s==="dropdown",showSkipButton:t.showSkipButton&&!e.editingParam,skipDisabled:e.inSelectionAnimation,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,onSelect:l,onHighlight:x=>p.set({activeDropdownIndex:x}),onPillClick:d,onSkip:t.skipActivePill,onProductSelect:t.selectProduct,onProductFocusChange:x=>p.set({isFocused:x})})}function at(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,a=r.length===0&&n.text.length>0&&n.placeholderText.length>0&&n.placeholderText.toLowerCase().startsWith(n.text.toLowerCase());(o||a)&&n.placeholderText&&(r=`${n.placeholderText} `);let s=Be(r,e.text);s>0&&(r=r.slice(0,r.length-s));let d=r.length>0&&r[r.length-1]!==" ",l=`${r}${d?" ":""}${e.text} `,p=(o||a)&&l.length>0?l[0].toUpperCase()+l.slice(1):l,c=p.toLowerCase().lastIndexOf(e.text.toLowerCase()),m=c>=0?p.slice(c,c+e.text.length):e.text,f={id:crypto.randomUUID(),placeholder:"",type:t.type,text:m,kind:e.kind,suggestionType:t.type,suggestionPlaceholder:t.text,options:t.options??[],metadata:e.metadata},h=n.actionableSuggestions.length-1;return{patch:{text:p,filterBase:p.length,completedParams:[...n.completedParams,f],newParamId:f.id,caretOffset:p.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:!0,inSelectionAnimation:!0,pendingSpan:null},telemetry:{selectedOption:e.text,otherOptions:n.filteredOptions.filter(S=>S.text!==e.text).map(S=>S.text)},consumedSuggestion:t,remainingActionable:h}}function he(n){let e=n,t=new Set,i=[],r=!1;return{get:()=>e,set:o=>{let a=typeof o=="function"?o(e):o,s=e;if(e={...e,...a},i.push([e,s]),!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[p,c]=l;for(let m of t)m(p,c)}}catch(d){throw i.length=0,d}finally{r=!1}}},subscribe:o=>(t.add(o),()=>{t.delete(o)})}}function lt(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(a=>{let s={...a,...r(a)};return o(s)}):n.set(o)},peek:o=>{let a={...n.get(),...o};return{...a,...e(a)}},subscribe:o=>n.subscribe((a,s)=>{let d={...s,...r(s)},l={...a,...r(a)};o(l,d)})}}var Me=!1;function dt(){if(Me||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){Me=!0;return}Me=!0;let n=document.createElement("style");n.setAttribute("data-magicx-aia",""),n.textContent=Zt,document.head.appendChild(n)}var Zt=`@layer layout {
|
|
1
|
+
"use strict";var Fe=Object.defineProperty;var Ut=Object.getOwnPropertyDescriptor;var Gt=Object.getOwnPropertyNames;var qt=Object.prototype.hasOwnProperty;var Wt=(n,e)=>{for(var t in e)Fe(n,t,{get:e[t],enumerable:!0})},Qt=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Gt(e))!qt.call(n,r)&&r!==t&&Fe(n,r,{get:()=>e[r],enumerable:!(i=Ut(e,r))||i.enumerable});return n};var jt=n=>Qt(Fe({},"__esModule",{value:!0}),n);var Wn={};Wt(Wn,{AIAutocomplete:()=>Re,ATTRIBUTION_URL:()=>qe,ModeController:()=>V,OPTIONS_GRID_MOBILE_QUERY:()=>z,SKIPPED_PARAM_TEXT:()=>$e,WEEKDAY_LABELS:()=>q,addMonths:()=>J,buildAttributionUrl:()=>Ee,buildDateOptions:()=>Z,buildQuery:()=>C,buildSubmitResult:()=>K,cellDay:()=>ee,cellIso:()=>L,computeOptionsGridLayout:()=>ye,createStore:()=>ke,cursorIsAtEnd:()=>fe,extractPlainText:()=>Y,formatDate:()=>He,getCursorOffset:()=>A,getFooterHint:()=>Te,isOptionsGridMobileViewport:()=>ve,isoDate:()=>T,monthLabel:()=>X,optionsGridTemplateColumns:()=>Se,parseDate:()=>W,parseLooseDate:()=>Q,plainTextLength:()=>me,previousGraphemeBoundary:()=>ge,renderEditableContent:()=>De,resolveFormatType:()=>D,resolveIdentifiedDate:()=>ne,selectedIsoFromText:()=>F,setCursorOffset:()=>E,withSkippedParams:()=>H});module.exports=jt(Wn);var G=["January","February","March","April","May","June","July","August","September","October","November","December"],q=["S","M","T","W","T","F","S"],Ze="aiaDate",et="aiaDay",Xe=n=>String(n).padStart(2,"0");function T(n){return`${n.getFullYear()}-${Xe(n.getMonth()+1)}-${Xe(n.getDate())}`}function He(n){return`${G[n.getMonth()]} ${n.getDate()} ${n.getFullYear()}`}function W(n){if(!n)return null;let e=/^\s*([A-Za-z]+)\s+(\d{1,2})\s+(\d{4})\s*$/.exec(n);if(!e)return null;let t=G.findIndex(a=>a.toLowerCase()===e[1].toLowerCase());if(t<0)return null;let i=Number(e[2]),r=Number(e[3]),o=new Date(r,t,i);return o.getMonth()!==t||o.getDate()!==i?null:o}function X(n){return`${G[n.month]} ${n.year}`}function Be(){let n=new Date;return{year:n.getFullYear(),month:n.getMonth()}}function tt(n){return{year:n.getFullYear(),month:n.getMonth()}}function J(n,e){let t=new Date(n.year,n.month+e,1);return{year:t.getFullYear(),month:t.getMonth()}}function Je(){return{text:"",is_tappable:!1,kind:null}}function Z(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(Je());for(let r=1;r<=t;r++){let o=new Date(n.year,n.month,r);i.push({text:He(o),is_tappable:!0,kind:null,metadata:{[Ze]:T(o),[et]:r}})}for(;i.length%q.length!==0;)i.push(Je());return i}function F(n){let e=W(n);return e?T(e):null}function L(n){let e=n?.metadata?.[Ze];return typeof e=="string"?e:null}function ee(n){let e=n?.metadata?.[et];return typeof e=="number"?e:null}function Yt(n){return n.replace(/(\d+)(?:st|nd|rd|th)\b/g,"$1")}function nt(n){let e=n.toLowerCase().replace(/\.$/,"");return e.length<3?-1:G.findIndex(t=>t.toLowerCase().startsWith(e))}function zt(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 it(n,e,t){let i=new Date(n,e,t);return i.getMonth()===e&&i.getDate()===t?i:null}function Q(n,e={}){if(!n)return null;let t=e.today??new Date,i=Yt(n.trim().toLowerCase()).replace(/\s+/g," "),r=/^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(i);if(r){let l=it(Number(r[1]),Number(r[2])-1,Number(r[3]));return l?T(l):null}let o=/^([a-z]+)\.? (\d{1,2})(?:,? (\d{4}))?$/.exec(i);if(o){let l=nt(o[1]);if(l>=0)return te(l,Number(o[2]),o[3],t)}let a=/^(\d{1,2}) (?:of )?([a-z]+)\.?(?:,? (\d{4}))?$/.exec(i);if(a){let l=nt(a[2]);if(l>=0)return te(l,Number(a[1]),a[3],t)}let s=/^(\d{1,2})[/\-.](\d{1,2})(?:[/\-.](\d{2,4}))?$/.exec(i);if(s){let l=Number(s[1]),d=Number(s[2]);return l>12&&d<=12?te(d-1,l,s[3],t):d>12&&l<=12?te(l-1,d,s[3],t):null}return null}function te(n,e,t,i){if(t){if(t.length!==4)return null;let o=it(Number(t),n,e);return o?T(o):null}let r=zt(n,e,i);return r?T(r):null}function ne(n,e={}){let t=n.isoDate;return typeof t=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t)?t:Q(n.text,e)}var Xt=new Set(["date","dates"]),rt=3;function Jt(n){if(!n)return 0;let e=0;for(let t of n)if(t.is_tappable&&(Q(t.text)!==null&&(e+=1),e>=rt))return e;return e}function Zt(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9]+/).filter(Boolean).map(e=>e.toLowerCase())}function D(n){if(!n)return"options";let e=n.formatType;return e==="date"||e==="options"?e:Zt(n.type).some(t=>Xt.has(t))||Jt(n.options)>=rt?"date":"options"}var ie=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 en="https://api.ai-autocomplete.com",re=`${en}/api/suggest`,ot=new WeakMap;function j(n){return n?.type==="accessToken"}function tn(n){if(!(!n||j(n)))return n}function oe(n){let e=ot.get(n.getAccessToken);return e||(e=new ie(n),ot.set(n.getAccessToken,e)),e}function se(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function ae(n){let e=tn(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}var $e="skipped";function H(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:$e,kind:null}));return i.length>0?[...n,...i]:n}var nn="0.14.0",st=!1;function rn(){return crypto.randomUUID()}function on(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.text},kind:n.kind}}function sn(n,e,t,i,r,o,a,s){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:H(e.map(c=>on(c,t)),a??[]),...r&&r.length>0&&{identified_params:r.map(c=>({type:c.type,value:c.text}))},...o&&o.length>0&&{recently_suggested:o},...d!=null&&{contact_account_count:d},...s!==void 0&&{additional_context:s}},meta:{request_id:rn(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:nn,session_id:i}}}async function at(n,e,t,i,r){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:r})}async function lt(n,e,t){let i=t.apiConfig,r=!t.maskCompletedText,o=sn(n,e,r,t.sessionId,t.identifiedParams,t.recentlySuggested,t.skippedParams,t.additionalContext),a=se(i),s=i?.endpoint??re,l=JSON.stringify(o);if(j(i)){let u=oe(i),p=await u.getToken(),h=await at(s,a,p,l,t.signal);if(h.status===401){let b=await u.getToken(!0);h=await at(s,a,b,l,t.signal)}if(!h.ok)throw new Error(`API error: ${h.status} ${h.statusText}`);return h.json()}let d=ae(i);!d&&!st&&(st=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),d&&(a.Authorization=d);let c=await fetch(s,{method:"POST",headers:a,body:l,signal:t.signal});if(!c.ok)throw new Error(`API error: ${c.status} ${c.statusText}`);return c.json()}function C(n,e){let t=n,i={},r=[],o=[],a=0;for(let s of e){let l=(i[s.type]??0)+1;i[s.type]=l;let c=`{{${s.type.toUpperCase().replace(/\s+/g,"_")}_${l}}}`,u=h=>{let b=t.indexOf(s.text,h);for(;b!==-1&&o.some(S=>b<S.end&&b+s.text.length>S.start);)b=t.indexOf(s.text,b+1);return b},p=u(a);if(p===-1&&(p=u(0)),p!==-1){t=t.slice(0,p)+c+t.slice(p+s.text.length);let h=c.length-s.text.length;for(let b of o)b.start>=p+s.text.length&&(b.start+=h,b.end+=h);o.push({start:p,end:p+c.length}),a=p>=a?p+c.length:a+h}r.push({...s,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 le(n,e,t){return e===0&&n.length>0&&t.length>0&&t.toLowerCase().startsWith(n.toLowerCase())}function N(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 dt(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 a=i.slice(o).join(" ");if(r.startsWith(a.toLowerCase())){let s=t.length-a.length;return n.length-s}}return 0}function R(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 B(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 ct(n,e){return e?n.map(t=>{let i=e[t.type];if(!i)return t;let r=i("");return r?{...t,options:r}:t}):n}function ut(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 pt(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 mt(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 ft(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 Ke(n,e){let t=[],i=[],r=0;for(let o of e){let a=n.indexOf(o.text,r);if(a===-1){i.push(o);continue}t.push({start:a,end:a+o.text.length,param:o}),r=a+o.text.length}return{located:t,missing:i}}function gt(n,e,t){let i=[],r=[],o=0;for(let a of t){let s=n.indexOf(a.text,o);for(;s!==-1&&e.some(l=>s<l.end&&s+a.text.length>l.start);)s=n.indexOf(a.text,s+1);if(s===-1){r.push(a);continue}i.push({start:s,end:s+a.text.length,param:a}),o=s+a.text.length}return{located:i,missing:r}}function ht(n,e,t=[]){let i=Ke(n,e).located,r=gt(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),a=[],s=0;for(let d of o)d.start>s&&a.push({type:"text",value:n.slice(s,d.start)}),a.push(d.segment),s=d.end;let l=n.slice(s);return l&&a.push({type:"text",value:l}),a}function bt(n,e){let{located:t,missing:i}=Ke(n,e);return{valid:t.map(r=>r.param),invalid:i}}function de(n,e,t){let i=Ke(n,e).located,{located:r,missing:o}=gt(n,i,t);return{valid:r.map(a=>a.param),invalid:o}}function an(n){if(n instanceof Error)return n;try{return new Error(String(n))}catch{return new Error("Unknown error")}}var ln=100,dn=300,cn=2,ce=class{constructor(e,t,i,r,o,a,s,l={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=r;this.getOnError=o;this.getSessionId=a;this.getAdditionalContext=s;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 a=this.store.get(),s=a.pendingSpan?mt(a.pendingSpan.snapshot,a.actionableSuggestions):void 0,l=await lt(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig(),identifiedParams:a.identifiedParams,recentlySuggested:s,skippedParams:a.skippedParams,additionalContext:this.getAdditionalContext()});if(r!==this.fetchVersion)return;let d=(l.data.input??[]).filter(g=>g.source==="identified").map(g=>({id:crypto.randomUUID(),type:g.type,text:g.text})),c=ct(l.data.suggestions??[],this.getOptionOverrides()),u=l.data.input??[],p=u[u.length-1],h=this.store.get().text,b,S;if(p?.state==="in_progress"){S=!0;let g=h.toLowerCase().lastIndexOf(p.text.toLowerCase());b=g!==-1?g:o}else S=!1,b=o;let m=c.filter(g=>g.type!=="placeholder")[0],f=null;if(m&&D(m)!=="date"){let g=N(h,b,S),y=B(m.options,g);y&&(f={id:crypto.randomUUID(),placeholder:"",type:m.type,text:y.text,kind:y.kind,suggestionType:m.type,suggestionPlaceholder:m.text,options:m.options??[],metadata:y.metadata},c=c.filter(P=>P!==m),this.callbacks.onAutoMatch?.({active:m,matched:y,rawQuery:e}))}this.store.set(g=>{let y=f?[...g.completedParams,f]:g.completedParams,P=de(g.text,y,d).valid,v=new Set(a.skippedParams.map(w=>w.id)),I=new Set(g.skippedParams.filter(w=>!v.has(w.id)).map(w=>w.type));return{suggestions:I.size>0?c.filter(w=>w.type==="placeholder"||!I.has(w.type)):c,isLoading:!1,isReady:l.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:b,filterInProgress:S,identifiedParams:P,...f?{completedParams:y}:{}}})}catch(a){let s=an(a);r===this.fetchVersion&&(this.store.set({error:s,isLoading:!1}),this.getOnError()?.(s))}finally{if(r===this.fetchVersion&&this.store.get().isLoading)try{this.store.set({isLoading:!1})}catch{}}}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}let t=i=>{let r=this.store.get();if(!r.text&&r.completedParams.length===0)return this.doFetch("",[]),!0;let o=r.suggestions.filter(g=>g.type==="placeholder").map(g=>g.text).join(" "),a=k(r.text,r.filterBase,o),s=N(r.text,a,r.filterInProgress),d=r.suggestions.filter(g=>g.type!=="placeholder")[0],c=r.activeFormatType==="date",p=(d&&!c?R(d.options,s):[]).filter(g=>g.is_tappable),h=d&&!c?B(d.options,s)!==null:!1,b=s.trim().length>0;if(p.length>0&&!h&&b||le(r.text,r.completedParams.length,o))return!1;let{rawQuery:S,completedParams:x}=C(r.text,r.completedParams),m=S.length<r.lastRawQuery.length,f=Math.abs(S.length-r.lastRawQuery.length);return m||f>=i?(this.doFetch(S,x),!0):!1};this.debounceTimer=setTimeout(()=>{t(cn)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},ln),this.slowDebounceTimer=setTimeout(()=>t(1),dn)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var yt='[contenteditable="false"]',$;function un(){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 ue(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(yt))return!0;t=t.parentNode}return!1}function pe(n){return(n.ownerDocument??document).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return ue(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function Y(n){let e=pe(n),t="",i=e.nextNode();for(;i;)t+=i.data,i=e.nextNode();return t}function me(n){let e=pe(n),t=0,i=e.nextNode();for(;i;)t+=i.data.length,i=e.nextNode();return t}function A(n){let e=(n.ownerDocument??document).getSelection();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(ue(r,n)&&r!==n)return null;let o=0;for(let a=0;a<i&&a<r.childNodes.length;a++)o+=St(r.childNodes[a],n);return o+xt(r,n)}return t.nodeType!==Node.TEXT_NODE||ue(t,n)?null:xt(t,n)+i}function St(n,e){if(n.nodeType===Node.TEXT_NODE)return ue(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(yt))return 0;let i=0;for(let r of Array.from(t.childNodes))i+=St(r,e);return i}function xt(n,e){let t=pe(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 E(n,e){let t=n.ownerDocument??document,i=t.getSelection();if(!i)return;let r=Math.max(0,Math.min(e,me(n))),o=pe(n),a=0,s=null,l=0,d=o.nextNode(),c=null;for(;d;){let p=d.data.length;if(r<a+p){s=d,l=r-a;break}if(r===a+p){let h=o.nextNode();h?(s=h,l=0):(s=d,l=p);break}a+=p,c=d,d=o.nextNode()}let u=t.createRange();if(s){let p=s.parentElement?.closest('strong[data-seg="completed"]');p&&p!==n&&n.contains(p)?l===0?u.setStartBefore(p):l===s.data.length?u.setStartAfter(p):u.setStart(s,l):u.setStart(s,l)}else c?u.setStart(c,c.data.length):u.setStart(n,0);u.collapse(!0),i.removeAllRanges(),i.addRange(u)}function fe(n){let e=A(n);return e==null?!1:e>=me(n)}function ge(n,e){if(e<=0)return 0;let t=un();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 K(n,e,t=[]){let{rawQuery:i,completedParams:r}=C(n,e);return{query:n.trim(),raw_query:i,completed_params:H(r,t)}}function Ve(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")?fe(n):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function Ue(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?A(n):null}var he=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:r}=this.ctx,o=this.getEffectiveColumns(),a=r(),s=this.getTappableIndices(o);if((e.shiftKey||e.metaKey||e.ctrlKey||e.altKey)&&(e.key==="ArrowDown"||e.key==="ArrowUp"||e.key==="ArrowLeft"||e.key==="ArrowRight"))return;let l=this.ctx.getOptionsPosition()==="above";switch(e.key){case"ArrowDown":{let d=Ve(e.target,t),c=!!t.editingParam;if(!d&&!c&&t.activeDropdownIndex<0)break;if(t.activeDropdownIndex<0){if(l)break;e.preventDefault();let h=t.activeFormatType==="date"?this.dateEntryIndex(t,!1):s[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:h});break}if(s.length===0)return;this.store.set({activeDropdownIndex:h});break}if(e.preventDefault(),s.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)/o);if(Math.floor(t.activeDropdownIndex/o)===h){this.store.set({activeDropdownIndex:-1});break}}let u=s.indexOf(t.activeDropdownIndex),p=u<s.length-1?u+1:0;this.store.set({activeDropdownIndex:s[p]});break}case"ArrowUp":{if(t.activeDropdownIndex<0){if(!l)break;let u=Ve(e.target,t),p=!!t.editingParam;if(!u&&!p)break;e.preventDefault();let h=t.activeFormatType==="date"?this.dateEntryIndex(t,!0):this.firstTappableInBottomRow(o)??s[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:h});break}if(s.length===0)return;this.store.set({activeDropdownIndex:h});break}if(s.length===0)break;if(e.preventDefault(),t.activeFormatType==="date"){this.stepDateWeek(t,-7);break}if(t.activeDropdownIndex<o){this.store.set({activeDropdownIndex:-1});break}let d=s.indexOf(t.activeDropdownIndex),c=d>0?d-1:s.length-1;this.store.set({activeDropdownIndex:s[c]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeFormatType==="date"){this.stepDateDay(t,1);break}if(t.activeDropdownIndex%o<o-1){let u=t.activeDropdownIndex+1;u<t.filteredOptions.length&&t.filteredOptions[u]?.is_tappable&&this.store.set({activeDropdownIndex:u})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let c=e.target.closest("[data-aia-input]")??e.target,u=t.editingTail;this.ctx.exitEditMode?.(),E(c,u);break}Ve(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%o>0){let d=t.activeDropdownIndex-1;d>=0&&t.filteredOptions[d]?.is_tappable&&this.store.set({activeDropdownIndex:d});break}if(!t.editingParam&&this.ctx.startEditingParamAtCaret){let d=Ue(e.target);d!=null&&this.ctx.startEditingParamAtCaret(d)}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let d=e.target.closest("[data-aia-input]")??e.target,c=t.editingAnchor;this.ctx.exitEditMode?.(),E(d,c);break}if(this.ctx.startEditingParamAtCaret){let d=Ue(e.target);d!=null&&this.ctx.startEditingParamAtCaret(d)&&e.preventDefault()}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let d=Ue(e.target);if(d==null)break;this.ctx.removeParamAtCaret(d)&&e.preventDefault();break}case"Enter":{e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable?this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i):a&&a(K(t.text,t.completedParams,t.skippedParams))&&this.ctx.afterSubmit?.();break}case"Tab":{let d=t.filteredOptions.map((p,h)=>p.is_tappable?h:-1).filter(p=>p!==-1);if(d.length===0)break;if(!t.isDropdownOpen){if(t.actionableSuggestions.length===0)break;e.preventDefault();let p=e.shiftKey?d[d.length-1]:d[0];this.store.set({pillTapped:!0,activeDropdownIndex:p});break}e.preventDefault();let c=d.indexOf(t.activeDropdownIndex),u;if(c<0)u=e.shiftKey?d.length-1:0;else{let p=e.shiftKey?-1:1;u=(c+p+d.length)%d.length}this.store.set({activeDropdownIndex:d[u]});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 d=e.target.closest("[data-aia-input]")??e.target,c=t.editingTail;this.ctx.exitEditMode?.(),E(d,c)}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=T(new Date),r=e.filteredOptions.findIndex(a=>L(a)===i);if(r>=0)return r;let o=e.filteredOptions.map((a,s)=>a.is_tappable?s:-1).filter(a=>a!==-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,a)=>o.is_tappable?a:-1).filter(o=>o!==-1),r=Array.from({length:e},()=>[]);for(let o of i)r[o%e].push(o);return r.flat()}getEffectiveColumns(){let e=document.getElementById(this.ctx.listboxId);if(!e)return this.ctx.columns;let i=document.getElementById(`${this.ctx.listboxId}-option-0`)?.parentElement??null;for(;i;){let r=getComputedStyle(i).gridTemplateColumns;if(r&&r!=="none"){let o=r.split(" ").filter(Boolean).length;if(o>0)return o}if(i===e)break;i=i.parentElement}return this.ctx.columns}clickOrSelect(e,t,i){let r=document.getElementById(`${i}-option-${e}`);r?r.click():this.ctx.selectOption(t[e])}};var be=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),a=t.suggestions.filter(d=>d.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:d}=C(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:d,selectedPill:r.text,otherPills:o.map(c=>c.text)})}let s=[...a,r,...o],l=this.store.peek({suggestions:s}).filteredOptions.findIndex(d=>d.is_tappable);this.store.set({suggestions:s,pillTapped:!0,activeDropdownIndex:l})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};var xe=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 a=r.transform(o),s=Array.isArray(a)?a:[],l=r.limit!=null?s.slice(0,r.limit):s;if(t.aborted||!i())return;this.commit(l)}catch(o){if(t.aborted||pn(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 pn(n){return n instanceof Error&&n.name==="AbortError"}var z="(max-width: 768px)";var mn="var(--aia-option-row-height, 37px)",fn="var(--aia-grid-scroll-top, 0px) + var(--aia-grid-scroll-bottom, 0px)";function ye(n,e){let t=(i,r)=>({cols:i,rows:r,maxHeight:`calc(${r} * ${mn} + ${fn})`});return e?t(1,Math.min(n,5)):n>=5&&n<=6?t(2,Math.ceil(n/2)):t(1,Math.min(n,4))}function Se(n){return Array.from({length:n},()=>"minmax(0,1fr)").join(" ")}function ve(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(z).matches}function vt(n,e){let t=e.dropdownTrigger??"auto",i=e.closeDropdownOnBlur??!0,a=n.filteredOptionsLength>0||n.activePillHasNoOptions||n.hasProducts;if(n.inEditMode){let s=i?n.isFocused:!0;return a&&s}if(t==="auto"){let s=i?n.isFocused:!0,l=n.text.replace(/\s+$/,"").length,d=n.caretOffset==null||n.caretOffset>=l;return(a||n.isLoading)&&s&&d}return t==="manual"?(a||n.isLoading)&&n.pillTapped:!1}function Ge(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 gn(n){if(!n)return Be();let[e,t]=n.split("-").map(Number);return{year:e,month:t-1}}function hn(n){let e=W(n);return e?tt(e):Be()}function Pt(n,e){let t=ht(n.text,n.completedParams,n.identifiedParams),i=n.suggestions.filter(v=>v.type!=="placeholder"),r=i[0],o=r?e.optionOverrides?.[r.type]:void 0,a=n.suggestions.filter(v=>v.type==="placeholder").map(v=>v.text).join(" "),s=k(n.text,Math.min(n.filterBase,n.text.length),a),d=s===0&&le(n.text,n.completedParams.length,a)?"":N(n.text,s,n.filterInProgress),c=r?o?o(d.trim())??r.options??[]:r.options??[]:[],u=n.editingParam!=null&&n.editingAnchor!=null,p;if(u&&n.editingParam&&n.editingAnchor!=null){let v=n.editingParam.id,I=n.completedParams.some(U=>U.id===v),_=n.caretOffset??n.editingAnchor,w=I?"":n.text.slice(n.editingAnchor,_);p=R(n.editingParam.options,w)}else p=R(c,d);let h=e.showNonTappableOptions===!1;h&&(p=p.filter(v=>v.is_tappable));let b=n.editingIdentified,S=b?{type:b.type}:u?n.editingParam&&{type:n.editingParam.suggestionType,options:n.editingParam.options}:r,x=D(S),m=null;if(x==="date"){let v=Ge({...n,actionableSuggestions:i}),I=n.dateViewMonth;m=I&&I.key===v?{year:I.year,month:I.month}:b?gn(b.iso):hn(n.editingParam?.text),p=Z(m)}let f=v=>h?v.is_tappable:!0,g;if(u){let v=n.editingParam?.options??[];g=n.editingParam!=null&&v.filter(f).length===0}else{let v=r?o?o("")??r.options??[]:r.options??[]:[];g=r!=null&&v.filter(f).length===0}let y=vt({inEditMode:u||b!=null,filteredOptionsLength:p.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading,pillTapped:n.pillTapped,activePillHasNoOptions:g,hasProducts:n.products.length>0},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),P=y&&n.activeDropdownIndex>=0&&!!p[n.activeDropdownIndex]?.is_tappable;return{segments:t,actionableSuggestions:i,filteredOptions:p,activeFormatType:x,dateView:m,placeholderText:a,isDropdownOpen:y,isActivePillSelected:P}}function Pe(n){return n.mode==="fresh"?bn(n):xn(n)}function bn(n){let{text:e,completedParams:t,suggestions:i,filterBase:r,filterInProgress:o}=n,s=i.filter(y=>y.type!=="placeholder")[0];if(!s?.options)return null;let l=i.filter(y=>y.type==="placeholder").map(y=>y.text).join(" "),d=k(e,r,l),c=N(e,d,o),u=B(s.options,c);if(!u)return null;let p=u.text.toLowerCase(),h=e.toLowerCase().lastIndexOf(p),b=h>=0?h:Math.max(0,e.length-u.text.length),S=b+u.text.length,x=e.slice(b,S),f=S<e.length&&e[S]===" "?S+1:S,g={id:crypto.randomUUID(),placeholder:"",type:s.type,text:x,kind:u.kind,suggestionType:s.type,suggestionPlaceholder:s.text,options:s.options??[],metadata:u.metadata};return{patch:{text:e,completedParams:[...t,g],suggestions:i.filter(y=>y!==s),filterBase:f,newParamId:g.id,caretOffset:f,activeDropdownIndex:-1},caretPos:f}}function xn(n){let{text:e,completedParams:t,editingParam:i,editingAnchor:r,editingTail:o}=n;if(t.some(g=>g.id===i.id))return null;let a=e.slice(r,o),s=B(i.options,a);if(!s)return null;let l=s.text.toLowerCase(),d=a.toLowerCase().lastIndexOf(l),c=r+Math.max(0,d),u=c+s.text.length,p=e.slice(c,u),b=u<e.length&&e[u]===" "?u+1:u,S={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:p,kind:s.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:s.metadata},x=t.length,m=0;for(let g=0;g<t.length;g++){let y=e.indexOf(t[g].text,m);if(y!==-1){if(y>=b){x=g;break}m=y+t[g].text.length}}let f=[...t];return f.splice(x,0,S),{patch:{text:e,completedParams:f,newParamId:S.id,filterBase:b,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:b,activeDropdownIndex:-1},caretPos:b}}function we(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(a=>a.id===e);if(!i)return;let r=0,o=-1;for(let a of t.completedParams){let s=t.text.indexOf(a.text,r);if(s!==-1){if(a.id===e){o=s;break}r=s+a.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:a}=e===""?we(t.text,r,o):{text:t.text.slice(0,r)+e+t.text.slice(o)},s=r+e.length;return this.deps.store.set(l=>({text:a,completedParams:l.completedParams.filter(d=>d.id!==i.id),editingTail:s,caretOffset:s,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(s),this.tryPromote(),!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.tryPromote()}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:C(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:i.options.filter(m=>m.text!==e.text).map(m=>m.text)});let a=t.text.slice(0,r),s=t.text.slice(o),l=r===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,d=s.length===0||s[0]!==" ",c=d?`${l} `:l,u=a+c+s,p=r+c.length+(d?0:1),h={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:l,kind:e.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:e.metadata},b=t.completedParams.findIndex(m=>m.id===i.id),S=t.completedParams.filter(m=>m.id!==i.id),x=b>=0?Math.min(b,S.length):S.length;S.splice(x,0,h),this.deps.store.set({text:u,completedParams:S,newParamId:h.id,filterBase:p,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:p,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.deps.startSelectionAnimationTimer(),this.deps.scheduleSetCursor(p),this.deps.fetchNow()}tryPromote(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let t=Pe({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 qe="https://ai-autocomplete.com";function Ee(n=qe){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 Te(n,e){return n?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}var wt="data-aia-key";function M(n,e,t){let i=new Map;for(let a of Array.from(n.children)){let s=a.getAttribute(wt);s!=null&&i.set(s,a)}let r=new Set,o=[];for(let a=0;a<e.length;a++){let s=e[a],l=t.keyOf(s,a);r.add(l);let d=i.get(l);d||(d=t.create(s,a),d.setAttribute(wt,l)),t.update?.(d,s,a),n.children[a]!==d&&n.insertBefore(d,n.children[a]??null),o.push(d)}for(let[a,s]of i)r.has(a)||s.remove();return o}function Et(n,e,t,i,r,o,a){let s=n.querySelector(".magicx-aia-datepicker");if(!r||e.length===0){s?.remove();return}s||(s=vn(),n.appendChild(s));let l=s.querySelector(".magicx-aia-datepicker-month");l&&(l.textContent=X(r));let d=s.querySelector("[data-aia-date-prev]"),c=s.querySelector("[data-aia-date-next]");d&&(d.onclick=()=>a.onPreviousMonth()),c&&(c.onclick=()=>a.onNextMonth());let u=s.querySelector(".magicx-aia-datepicker-grid");u&&yn(u,e,t,i,o,a)}function yn(n,e,t,i,r,o){let a=T(new Date);M(n,e,{keyOf:(s,l)=>L(s)??`pad-${l}`,create:s=>Sn(s),update:(s,l,d)=>{let c=L(l),u=d===t&&l.is_tappable;s.id=`${i}-option-${d}`,s.dataset.aiaIndex=String(d),s.setAttribute("aria-selected",String(u)),s.classList.toggle("magicx-aia-date-cell--highlighted",u),s.classList.toggle("magicx-aia-date-cell--today",c!=null&&c===a),s.classList.toggle("magicx-aia-date-cell--selected",c!=null&&r!=null&&c===r),l.is_tappable?(s.onclick=()=>{s.classList.add("magicx-aia-date-cell--pressed"),o.onSelect(l),setTimeout(()=>s.classList.remove("magicx-aia-date-cell--pressed"),500)},s.onmouseenter=()=>{let p=Number.parseInt(s.dataset.aiaIndex??"-1",10);p>=0&&o.onHighlight(p)}):(s.onclick=null,s.onmouseenter=null)}})}function Sn(n){let e=document.createElement("div");e.setAttribute("role","option"),e.setAttribute("data-aia-option",""),e.setAttribute("data-aia-date-cell","");let t=ee(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 vn(){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(Ct("prev","Previous month","\u2039"),t,Ct("next","Next month","\u203A"));let i=document.createElement("div");i.className="magicx-aia-datepicker-weekdays",i.setAttribute("aria-hidden","true");for(let o of q){let a=document.createElement("span");a.className="magicx-aia-datepicker-weekday",a.textContent=o,i.appendChild(a)}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 Ct(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 Tt=[125,69];function It(n,e){return e?1:n===0?.7:n===1?.4:.2}function Ie(n,e,t,i,r=!1,o=!1,a=!1){let s=n.querySelector(".magicx-aia-pill-list");if(s||(s=document.createElement("span"),s.className="magicx-aia-pill-list",n.appendChild(s)),o&&e.length===0){s.setAttribute("data-aia-pill-list-loading",""),s.innerHTML="";for(let l=0;l<Tt.length;l++){let d=Tt[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(It(l,!1)),s.appendChild(c)}return}o?s.setAttribute("data-aia-pill-list-loading",""):s.removeAttribute("data-aia-pill-list-loading");for(let l of s.querySelectorAll("[data-aia-pill-skeleton]"))l.remove();M(s,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,p=a&&c===t&&!o,h=["magicx-aia-pill"];r&&h.push("magicx-aia-pill--rounded"),o&&h.push("magicx-aia-pill--skeleton"),u.className=h.join(" "),u.style.width="",u.style.opacity=String(It(c,p)),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 We(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var Pn="Products";function At(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 s=document.createElement("div");s.className="magicx-aia-products-label",s.id=`${t}-products-label`,s.textContent=Pn;let l=document.createElement("div");l.className="magicx-aia-products-row",l.setAttribute("data-aia-products-row",""),o.append(s,l),n.appendChild(o)}let a=o.querySelector(".magicx-aia-products-row");a&&M(a,e,{keyOf:s=>wn(s),create:s=>Cn(s,i,r),update:(s,l,d)=>{s.id=`${t}-product-${d}`,s.dataset.aiaIndex=String(d)}})}function Qe(n,e){let t=n.querySelectorAll("[data-aia-product]");for(let i of t)i.tabIndex=e?0:-1}function wn(n){return[n.id,n.title,n.url,n.imageUrl,n.price,n.vendor].map(e=>e??"").join("\0")}function Cn(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 s=document.createElement("img");s.className="magicx-aia-product-image",s.src=n.imageUrl,s.alt="",s.loading="lazy",s.decoding="async",r.appendChild(s)}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 s=document.createElement("span");s.className="magicx-aia-product-vendor",s.textContent=n.vendor,o.appendChild(s)}let a=document.createElement("span");if(a.className="magicx-aia-product-title",a.textContent=n.title,o.appendChild(a),n.price){let s=document.createElement("span");s.className="magicx-aia-product-price",s.textContent=n.price,o.appendChild(s)}return i.appendChild(o),i.addEventListener("click",s=>{s.metaKey||s.ctrlKey||s.shiftKey||s.altKey||s.button!==0||(s.preventDefault(),e(n))}),i.addEventListener("keydown",s=>{s.key!=="Enter"&&s.key!==" "||(s.preventDefault(),e(n))}),i.addEventListener("focus",()=>t(!0)),i.addEventListener("blur",s=>{s.relatedTarget?.closest("[data-aia-dropdown]")||t(!1)}),i}function En(n,e){let{cols:t,maxHeight:i}=ye(e,ve());n.style.gridTemplateColumns=Se(t),n.style.setProperty("--aia-grid-max-height",i)}function Ot(n,e,t,i,r,o,a,s=""){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)),En(l,e.length),In(l,e,t,i,r,o,a),Tn(l,s)}function Tn(n,e){n.dataset.aiaGroup!==e&&(n.dataset.aiaGroup=e,n.scrollTop=0)}function In(n,e,t,i,r,o,a){let s=a?"1":"0";M(n,e,{keyOf:l=>`${l.text}\0${s}`,create:l=>An(l,a),update:(l,d,c)=>{let u=c===t&&!a;l.id=`${o}-option-${c}`,l.dataset.aiaIndex=String(c),l.setAttribute("aria-selected",String(u)),l.classList.toggle("magicx-aia-option--highlighted",u),!a&&d.is_tappable?(l.onclick=()=>{l.classList.add("magicx-aia-option--pressed"),i(d),setTimeout(()=>l.classList.remove("magicx-aia-option--pressed"),500)},l.onmouseenter=()=>{let p=Number.parseInt(l.dataset.aiaIndex??"-1",10);p>=0&&r(p)}):(l.onclick=null,l.onmouseenter=null)}})}function An(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("div");r.className="magicx-aia-streaks",t.appendChild(r);let o=document.createElement("div");o.className="magicx-aia-streaks-vert",t.appendChild(o);let a=document.createElement("span");a.className="magicx-aia-option-content";let s=document.createElement("span");if(s.className="magicx-aia-option-text",s.textContent=n.icon?`${n.icon} ${n.text}`:n.text,a.appendChild(s),n.tag){let l=document.createElement("span");l.className="magicx-aia-option-tag",l.textContent=n.tag,a.appendChild(l)}return t.appendChild(a),t}var On=[159,119,164];function Ae(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}function Oe(n,e){let{filteredOptions:t,activeIndex:i,isOpen:r,isLoading:o,pills:a,showPills:s,isActivePillSelected:l,onSelect:d,onHighlight:c,onPillClick:u,onSkip:p}=e,h=a.length>0,b=s&&h,S=t.length>0,x=e.products.length>0,m=r&&(S||b||o||x);if(m?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"),!m){Qe(n,!1);return}x?n.setAttribute("data-aia-has-products",""):n.removeAttribute("data-aia-has-products");let f=n.querySelector(".aia-stack");f||(f=document.createElement("div"),f.className="aia-stack",f.style.setProperty("--aia-stack-space","8px"),n.appendChild(f));let g=e.showSkipButton&&h&&!e.isInputEmpty,y=b||o&&s||g,P=f.querySelector(".magicx-aia-pill-bar");if(y){P||(P=document.createElement("div"),P.className="magicx-aia-pill-bar aia-cluster",P.setAttribute("data-nowrap",""),P.setAttribute("data-aia-pillbar",""),f.insertBefore(P,f.firstChild));let O=P.querySelector(".magicx-aia-pill-scroll");O||(O=document.createElement("span"),O.className="magicx-aia-pill-scroll",O.setAttribute("data-aia-pill-scroll",""),P.insertBefore(O,P.firstChild)),Ie(O,s?a:[],0,u,!0,o&&s,l),kn(P,g,o||e.skipDisabled,a[0],p)}else P&&P.remove();let v=e.suggestions[0],I=v?`${v.type} ${v.text}`:"",_=e.formatType==="date";Ot(f,_?[]:t,i,d,c,e.listboxId,o,I),Et(f,_?t:[],i,e.listboxId,_?e.dateView:null,e.selectedDateIso,{onSelect:d,onHighlight:c,onPreviousMonth:e.onPreviousMonth,onNextMonth:e.onNextMonth});let w=f.querySelector(".magicx-aia-skeleton-bars");if(o&&!S){if(!w){w=document.createElement("div"),w.className="magicx-aia-skeleton-bars",w.setAttribute("data-aia-skeleton-bars","");for(let O of On){let _e=document.createElement("span");_e.className="magicx-aia-skeleton-bar",_e.style.width=`${O}px`,w.appendChild(_e)}f.appendChild(w)}}else w&&w.remove();At(f,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange),Qe(n,!0);let U=f.querySelector(".magicx-aia-footer")??Ln(),Vt=i>=0&&!!t[i]?.is_tappable;Mn(U,Te(Vt,e.isInputEmpty)),U.isConnected||f.appendChild(U),Dn(f,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-datepicker",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"])}function Dn(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 kn(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",a=>a.preventDefault()),n.appendChild(o)),o.setAttribute("aria-label",i?`Skip ${i.text}`:"Skip"),o.disabled=t,o.onclick=t?null:()=>r()}function Mn(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 Ln(){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=Ee(),o.target="_blank",o.rel="noopener noreferrer",o.style.setProperty("--aia-cluster-gap","2px");let a=document.createElement("span");a.className="magicx-aia-footer-brand",a.textContent="AI";let s=document.createElement("span");return s.className="magicx-aia-footer-badge",s.textContent="Autocomplete",o.append(a,s),e.append(t,o),n.append(e),n}function Dt(n,e){let t=Ae(e.listboxId);return n.appendChild(t),{dropdown:t}}function je(n,e,t){Oe(n.dropdown,{suggestions:e.editingIdentified?[{type:e.editingIdentified.type,text: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,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:F(e.editingParam?.text),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 Nn=6,Rn=.3;function kt(n){return n<=0?"0px":`${(-Math.min(Rn,2*Nn/n)).toFixed(3)}px`}function De(n){let{input:e,segments:t,newParamId:i,editingParamId:r,placeholderText:o,isFocused:a}=n,s=t.length===0;e.dataset.aiaEmpty=s?"true":"false",s&&o?e.dataset.placeholder=o:delete e.dataset.placeholder;let l=t.map(x=>`${x.type}:${x.value}`).join("\0"),d=e.dataset.segKey??"",c=e.dataset.newParamId??"",u=e.dataset.editingParamId??"";if(l===d&&(i??"")===c&&(r??"")===u)return;let p=a?A(e):null;e.dataset.segKey=l,e.dataset.newParamId=i??"",e.dataset.editingParamId=r??"";let h=e.ownerDocument??document,b=h.createDocumentFragment(),S=0;for(let x of t)if(S+=x.value.length,x.type==="completed"){let m=h.createElement("strong");m.dataset.seg="completed",m.dataset.paramId=x.param.id;let f=x.param.id===i,g=x.param.id===r,y=["magicx-aia-segment","magicx-aia-segment--completed"];f&&y.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),g&&y.push("magicx-aia-segment--editing"),m.className=y.join(" "),m.style.letterSpacing=kt(x.value.length),m.textContent=x.value,b.appendChild(m)}else if(x.type==="identified"){let m=h.createElement("strong");m.dataset.seg="identified",m.dataset.paramId=x.param.id;let f=["magicx-aia-segment","magicx-aia-segment--completed"];x.param.id===r&&f.push("magicx-aia-segment--editing"),m.className=f.join(" "),m.style.letterSpacing=kt(x.value.length),m.textContent=x.value,b.appendChild(m)}else b.appendChild(h.createTextNode(x.value));e.replaceChildren(b),e.dataset.aiaTextLength=String(S),p!=null&&E(e,Math.max(0,Math.min(p,S)))}var _n='<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 Mt(){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=_n,n}function Fn(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function Lt(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 Nt(n,e){let{listboxId:t}=e,i=Ae(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 a=document.createElement("div");a.className="magicx-aia-input",a.setAttribute("data-aia-input",""),a.setAttribute("contenteditable",Fn()?"plaintext-only":"true"),a.setAttribute("role","combobox"),a.setAttribute("aria-autocomplete","list"),a.setAttribute("aria-haspopup","listbox"),a.setAttribute("aria-controls",t),a.setAttribute("aria-expanded","false"),a.setAttribute("spellcheck","true"),a.setAttribute("enterkeyhint","send"),o.appendChild(a);let s=document.createElement("span");s.className="magicx-aia-pill-list-container",s.setAttribute("data-aia-pill-list-container",""),o.appendChild(s);let l=null,d=null;e.submitButton===void 0?(l=Mt(),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,p=!1,h=0,b=()=>{let m=Y(a),g=m.length>0&&m[0]!==m[0].toUpperCase()?m[0].toUpperCase()+m.slice(1):m;e.handleChange(g)},S=()=>{let m=(a.ownerDocument??document).getSelection();if(!m||m.rangeCount===0)return null;let f=m.anchorNode;return!f||!a.contains(f)?null:(f.nodeType===Node.ELEMENT_NODE?f:f.parentElement)?.closest("strong[data-param-id]")?.dataset.paramId??null};r.addEventListener("click",m=>{m.target?.closest("[data-aia-pill]")||a.focus()},{signal:u}),a.addEventListener("input",()=>{p||(h=performance.now(),b(),e.handleCaretAfterInput(A(a)))},{signal:u});let x=a.ownerDocument??document;if(x.addEventListener("selectionchange",()=>{let m=x.getSelection();if(!m||m.rangeCount===0||!a.contains(m.anchorNode))return;let f=m.isCollapsed?S():null,g=e.store.get(),y=g.editingParam?.id??g.editingIdentified?.id??null;if(f&&f!==y){e.startEditingParam(f);return}performance.now()-h<50||e.handleCaretMove(A(a))},{signal:u}),a.addEventListener("compositionstart",()=>{p=!0},{signal:u}),a.addEventListener("compositionend",()=>{p=!1,b()},{signal:u}),a.addEventListener("beforeinput",m=>{let f=m,g=f.inputType;if(g==="insertParagraph"||g==="insertLineBreak"||g==="insertFromDrop"){m.preventDefault();return}if(g.startsWith("insert")||g.startsWith("delete")){let y=g.startsWith("delete")?"":f.data??"";e.replaceEditingRange(y)&&m.preventDefault()}},{signal:u}),a.addEventListener("paste",m=>{m.preventDefault();let f=(m.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!f)return;let g=a.ownerDocument??document,y=g.getSelection();if(!y||y.rangeCount===0)return;let P=y.getRangeAt(0);if(!a.contains(P.startContainer))return;P.deleteContents();let v=g.createTextNode(f);P.insertNode(v),P.setStartAfter(v),P.collapse(!0),y.removeAllRanges(),y.addRange(P),b()},{signal:u}),a.addEventListener("keydown",m=>e.handleKeyDown(m),{signal:u}),a.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:u}),a.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:u}),d&&d.addEventListener("click",m=>{let f=e.store.get();if(!(!!f.text||f.completedParams.length>0)||!e.onSubmit)return;m.stopPropagation(),e.onSubmit(K(f.text,f.completedParams,f.skippedParams))&&e.afterSubmit?.()},{signal:u}),e.autoFocus!==!1){a.focus();let m=a.ownerDocument??document,f=m.getSelection(),g=f&&f.rangeCount>0&&a.contains(f.anchorNode);if(f&&!g){let y=m.createRange();y.selectNodeContents(a),y.collapse(!0),f.removeAllRanges(),f.addRange(y)}}if(typeof ResizeObserver<"u"){let m=new ResizeObserver(()=>Lt(a,s));m.observe(a),c.signal.addEventListener("abort",()=>m.disconnect(),{once:!0})}return{input:a,inlinePillContainer:s,dropdown:i,submitButton:l,abort:c}}function Ye(n,e,t){let{input:i,inlinePillContainer:r,dropdown:o,submitButton:a}=n,{pillPlacement:s,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"),a){let x=!!e.text||e.completedParams.length>0;a.disabled=!x}let p=i.dataset.newParamId??"",h=e.newParamId!==null&&e.newParamId!==p;if(De({input:i,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused}),s==="inline"){let x=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;x||e.actionableSuggestions.length>0?Ie(r,e.actionableSuggestions,0,l,!1,x,e.isActivePillSelected):We(r)}else We(r);Lt(i,r),h?(i.focus(),E(i,e.caretOffset??e.text.length)):e.isFocused&&Y(i)!==e.text&&E(i,e.text.length);let b=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:e.editingIdentified?{type:e.editingIdentified.type,text:e.editingIdentified.type,required:!0,options:[]}:null,S=b??e.actionableSuggestions[0];Oe(o,{suggestions:S?[{...S,options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation,listboxId:t.listboxId,pills:b?[b]:e.actionableSuggestions,showPills:s==="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:F(e.editingParam?.text),onSelect:d,onHighlight:x=>c.set({activeDropdownIndex:x}),onPillClick:l,onSkip:t.skipActivePill,onPreviousMonth:t.showPreviousMonth,onNextMonth:t.showNextMonth,onProductSelect:t.selectProduct,onProductFocusChange:x=>c.set({isFocused:x})})}function Rt(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,a=r.length===0&&n.text.length>0&&n.placeholderText.length>0&&n.placeholderText.toLowerCase().startsWith(n.text.toLowerCase());(o||a)&&n.placeholderText&&(r=`${n.placeholderText} `);let s=dt(r,e.text);s>0&&(r=r.slice(0,r.length-s));let l=r.length>0&&r[r.length-1]!==" ",d=`${r}${l?" ":""}${e.text} `,c=(o||a)&&d.length>0?d[0].toUpperCase()+d.slice(1):d,u=c.toLowerCase().lastIndexOf(e.text.toLowerCase()),p=u>=0?c.slice(u,u+e.text.length):e.text,h={id:crypto.randomUUID(),placeholder:"",type:t.type,text:p,kind:e.kind,suggestionType:t.type,suggestionPlaceholder:t.text,options:t.options??[],metadata:e.metadata},b=n.actionableSuggestions.length-1;return{patch:{text:c,filterBase:c.length,completedParams:[...n.completedParams,h],newParamId:h.id,caretOffset:c.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:!0,inSelectionAnimation:!0,pendingSpan:null},telemetry:{selectedOption:e.text,otherOptions:n.filteredOptions.filter(S=>S.text!==e.text).map(S=>S.text)},consumedSuggestion:t,remainingActionable:b}}function ke(n){let e=n,t=new Set,i=[],r=!1;return{get:()=>e,set:o=>{let a=typeof o=="function"?o(e):o,s=e;if(e={...e,...a},i.push([e,s]),!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 p of t)p(c,u)}}catch(l){throw i.length=0,l}finally{r=!1}}},subscribe:o=>(t.add(o),()=>{t.delete(o)})}}function _t(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(a=>{let s={...a,...r(a)};return o(s)}):n.set(o)},peek:o=>{let a={...n.get(),...o};return{...a,...e(a)}},subscribe:o=>n.subscribe((a,s)=>{let l={...s,...r(s)},d={...a,...r(a)};o(d,l)})}}var ze=!1;function Ft(){if(ze||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){ze=!0;return}ze=!0;let n=document.createElement("style");n.setAttribute("data-magicx-aia",""),n.textContent=Hn,document.head.appendChild(n)}var Hn=`@layer layout {
|
|
2
2
|
.aia-stack {
|
|
3
3
|
display: flex;
|
|
4
4
|
flex-direction: column;
|
|
@@ -1202,6 +1202,149 @@
|
|
|
1202
1202
|
animation: magicx-aia-fadeIn 400ms cubic-bezier(0.4, 0, 0.2, 1) forwards;
|
|
1203
1203
|
}
|
|
1204
1204
|
|
|
1205
|
+
/* --- Datepicker (replaces the options grid for date suggestions) ---
|
|
1206
|
+
|
|
1207
|
+
Every colour resolves through the same --aia-option-* chain the option rows
|
|
1208
|
+
use. The dropdown paints a background but sets no \`color\`, so anything here
|
|
1209
|
+
relying on \`color: inherit\` would pick up the HOST page's text colour and go
|
|
1210
|
+
black on a dark panel \u2014 and \`prefers-color-scheme\` can't be used to guess,
|
|
1211
|
+
because the panel's darkness comes from --aia-surface, which the media query
|
|
1212
|
+
says nothing about. Going through the option chain means one consumer
|
|
1213
|
+
override restyles the calendar and the options together. */
|
|
1214
|
+
.magicx-aia-datepicker {
|
|
1215
|
+
display: flex;
|
|
1216
|
+
flex-direction: column;
|
|
1217
|
+
gap: 4px;
|
|
1218
|
+
padding: 4px 2px 8px;
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1221
|
+
.magicx-aia-datepicker-header {
|
|
1222
|
+
display: flex;
|
|
1223
|
+
align-items: center;
|
|
1224
|
+
justify-content: space-between;
|
|
1225
|
+
gap: 8px;
|
|
1226
|
+
padding: 2px 6px 6px;
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
.magicx-aia-datepicker-month {
|
|
1230
|
+
font-family: inherit;
|
|
1231
|
+
font-size: var(--aia-date-month-font-size, 14px);
|
|
1232
|
+
font-weight: 500;
|
|
1233
|
+
line-height: 20px;
|
|
1234
|
+
color: var(--aia-option-color-selected, var(--aia-color-text-default, #fff));
|
|
1235
|
+
}
|
|
1236
|
+
|
|
1237
|
+
.magicx-aia-datepicker-nav {
|
|
1238
|
+
display: inline-flex;
|
|
1239
|
+
align-items: center;
|
|
1240
|
+
justify-content: center;
|
|
1241
|
+
width: 24px;
|
|
1242
|
+
height: 24px;
|
|
1243
|
+
padding: 0;
|
|
1244
|
+
border: none;
|
|
1245
|
+
border-radius: 6px;
|
|
1246
|
+
background: transparent;
|
|
1247
|
+
font-family: inherit;
|
|
1248
|
+
font-size: 16px;
|
|
1249
|
+
line-height: 1;
|
|
1250
|
+
color: var(--aia-option-color, var(--aia-color-text-muted, #c1c4cb));
|
|
1251
|
+
cursor: pointer;
|
|
1252
|
+
transition:
|
|
1253
|
+
color 150ms ease-out,
|
|
1254
|
+
background-color 150ms ease-out;
|
|
1255
|
+
}
|
|
1256
|
+
|
|
1257
|
+
.magicx-aia-datepicker-nav:hover {
|
|
1258
|
+
color: var(--aia-option-color-selected, var(--aia-color-text-default, #fff));
|
|
1259
|
+
background: var(--aia-option-bg, transparent);
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
.magicx-aia-datepicker-weekdays,
|
|
1263
|
+
.magicx-aia-datepicker-grid {
|
|
1264
|
+
display: grid;
|
|
1265
|
+
/* The 7 columns live on the cell container itself, not on an ancestor:
|
|
1266
|
+
KeyboardController.getEffectiveColumns() measures grid-template-columns by
|
|
1267
|
+
walking up from option-0's PARENT, and it is this number that makes
|
|
1268
|
+
ArrowDown mean "+1 week". */
|
|
1269
|
+
grid-template-columns: repeat(7, minmax(0, 1fr));
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
.magicx-aia-datepicker-weekday {
|
|
1273
|
+
padding: 2px 0;
|
|
1274
|
+
text-align: center;
|
|
1275
|
+
font-family: inherit;
|
|
1276
|
+
font-size: var(--aia-date-weekday-font-size, 11px);
|
|
1277
|
+
font-weight: 500;
|
|
1278
|
+
line-height: 16px;
|
|
1279
|
+
color: var(--aia-option-color, var(--aia-color-text-muted, #c1c4cb));
|
|
1280
|
+
opacity: 0.7;
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
.magicx-aia-date-cell {
|
|
1284
|
+
display: flex;
|
|
1285
|
+
align-items: center;
|
|
1286
|
+
justify-content: center;
|
|
1287
|
+
/* Deliberately NOT sized here. Giving the grid item a definite size (an
|
|
1288
|
+
aspect-ratio, a width) stops it stretching to its track, so it parks at
|
|
1289
|
+
the track's start edge and the whole month drifts left of the weekday
|
|
1290
|
+
header above it \u2014 the two grids agree on their columns, and only the
|
|
1291
|
+
items disagree, which makes it look like a column-count bug. The cell
|
|
1292
|
+
fills its track; the square is the number span inside it. */
|
|
1293
|
+
min-width: 0;
|
|
1294
|
+
/* Keeps a month readable in a narrow dropdown without letting a 6-row month
|
|
1295
|
+
grow the panel past the options grid it replaces. */
|
|
1296
|
+
height: var(--aia-date-row-height, 40px);
|
|
1297
|
+
font-family: inherit;
|
|
1298
|
+
font-size: var(--aia-date-cell-font-size, 14px);
|
|
1299
|
+
font-weight: 450;
|
|
1300
|
+
line-height: 20px;
|
|
1301
|
+
color: var(--aia-option-color, var(--aia-color-text-muted, #c1c4cb));
|
|
1302
|
+
}
|
|
1303
|
+
|
|
1304
|
+
/* The visual box: everything a cell paints \u2014 fill, ring, press \u2014 lands here so
|
|
1305
|
+
it reads as a square centred in its column rather than a full-width band. */
|
|
1306
|
+
.magicx-aia-date-cell-number {
|
|
1307
|
+
display: flex;
|
|
1308
|
+
align-items: center;
|
|
1309
|
+
justify-content: center;
|
|
1310
|
+
width: var(--aia-date-cell-size, 36px);
|
|
1311
|
+
height: var(--aia-date-cell-size, 36px);
|
|
1312
|
+
border-radius: 8px;
|
|
1313
|
+
}
|
|
1314
|
+
|
|
1315
|
+
.magicx-aia-date-cell--day {
|
|
1316
|
+
cursor: pointer;
|
|
1317
|
+
}
|
|
1318
|
+
|
|
1319
|
+
.magicx-aia-date-cell--blank {
|
|
1320
|
+
cursor: default;
|
|
1321
|
+
}
|
|
1322
|
+
|
|
1323
|
+
.magicx-aia-date-cell--day:hover .magicx-aia-date-cell-number,
|
|
1324
|
+
.magicx-aia-date-cell--highlighted .magicx-aia-date-cell-number {
|
|
1325
|
+
color: var(--aia-option-color-selected, var(--aia-color-text-default, #fff));
|
|
1326
|
+
background: var(--aia-option-bg, transparent);
|
|
1327
|
+
font-weight: 500;
|
|
1328
|
+
}
|
|
1329
|
+
|
|
1330
|
+
/* Today reads as an outline, the committed answer as a fill \u2014 so a re-edited
|
|
1331
|
+
date can show both at once without either being ambiguous. */
|
|
1332
|
+
.magicx-aia-date-cell--today .magicx-aia-date-cell-number {
|
|
1333
|
+
box-shadow: inset 0 0 0 1px
|
|
1334
|
+
var(--aia-date-today-ring, var(--aia-option-color, var(--aia-color-text-muted, #c1c4cb)));
|
|
1335
|
+
}
|
|
1336
|
+
|
|
1337
|
+
.magicx-aia-date-cell--selected .magicx-aia-date-cell-number {
|
|
1338
|
+
color: var(--aia-option-color-selected, var(--aia-color-text-default, #fff));
|
|
1339
|
+
background: var(--aia-date-selected-bg, rgba(var(--aia-streak-rgb, 255, 255, 255), 0.12));
|
|
1340
|
+
font-weight: 500;
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
.magicx-aia-date-cell--pressed .magicx-aia-date-cell-number {
|
|
1344
|
+
opacity: 0.8;
|
|
1345
|
+
background: rgba(var(--aia-streak-rgb, 255, 255, 255), 0.06);
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1205
1348
|
/*
|
|
1206
1349
|
* Built-in appearance defaults \u2014 zero specificity via :where().
|
|
1207
1350
|
* Consumer CSS always wins without !important.
|
|
@@ -1508,5 +1651,5 @@
|
|
|
1508
1651
|
animation-duration: 0s !important;
|
|
1509
1652
|
transition-duration: 0s !important;
|
|
1510
1653
|
}
|
|
1511
|
-
`;var be=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 xe=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=(...a)=>t(...a);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 Se=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 B=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 en(n){return(n??G).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function tn(n){return H(n)?`Bearer ${await q(n).getToken()}`:W(n)}async function ct(n){try{let e=en(n.apiConfig?.endpoint),t=Q(n.apiConfig),i=await tn(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 nn="newParam",pt="suggestionRemoval",rn="selectionAnimation",on=650,sn=0;function an(){return`:ac-${++sn}:`}var ut=500;function mt(){return{text:"",completedParams:[],identifiedParams:[],skippedParams:[],pendingSpan:null,suggestions:[],products:[],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}}var ye=class{constructor(e,t={}){this.inputStore=he(mt());this._listboxId=an();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new Se;this.boundary=new be;this.subscriberCount=0;this.emitter=new xe(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=lt(this.inputStore,i=>ze(i,this.deriveOpts())),t.onSubmit&&this.emitter.on("submit",t.onSubmit),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 ne(this.store,{onPillSelected:({rawQuery:i,selectedPill:r,otherPills:o})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:r,other_pills:o})}}),this.reEdit=new de({store:this.store,scheduleSetCursor:i=>this.scheduleSetCursor(i),fireTelemetry:(i,r)=>this.fireTelemetry(i,r),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer(),fetchNow:()=>this.fetchNow()}),this.productsController=new ie(this.store,()=>this.opts.products),this.fetchController=new X(this.store,()=>this.opts.apiConfig,()=>this.deriveOpts().optionOverrides,()=>this.opts.maskCompletedText,()=>this.emitter.hasListeners("error")?this.emitError:void 0,()=>this.sessionId,()=>this.opts.additionalContext,()=>this.opts.generateStartingStateOptions,{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(a=>a.text!==r.text).map(a=>a.text)})}}),this.keyboardController=new te(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(),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:a}=j(i.text,i.completedParams,i.identifiedParams);a.length>0&&this.store.set({identifiedParams:o})})),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 a=o.anchor;if(i.text!==r.text){let d=$e(r.text,i.text,a);if(d===null){this.store.set({pendingSpan:null});return}a=d}i.text.slice(a).trim().length===0||Ke(i.segments,a)?this.store.set({pendingSpan:null}):a!==o.anchor&&this.store.set({pendingSpan:{anchor:a,snapshot:o.snapshot}})})),this.renderMode!=="headless"&&(dt(),this.setupContainer()),this.renderMode==="full"?this.buildAndRenderFull():this.renderMode==="dropdown"&&this.buildAndRenderDropdown(),this.fetchController.start()}focus(){this.domRefs?.input.focus()}blur(){this.domRefs?.input.blur()}reset(){let e=this.store.get().isFocused;this.store.set({...mt(),isFocused:e,skipNextFetch:!0}),this.sessionId=crypto.randomUUID(),this.fetchController.doFetch("",[])}destroy(){this.fetchController.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=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}setValue(e){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}=le(i,r,o);return this.store.set(p=>({text:d,filterBase:Math.min(p.filterBase>r?Math.max(r,p.filterBase-l):p.filterBase,d.length),...this.withoutChip(p,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(r),!0}let a=ee(i,e),s=i.slice(0,a)+i.slice(e);return this.store.set(d=>({text:s,filterBase:Math.min(d.filterBase,s.length),...this.withoutChip(d,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(a),!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(),C(t.input,e);else{let i=this.opts.setCursor;i&&this.boundary.runListener("setCursor",()=>i(e))}})}clearNewParamId(){this.store.set({newParamId:null})}startEditingParam(e){this.reEdit.start(e)}replaceEditingRange(e){return this.reEdit.replaceRange(e)}exitEditMode(){this.reEdit.exit()}handleCaretAfterInput(e){this.reEdit.caretAfterInput(e)}handleCaretMove(e){this.reEdit.caretMove(e)}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}selectProduct(e){this.emitter.emit("productSelect",e)}handleTextChange(e){this.handleChange(e)}skipActivePill(){let e=this.store.get();if(e.editingParam||e.inSelectionAnimation)return;let t=e.suggestions.filter(s=>s.type==="placeholder"),i=e.suggestions.filter(s=>s.type!=="placeholder");if(i.length===0)return;let r=i[0],o=i.slice(1),a=e.skippedParams.some(s=>s.type===r.type);this.store.set({suggestions:[...t,...o],pillTapped:o.length>0,activeDropdownIndex:-1,...a?{}:{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()}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;Object.assign(this.opts,e),"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.editingParam&&t.editingAnchor!=null&&t.editingTail!=null){this.reEdit.selectOption(e);return}let i=at(t,e);if(i){if(this.fireTelemetry("option",{raw_query:v(t.text,t.completedParams).rawQuery,selected_option:i.telemetry.selectedOption,other_options:i.telemetry.otherOptions}),this.store.set(i.patch),this.startSelectionAnimationTimer(),this.timers.clear(pt),i.remainingActionable>0){let r=i.consumedSuggestion;this.timers.schedule(pt,()=>{this.store.get().suggestions.includes(r)&&this.store.set(o=>({suggestions:o.suggestions.filter(a=>a!==r)}))},ut)}this.fetchNow()}}startSelectionAnimationTimer(){this.timers.schedule(rn,()=>this.store.set({inSelectionAnimation:!1}),ut)}fireTelemetry(e,t){let i=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");ct({source:i,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}deriveOpts(){let e=this.opts.optionOverrides;if(!e)return this.opts;if(e!==this.rawOverrides){this.rawOverrides=e;let t={};for(let[i,r]of Object.entries(e))t[i]=o=>this.boundary.run(`optionOverrides.${i}`,()=>r(o));this.wrappedOverrides=t}return{...this.opts,optionOverrides:this.wrappedOverrides}}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 B(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 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),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=st(this.container,t);let i=()=>{this.domRefs&&Le(this.domRefs,this.store.get(),t)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),Le(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},selectOption:r=>this.selectOption(r),setActivePill:r=>this.pillsController.setActivePill(r),skipActivePill:()=>this.skipActivePill(),selectProduct:r=>this.selectProduct(r)};this.dropdownRefs=nt(this.container,t);let i=()=>{this.dropdownRefs&&ke(this.dropdownRefs,this.store.get(),t)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),ke(this.dropdownRefs,this.store.get(),t),this.subscribeNewParamTimer()}subscribeViewportBreakpoint(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;let t=window.matchMedia(K),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(nn,()=>this.store.set({newParamId:null}),on)}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:r}=Qe(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=O(e.text,Math.min(e.filterBase,e.text.length),e.placeholderText),i=Fe(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))return;let t=e.caretOffset??e.editingAnchor,i=e.text.slice(e.editingAnchor,t);L(e.editingParam.options,i).some(o=>o.is_tappable)||(this.reEdit.exit(),this.fetchNow())}fetchNow(){let e=this.store.get(),{rawQuery:t,completedParams:i}=v(e.text,e.completedParams);this.fetchController.doFetch(t,i)}maybePromoteExactMatch(e){let t=this.store.get(),i=ae({mode:"fresh",text:e,completedParams:t.completedParams,suggestions:t.suggestions,filterBase:t.filterBase,filterInProgress:t.filterInProgress});i&&this.store.set(i.patch)}};0&&(module.exports={AIAutocomplete,ATTRIBUTION_URL,ModeController,OPTIONS_GRID_MOBILE_QUERY,SKIPPED_PARAM_TEXT,buildAttributionUrl,buildQuery,buildSubmitResult,computeOptionsGridLayout,createStore,cursorIsAtEnd,extractPlainText,getCursorOffset,getFooterHint,isOptionsGridMobileViewport,optionsGridTemplateColumns,plainTextLength,previousGraphemeBoundary,renderEditableContent,setCursorOffset,withSkippedParams});
|
|
1654
|
+
`;var Me=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 Le=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=(...a)=>t(...a);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 Ne=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 V=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 Bn(n){return(n??re).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function $n(n){return j(n)?`Bearer ${await oe(n).getToken()}`:ae(n)}async function Ht(n){try{let e=Bn(n.apiConfig?.endpoint),t=se(n.apiConfig),i=await $n(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 Kn="newParam",Bt="suggestionRemoval",Vn="selectionAnimation",Un=650,Gn=0;function qn(){return`:ac-${++Gn}:`}var $t=500;function Kt(){return{text:"",completedParams:[],identifiedParams:[],skippedParams:[],pendingSpan:null,suggestions:[],products:[],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 Re=class{constructor(e,t={}){this.inputStore=ke(Kt());this._listboxId=qn();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new Ne;this.boundary=new Me;this.subscriberCount=0;this.emitter=new Le(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=_t(this.inputStore,i=>Pt(i,this.deriveOpts())),t.onSubmit&&this.emitter.on("submit",t.onSubmit),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 be(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 xe(this.store,()=>this.opts.products),this.fetchController=new ce(this.store,()=>this.opts.apiConfig,()=>this.deriveOpts().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(a=>a.text!==r.text).map(a=>a.text)})}}),this.keyboardController=new he(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:a}=de(i.text,i.completedParams,i.identifiedParams);a.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 a=0,s;for(let l of i.segments){if(l.type==="identified"&&a===o.anchor&&l.value===o.text){s=l.param;break}a+=l.value.length}if(s){this.store.set({editingIdentified:{...o,id:s.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 a=o.anchor;if(i.text!==r.text){let l=ft(r.text,i.text,a);if(l===null){this.store.set({pendingSpan:null});return}a=l}i.text.slice(a).trim().length===0||pt(i.segments,a)?this.store.set({pendingSpan:null}):a!==o.anchor&&this.store.set({pendingSpan:{anchor:a,snapshot:o.snapshot}})})),this.renderMode!=="headless"&&(Ft(),this.setupContainer()),this.renderMode==="full"?this.buildAndRenderFull():this.renderMode==="dropdown"&&this.buildAndRenderDropdown(),this.fetchController.start()}focus(){this.domRefs?.input.focus()}blur(){this.domRefs?.input.blur()}reset(){let e=this.store.get().isFocused;this.store.set({...Kt(),isFocused:e,skipNextFetch:!0}),this.sessionId=crypto.randomUUID(),this.fetchController.doFetch("",[])}destroy(){this.fetchController.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=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}=we(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 a=ge(i,e),s=i.slice(0,a)+i.slice(e);return this.store.set(l=>({text:s,filterBase:Math.min(l.filterBase,s.length),...this.withoutChip(l,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(a),!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(),E(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(s=>s.id===e);if(!i||D(i)!=="date")return!1;let r=0,o=-1;for(let s of t.segments){if(s.type!=="text"&&s.param.id===e){o=r;break}r+=s.value.length}if(o<0)return!1;let a=o+i.text.length;return this.store.set({editingIdentified:{id:e,type:i.type,anchor:o,tail:a,text:i.text,iso:ne(i)},editingParam:null,editingAnchor:null,editingTail:null,caretOffset:a,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=J(t.dateView,e);this.store.set({dateViewMonth:{...i,key:Ge(t)},activeDropdownIndex:-1})}skipActivePill(){let e=this.store.get();if(e.editingParam||e.inSelectionAnimation)return;let t=e.suggestions.filter(s=>s.type==="placeholder"),i=e.suggestions.filter(s=>s.type!=="placeholder");if(i.length===0)return;let r=i[0],o=i.slice(1),a=e.skippedParams.some(s=>s.type===r.type);this.store.set({suggestions:[...t,...o],pillTapped:o.length>0,activeDropdownIndex:-1,...a?{}:{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()}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;Object.assign(this.opts,e),"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=Rt(t,e);if(i){if(this.fireTelemetry("option",{raw_query:C(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(Bt),i.remainingActionable>0){let r=i.consumedSuggestion;this.timers.schedule(Bt,()=>{this.store.get().suggestions.includes(r)&&this.store.set(o=>({suggestions:o.suggestions.filter(a=>a!==r)}))},$t)}this.fetchNow()}}startSelectionAnimationTimer(){this.timers.schedule(Vn,()=>this.store.set({inSelectionAnimation:!1}),$t)}fireTelemetry(e,t){let i=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");Ht({source:i,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}deriveOpts(){let e=this.opts.optionOverrides;if(!e)return this.opts;if(e!==this.rawOverrides){this.rawOverrides=e;let t={};for(let[i,r]of Object.entries(e))t[i]=o=>this.boundary.run(`optionOverrides.${i}`,()=>r(o));this.wrappedOverrides=t}return{...this.opts,optionOverrides:this.wrappedOverrides}}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 V(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 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=Nt(this.container,t);let i=()=>{this.domRefs&&Ye(this.domRefs,this.store.get(),t)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),Ye(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},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=Dt(this.container,t);let i=()=>{this.dropdownRefs&&je(this.dropdownRefs,this.store.get(),t)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),je(this.dropdownRefs,this.store.get(),t),this.subscribeNewParamTimer()}subscribeViewportBreakpoint(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;let t=window.matchMedia(z),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(Kn,()=>this.store.set({newParamId:null}),Un)}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:r}=bt(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=ut(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))return;let t=e.caretOffset??e.editingAnchor,i=e.text.slice(e.editingAnchor,t);R(e.editingParam.options,i).some(o=>o.is_tappable)||(this.reEdit.exit(),this.fetchNow())}fetchNow(){let e=this.store.get(),{rawQuery:t,completedParams:i}=C(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),a=i.anchor===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,s=o.length===0||o[0]!==" ",l=s?`${a} `:a,d=r+l+o,c=i.anchor+l.length+(s?0:1),u={id:crypto.randomUUID(),placeholder:"",type:i.type,text:a,kind:e.kind,suggestionType:i.type,suggestionPlaceholder:i.type,options:[],metadata:e.metadata};this.fireTelemetry("option",{raw_query:C(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:[]}),this.store.set({text:d,completedParams:[...t.completedParams,u],identifiedParams:t.identifiedParams.filter(p=>p.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=Pe({mode:"fresh",text:e,completedParams:t.completedParams,suggestions:t.suggestions,filterBase:t.filterBase,filterInProgress:t.filterInProgress});i&&this.store.set(i.patch)}};0&&(module.exports={AIAutocomplete,ATTRIBUTION_URL,ModeController,OPTIONS_GRID_MOBILE_QUERY,SKIPPED_PARAM_TEXT,WEEKDAY_LABELS,addMonths,buildAttributionUrl,buildDateOptions,buildQuery,buildSubmitResult,cellDay,cellIso,computeOptionsGridLayout,createStore,cursorIsAtEnd,extractPlainText,formatDate,getCursorOffset,getFooterHint,isOptionsGridMobileViewport,isoDate,monthLabel,optionsGridTemplateColumns,parseDate,parseLooseDate,plainTextLength,previousGraphemeBoundary,renderEditableContent,resolveFormatType,resolveIdentifiedDate,selectedIsoFromText,setCursorOffset,withSkippedParams});
|
|
1512
1655
|
//# sourceMappingURL=index.js.map
|