@magicx-eng/ai-autocomplete-vanilla 0.1.12 → 0.1.14
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/index.js +2 -2
- package/index.js.map +1 -1
- package/index.mjs +2 -2
- package/index.mjs.map +1 -1
- package/package.json +1 -1
package/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
function y(i,e){let t=i,o={},n=[];for(let r of e){let s=(o[r.type]??0)+1;o[r.type]=s;let a=`{{${r.type.toUpperCase().replace(/\s+/g,"_")}_${s}}}`,l=t.indexOf(r.text);l!==-1&&(t=t.slice(0,l)+a+t.slice(l+r.text.length)),n.push({...r,placeholder:a})}return{rawQuery:t,completedParams:n}}function C(i,e,t){let o=i.slice(e);if(t||e===0||i[e-1]===" ")return o;let n=o.indexOf(" ");return n===-1?"":o.slice(n+1)}function B(i,e){let t=i.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let o=t.split(" "),n=e.toLowerCase();for(let r=0;r<o.length;r++){let s=o.slice(r).join(" ");if(n.startsWith(s.toLowerCase())){let c=t.length-s.length;return i.length-c}}return 0}function w(i,e){if(!i)return[];let t=e.trimStart();if(!t)return i;let o=t.toLowerCase();return i.filter(n=>!n.is_tappable||n.text.toLowerCase().includes(o))}function k(i,e){if(!i)return null;let t=e.trim();if(!t)return null;let o=t.toLowerCase();return i.find(n=>n.is_tappable&&n.text.toLowerCase()===o)??null}var P=class{constructor(e,t="auto"){this.container=e;this.mode=t;this.mediaQuery=null;this.onSystemChange=e=>{this.container.dataset.mode=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.container.dataset.mode=this.mediaQuery.matches?"dark":"light"):this.container.dataset.mode=this.mode}detachListener(){this.mediaQuery?.removeEventListener("change",this.onSystemChange)}};function H(i,e){let t=[],o=0;for(let r of e){let s=i.indexOf(r.text,o);s!==-1&&(s>o&&t.push({type:"text",value:i.slice(o,s)}),t.push({type:"completed",value:r.text,param:r}),o=s+r.text.length)}let n=i.slice(o);return n&&t.push({type:"text",value:n}),t}function K(i,e){let t=[],o=[],n=0;for(let r of e){let s=i.indexOf(r.text,n);s===-1?o.push(r):(t.push(r),n=s+r.text.length)}return{valid:t,invalid:o}}var S=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 ie="https://api.ai-autocomplete.com/api/suggest",N="/api/telemetry/events",$=new WeakMap;function q(i){return i?.type==="accessToken"}function oe(i){if(!(!i||q(i)))return i}function ne(i){let e=$.get(i.getAccessToken);return e||(e=new S(i),$.set(i.getAccessToken,e)),e}function se(i){let e=i??ie;try{return`${new URL(e).origin}${N}`}catch{return`https://api.ai-autocomplete.com${N}`}}async function re(i){if(q(i))return`Bearer ${await ne(i).getToken()}`;let e=oe(i),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}async function Q(i){try{let e=await re(i.apiConfig);if(!e)return;let t=se(i.apiConfig?.endpoint),o={"Content-Type":"application/json",Authorization:e,...i.apiConfig?.appIdentifier&&{"X-App-Identifier":i.apiConfig.appIdentifier},...i.apiConfig?.headers},n=JSON.stringify({source:i.source,session_id:i.sessionId,type:i.type,at:new Date().toISOString(),query_data:i.queryData});await fetch(t,{method:"POST",headers:o,body:n})}catch{}}var ae="0.1.36",U=!1;function le(){return crypto.randomUUID()}function ce(i,e){return{placeholder:i.placeholder,type:i.type,...e&&{text:i.text},kind:i.kind}}function W(i){return i?.type==="accessToken"}function de(i){if(!(!i||W(i)))return i}var j=new WeakMap;function pe(i){let e=j.get(i.getAccessToken);return e||(e=new S(i),j.set(i.getAccessToken,e)),e}function ue(i,e,t,o){let n=e.find(s=>s.type==="contact"&&s.metadata?.contact_account_count)?.metadata?.contact_account_count,r=typeof n=="number"?n:void 0;return{data:{raw_query:i,completed_params:e.map(s=>ce(s,t)),...r!=null&&{contact_account_count:r}},meta:{request_id:le(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:ae,session_id:o}}}function me(i){return{"Content-Type":"application/json",...i?.appIdentifier&&{"X-App-Identifier":i.appIdentifier},...i?.headers}}async function V(i,e,t,o,n){return fetch(i,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:o,signal:n})}async function G(i,e,t){let o=t.apiConfig,n=!t.maskCompletedText,r=ue(i,e,n,t.sessionId),s=me(o),c=o?.endpoint??"https://api.ai-autocomplete.com/api/suggest",a=JSON.stringify(r);if(W(o)){let u=pe(o),m=await u.getToken(),g=await V(c,s,m,a,t.signal);if(g.status===401){let b=await u.getToken(!0);g=await V(c,s,b,a,t.signal)}if(!g.ok)throw new Error(`API error: ${g.status} ${g.statusText}`);return g.json()}let l=de(o),p=l?.apiKey??"";if(!p&&!U&&(U=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),p){let u=l?.authScheme??"Bearer";s.Authorization=u==="Basic"?`Basic ${btoa(p)}`:`Bearer ${p}`}let d=await fetch(c,{method:"POST",headers:s,body:a,signal:t.signal});if(!d.ok)throw new Error(`API error: ${d.status} ${d.statusText}`);return d.json()}function z(i,e){return e?i.map(t=>{let o=e[t.type];if(!o)return t;let n=o("");if(n.length===0)return t;let r=new Set(n.map(c=>c.text)),s=(t.options??[]).filter(c=>!r.has(c.text));return{...t,options:[...n,...s]}}):i}var ge=100,he=300,fe=2,T=class{constructor(e,t,o,n,r,s,c={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=o;this.getMaskCompletedText=n;this.getOnError=r;this.getSessionId=s;this.callbacks=c;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null}start(){this.doFetch("",[]);let e=this.store.get().text,t=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(o=>{(o.text!==e||o.completedParams!==t)&&(e=o.text,t=o.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let o=new AbortController;this.abortController=o;let n=++this.fetchVersion,r=this.store.get(),s=r.text.length;r.suggestions.some(a=>a.type!=="placeholder")||this.store.set({isLoading:!0}),this.store.set({error:null});try{let a=await G(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:o.signal,apiConfig:this.getApiConfig()});if(n!==this.fetchVersion)return;let l=z(a.data.suggestions??[],this.getOptionOverrides()),p=a.data.input??[],d=p[p.length-1],u=this.store.get().text,m,g;if(d?.state==="in_progress"){g=!0;let x=u.toLowerCase().lastIndexOf(d.text.toLowerCase());m=x!==-1?x:s}else g=!1,m=s;let f=l.filter(x=>x.type!=="placeholder")[0],h=null;if(f){let x=C(u,m,g),v=k(f.options,x);v&&(h={id:crypto.randomUUID(),placeholder:"",type:f.type,text:v.text,kind:v.kind,suggestionType:f.type,suggestionPlaceholder:f.text,options:f.options??[],metadata:v.metadata},l=l.filter(te=>te!==f),this.callbacks.onAutoMatch?.({active:f,matched:v,rawQuery:e}))}this.store.set(x=>({suggestions:l,isLoading:!1,isReady:a.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:m,filterInProgress:g,...h?{completedParams:[...x.completedParams,h]}:{}}))}catch(a){if(n===this.fetchVersion){let l=a instanceof Error?a:new Error(String(a));this.store.set({error:l,isLoading:!1}),this.getOnError()?.(l)}}}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}let t=o=>{let n=this.store.get();if(!n.text&&n.completedParams.length===0)return this.doFetch("",[]),!0;let r=C(n.text,n.filterBase,n.filterInProgress),c=n.suggestions.filter(f=>f.type!=="placeholder")[0],l=(c?w(c.options,r):[]).filter(f=>f.is_tappable),p=c?k(c.options,r)!==null:!1,d=r.trim().length>0;if(l.length>0&&!p&&d)return!1;if(n.completedParams.length===0&&n.text.length>0){let f=n.suggestions.filter(h=>h.type==="placeholder").map(h=>h.text).join(" ");if(f.length>0&&f.toLowerCase().startsWith(n.text.toLowerCase()))return!1}let{rawQuery:u,completedParams:m}=y(n.text,n.completedParams),g=u.length<n.lastRawQuery.length,b=Math.abs(u.length-n.lastRawQuery.length);return g||b>=o?(this.doFetch(u,m),!0):!1};this.debounceTimer=setTimeout(()=>{t(fe)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},ge),this.slowDebounceTimer=setTimeout(()=>t(1),he)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var O=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:o,getOnSubmit:n}=this.ctx,r=this.getEffectiveColumns(),s=n(),c=this.getTappableIndices(r);switch(e.key){case"ArrowDown":{let a=e.target;if(!(a.selectionStart!=null&&a.selectionStart===a.value.length)&&t.activeDropdownIndex<0)break;if(e.preventDefault(),!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:c[0]??0});break}if(c.length===0)return;let p=c.indexOf(t.activeDropdownIndex),d=p<c.length-1?p+1:0;this.store.set({activeDropdownIndex:c[d]});break}case"ArrowUp":{if(c.length===0||t.activeDropdownIndex<0)break;if(e.preventDefault(),t.activeDropdownIndex<r){this.store.set({activeDropdownIndex:-1});break}let a=c.indexOf(t.activeDropdownIndex),l=a>0?a-1:c.length-1;this.store.set({activeDropdownIndex:c[l]});break}case"ArrowRight":{if(t.activeDropdownIndex<0){let l=e.target;l.selectionStart!=null&&l.selectionStart===l.value.length&&t.actionableSuggestions.length>1&&(e.preventDefault(),this.pillsSetActivePill(1));break}if(t.activeDropdownIndex%r<r-1){let l=t.activeDropdownIndex+1;l<t.filteredOptions.length&&t.filteredOptions[l]?.is_tappable&&(e.preventDefault(),this.store.set({activeDropdownIndex:l}))}break}case"ArrowLeft":{if(t.activeDropdownIndex<0)break;if(t.activeDropdownIndex%r>0){let a=t.activeDropdownIndex-1;a>=0&&t.filteredOptions[a]?.is_tappable&&(e.preventDefault(),this.store.set({activeDropdownIndex:a}))}break}case"Enter":{if(e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable)this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,o);else if(s){let{rawQuery:a,completedParams:l}=y(t.text,t.completedParams);s({query:t.text.trim(),raw_query:a,completed_params:l}),this.ctx.afterSubmit?.()}break}case"Tab":{let a=!t.text&&!!t.placeholderText,l=t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable;if(a&&!l){e.preventDefault();let p=t.suggestions.find(d=>d.type==="placeholder");p?this.store.set(d=>({text:t.placeholderText,filterBase:t.placeholderText.length,completedParams:[...d.completedParams,{id:crypto.randomUUID(),placeholder:"",type:p.type,text:t.placeholderText,kind:null,suggestionType:p.type,suggestionPlaceholder:p.text,options:p.options??[]}],suggestions:d.suggestions.filter(u=>u!==p)})):this.store.set({text:t.placeholderText,filterBase:t.placeholderText.length})}else if(l)e.preventDefault(),this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,o);else if(t.isDropdownOpen){let p=t.filteredOptions.findIndex(d=>d.is_tappable);p>=0&&(e.preventDefault(),this.clickOrSelect(p,t.filteredOptions,o))}break}case"Escape":this.store.set({activeDropdownIndex:-1});break}}getTappableIndices(e){let o=this.store.get().filteredOptions.map((r,s)=>r.is_tappable?s:-1).filter(r=>r!==-1),n=Array.from({length:e},()=>[]);for(let r of o)n[r%e].push(r);return n.flat()}getEffectiveColumns(){let t=document.getElementById(`${this.ctx.listboxId}-option-0`)?.parentElement;if(!t)return this.ctx.columns;let o=getComputedStyle(t).gridTemplateColumns.split(" ").filter(Boolean).length;return o>0?o:this.ctx.columns}clickOrSelect(e,t,o){let n=document.getElementById(`${o}-option-${e}`);n?n.click():this.ctx.selectOption(t[e])}pillsSetActivePill(e){let t=this.store.get(),o=t.suggestions.filter(c=>c.type!=="placeholder");if(e<0||e>=o.length)return;let n=o[e],r=o.filter((c,a)=>a!==e),s=t.suggestions.filter(c=>c.type==="placeholder");this.store.set({suggestions:[...s,n,...r],pillTapped:!0,activeDropdownIndex:-1})}};var I=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),o=t.suggestions.filter(c=>c.type!=="placeholder");if(e<0||e>=o.length)return;let n=o[e],r=o.filter((c,a)=>a!==e),s=t.suggestions.filter(c=>c.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:c}=y(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:c,selectedPill:n.text,otherPills:r.map(a=>a.text)})}this.store.set({suggestions:[...s,n,...r],pillTapped:!0,activeDropdownIndex:-1})}removeLastParam(){let e=this.store.get();if(e.completedParams.length===0)return;let t=e.completedParams[e.completedParams.length-1],o={type:t.suggestionType,text:t.suggestionPlaceholder,required:!0,options:t.options};this.store.set(n=>({completedParams:n.completedParams.slice(0,-1),suggestions:[o,...n.suggestions],activeDropdownIndex:-1}))}};function be(i){return i===0?.4:i===1?.3:.15}function A(i,e,t,o,n=!1){let r=i.querySelector(".magicx-aia-pill-list");r||(r=document.createElement("span"),r.className="magicx-aia-pill-list",i.appendChild(r));let s=new Map;for(let a of r.querySelectorAll(".magicx-aia-pill"))s.set(a.dataset.pillKey??"",a);let c=new Set;for(let a=0;a<e.length;a++){let l=e[a],p=`${l.type}-${l.text}`;c.add(p);let d=s.get(p);d||(d=document.createElement("button"),d.type="button",d.dataset.pillKey=p,d.setAttribute("data-aia-pill",""),d.textContent=l.text),d.className=`magicx-aia-pill${n?" magicx-aia-pill--rounded":""}${a===t?" magicx-aia-pill--active":""}`,d.style.opacity=String(be(a)),d.onclick=()=>o(a),r.children[a]!==d&&r.insertBefore(d,r.children[a]??null)}for(let[a,l]of s)c.has(a)||l.remove()}function E(i){let e=document.createElement("div");return e.id=i,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",t=>t.preventDefault()),e}function D(i,e){let{filteredOptions:t,activeIndex:o,isOpen:n,pills:r,showPills:s,onSelect:c,onHighlight:a,onPillClick:l}=e,p=s&&r.length>0;n&&t.length>0||n&&p?i.classList.add("magicx-aia-dropdown--visible"):i.classList.remove("magicx-aia-dropdown--visible");let m=i.querySelector(".magicx-aia-pill-bar");p?(m||(m=document.createElement("div"),m.className="magicx-aia-pill-bar",m.setAttribute("data-aia-pillbar",""),i.insertBefore(m,i.firstChild)),A(m,r,0,l,!0)):m&&m.remove();let g=i.querySelector(".magicx-aia-grid");t.length>0?(g||(g=document.createElement("div"),g.className="magicx-aia-grid",i.appendChild(g)),xe(g,t,o,c,a,e.listboxId)):g&&(g.innerHTML="")}function xe(i,e,t,o,n,r){let s=e.map(l=>l.text).join("\0"),c=i.dataset.optionsKey??"",a=s!==c;if(i.dataset.optionsKey=s,a){let l=document.createDocumentFragment();for(let p=0;p<e.length;p++){let d=e[p],u=ye(d,p,t,o,n,r);l.appendChild(u)}i.innerHTML="",i.appendChild(l)}else{let l=i.querySelectorAll(".magicx-aia-option");for(let p=0;p<l.length;p++){let d=l[p],u=p===t;d.setAttribute("aria-selected",String(u)),u?d.classList.add("magicx-aia-option--highlighted"):d.classList.remove("magicx-aia-option--highlighted")}}}function ye(i,e,t,o,n,r){let s=document.createElement("div");s.id=`${r}-option-${e}`,s.setAttribute("role","option"),s.setAttribute("data-aia-option",""),s.setAttribute("aria-selected",String(e===t)),s.tabIndex=i.is_tappable?0:-1;let c=["magicx-aia-option"];e===t&&c.push("magicx-aia-option--highlighted"),i.is_tappable?c.push("magicx-aia-option--tappable"):c.push("magicx-aia-option--non-tappable"),s.className=c.join(" ");let a=document.createElement("div");a.className="magicx-aia-streaks",s.appendChild(a);let l=document.createElement("div");l.className="magicx-aia-streaks-vert",s.appendChild(l);let p=document.createElement("span");if(p.className="magicx-aia-option-content",p.textContent=i.icon?`${i.icon} ${i.text}`:i.text,i.tag){let d=document.createElement("span");d.className="magicx-aia-option-tag",d.textContent=i.tag,p.appendChild(d)}return s.appendChild(p),i.is_tappable&&(s.addEventListener("click",()=>{s.classList.add("magicx-aia-option--pressed"),o(i),setTimeout(()=>s.classList.remove("magicx-aia-option--pressed"),400)}),s.addEventListener("mouseenter",()=>n(e))),s}function X(i,e){let t=E(e.listboxId);return i.appendChild(t),{dropdown:t}}function M(i,e,t){D(i.dropdown,{suggestions:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,onSelect:t.selectOption,onHighlight:o=>t.store.set({activeDropdownIndex:o}),onPillClick:t.setActivePill})}function Y(i,e,t,o,n){let r=i.querySelector(".magicx-aia-sizer-text"),s=i.querySelector(".magicx-aia-placeholder");if(o&&n){r&&(r.style.display="none"),s||(s=document.createElement("span"),s.className="magicx-aia-placeholder",i.insertBefore(s,i.firstChild)),s.style.display="",s.textContent=`${n} `,i.dataset.segmentKey="";return}s&&(s.style.display="none"),r||(r=document.createElement("span"),r.className="magicx-aia-sizer-text",i.insertBefore(r,i.firstChild)),r.style.display="",r.className=`magicx-aia-sizer-text${t?" magicx-aia-sizer-text--visible":""}`;let c=e.map(p=>`${p.type}:${p.value}`).join("\0"),a=i.dataset.segmentKey??"",l=i.dataset.newParamId??"";if(!(c===a&&(t??"")===l)){i.dataset.segmentKey=c,i.dataset.newParamId=t??"",r.innerHTML="";for(let p of e){let d=document.createElement("span");p.type==="completed"&&(p.param.id===t?d.className="magicx-aia-shimmer-revealed magicx-aia-shimmer-sweep":d.className="magicx-aia-segment magicx-aia-segment--completed"),d.textContent=p.value,r.appendChild(d)}e.length===0&&(r.textContent="\xA0")}}var Se='<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 J(i,e){let{listboxId:t}=e,o=E(t);i.appendChild(o);let n=document.createElement("div");n.className="magicx-aia-input-wrapper",i.appendChild(n);let r=document.createElement("div");r.className="magicx-aia-editor",r.setAttribute("data-aia-editor",""),n.appendChild(r);let s=document.createElement("div");s.className="magicx-aia-sizer",s.setAttribute("aria-hidden","true"),r.appendChild(s);let c=document.createElement("span");s.appendChild(document.createTextNode(" ")),s.appendChild(c);let a=document.createElement("textarea");a.className="magicx-aia-textarea",a.rows=1,a.setAttribute("role","combobox"),a.setAttribute("aria-autocomplete","list"),a.setAttribute("aria-controls",t),a.setAttribute("data-aia-textarea",""),r.appendChild(a);let l=null,p=null;return e.submitButton===void 0?(l=document.createElement("button"),l.type="button",l.className="magicx-aia-submit",l.setAttribute("aria-label","Submit"),l.setAttribute("data-aia-submit",""),l.innerHTML=Se,n.appendChild(l),p=l):e.submitButton!==null&&(p=e.submitButton,p.hasAttribute("data-aia-submit")||p.setAttribute("data-aia-submit",""),n.appendChild(p)),n.addEventListener("click",()=>a.focus()),a.addEventListener("input",()=>{let d=a.value,m=d.length>0&&d[0]!==d[0].toUpperCase()?d[0].toUpperCase()+d.slice(1):d;e.handleChange(m)}),a.addEventListener("keydown",d=>e.handleKeyDown(d)),a.addEventListener("focus",()=>e.store.set({isFocused:!0})),a.addEventListener("blur",()=>e.store.set({isFocused:!1})),p&&p.addEventListener("click",d=>{let u=e.store.get();if(!(!!u.text||u.completedParams.length>0)||!e.onSubmit)return;d.stopPropagation();let{rawQuery:g,completedParams:b}=y(u.text,u.completedParams);e.onSubmit({query:u.text.trim(),raw_query:g,completed_params:b}),e.afterSubmit?.()}),e.autoFocus!==!1&&a.focus(),{textarea:a,dropdown:o,sizer:s,submitButton:l,inlinePillContainer:c}}function L(i,e,t){let{textarea:o,dropdown:n,sizer:r,submitButton:s,inlinePillContainer:c}=i,{pillPlacement:a,setActivePill:l,selectOption:p,store:d}=t;o.value!==e.text&&(o.value=e.text),e.placeholderText?o.placeholder=e.placeholderText:o.removeAttribute("placeholder"),o.setAttribute("aria-expanded",String(e.isDropdownOpen));let u=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(u?o.setAttribute("aria-activedescendant",u):o.removeAttribute("aria-activedescendant"),e.newParamId?o.classList.add("magicx-aia-textarea--hidden"):o.classList.remove("magicx-aia-textarea--hidden"),s){let m=!!e.text||e.completedParams.length>0;s.disabled=!m}Y(r,e.segments,e.newParamId,!e.text,e.placeholderText),a==="inline"?A(c,e.actionableSuggestions,0,l):c.innerHTML="",D(n,{suggestions:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:a==="dropdown",onSelect:p,onHighlight:m=>d.set({activeDropdownIndex:m}),onPillClick:l})}function R(i){let e=i,t=new Set;return{get:()=>e,set:o=>{let n=typeof o=="function"?o(e):o,r={...e,...n},s=e;e=r;for(let c of t)c(r,s)},subscribe:o=>(t.add(o),()=>{t.delete(o)})}}var _=!1;function Z(){if(_||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){_=!0;return}_=!0;let i=document.createElement("style");i.setAttribute("data-magicx-aia",""),i.textContent=ve,document.head.appendChild(i)}var ve=`/* ===================================================================
|
|
1
|
+
function y(o,e){let t=o,i={},s=[];for(let r of e){let n=(i[r.type]??0)+1;i[r.type]=n;let a=`{{${r.type.toUpperCase().replace(/\s+/g,"_")}_${n}}}`,l=t.indexOf(r.text);l!==-1&&(t=t.slice(0,l)+a+t.slice(l+r.text.length)),s.push({...r,placeholder:a})}return{rawQuery:t,completedParams:s}}function v(o,e,t){let i=o.slice(e);if(t||e===0||o[e-1]===" ")return i;let s=i.indexOf(" ");return s===-1?"":i.slice(s+1)}function q(o,e){let t=o.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let i=t.split(" "),s=e.toLowerCase();for(let r=0;r<i.length;r++){let n=i.slice(r).join(" ");if(s.startsWith(n.toLowerCase())){let c=t.length-n.length;return o.length-c}}return 0}function w(o,e){if(!o)return[];let t=e.trimStart();if(!t)return o;let i=t.toLowerCase();return o.filter(s=>!s.is_tappable||s.text.toLowerCase().includes(i))}function F(o,e){if(!o)return null;let t=e.trim();if(!t)return null;let i=t.toLowerCase();return o.find(s=>s.is_tappable&&s.text.toLowerCase()===i)??null}var P=class{constructor(e,t="auto"){this.container=e;this.mode=t;this.mediaQuery=null;this.onSystemChange=e=>{this.container.dataset.mode=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.container.dataset.mode=this.mediaQuery.matches?"dark":"light"):this.container.dataset.mode=this.mode}detachListener(){this.mediaQuery?.removeEventListener("change",this.onSystemChange)}};function Q(o,e){let t=[],i=0;for(let r of e){let n=o.indexOf(r.text,i);n!==-1&&(n>i&&t.push({type:"text",value:o.slice(i,n)}),t.push({type:"completed",value:r.text,param:r}),i=n+r.text.length)}let s=o.slice(i);return s&&t.push({type:"text",value:s}),t}function U(o,e){let t=[],i=[],s=0;for(let r of e){let n=o.indexOf(r.text,s);n===-1?i.push(r):(t.push(r),s=n+r.text.length)}return{valid:t,invalid:i}}var T=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 oe="https://api.ai-autocomplete.com",O=`${oe}/api/suggest`,j=new WeakMap;function C(o){return o?.type==="accessToken"}function se(o){if(!(!o||C(o)))return o}function I(o){let e=j.get(o.getAccessToken);return e||(e=new T(o),j.set(o.getAccessToken,e)),e}function A(o){return{"Content-Type":"application/json",...o?.appIdentifier&&{"X-App-Identifier":o.appIdentifier},...o?.headers}}function E(o){let e=se(o),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}function ne(o){return(o??O).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function re(o){return C(o)?`Bearer ${await I(o).getToken()}`:E(o)}async function V(o){try{let e=ne(o.apiConfig?.endpoint),t=A(o.apiConfig),i=await re(o.apiConfig);i&&(t.Authorization=i);let s=JSON.stringify({source:o.source,session_id:o.sessionId,type:o.type,at:new Date().toISOString(),query_data:o.queryData});await fetch(e,{method:"POST",headers:t,body:s})}catch{}}var ae="0.1.38",G=!1;function le(){return crypto.randomUUID()}function ce(o,e){return{placeholder:o.placeholder,type:o.type,...e&&{text:o.text},kind:o.kind}}function de(o,e,t,i){let s=e.find(n=>n.type==="contact"&&n.metadata?.contact_account_count)?.metadata?.contact_account_count,r=typeof s=="number"?s:void 0;return{data:{raw_query:o,completed_params:e.map(n=>ce(n,t)),...r!=null&&{contact_account_count:r}},meta:{request_id:le(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:ae,session_id:i}}}async function W(o,e,t,i,s){return fetch(o,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:s})}async function z(o,e,t){let i=t.apiConfig,s=!t.maskCompletedText,r=de(o,e,s,t.sessionId),n=A(i),c=i?.endpoint??O,a=JSON.stringify(r);if(C(i)){let p=I(i),m=await p.getToken(),u=await W(c,n,m,a,t.signal);if(u.status===401){let h=await p.getToken(!0);u=await W(c,n,h,a,t.signal)}if(!u.ok)throw new Error(`API error: ${u.status} ${u.statusText}`);return u.json()}let l=E(i);!l&&!G&&(G=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),l&&(n.Authorization=l);let d=await fetch(c,{method:"POST",headers:n,body:a,signal:t.signal});if(!d.ok)throw new Error(`API error: ${d.status} ${d.statusText}`);return d.json()}function X(o,e){return e?o.map(t=>{let i=e[t.type];if(!i)return t;let s=i("");if(s.length===0)return t;let r=new Set(s.map(c=>c.text)),n=(t.options??[]).filter(c=>!r.has(c.text));return{...t,options:[...s,...n]}}):o}var pe=100,ue=300,me=2,D=class{constructor(e,t,i,s,r,n,c={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=s;this.getOnError=r;this.getSessionId=n;this.callbacks=c;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null}start(){this.doFetch("",[]);let e=this.store.get().text,t=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(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 s=++this.fetchVersion,r=this.store.get(),n=r.text.length;r.suggestions.some(a=>a.type!=="placeholder")||this.store.set({isLoading:!0}),this.store.set({error:null});try{let a=await z(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig()});if(s!==this.fetchVersion)return;let l=X(a.data.suggestions??[],this.getOptionOverrides()),d=a.data.input??[],p=d[d.length-1],m=this.store.get().text,u,h;if(p?.state==="in_progress"){h=!0;let b=m.toLowerCase().lastIndexOf(p.text.toLowerCase());u=b!==-1?b:n}else h=!1,u=n;let f=l.filter(b=>b.type!=="placeholder")[0],g=null;if(f){let b=v(m,u,h),S=F(f.options,b);S&&(g={id:crypto.randomUUID(),placeholder:"",type:f.type,text:S.text,kind:S.kind,suggestionType:f.type,suggestionPlaceholder:f.text,options:f.options??[],metadata:S.metadata},l=l.filter(ie=>ie!==f),this.callbacks.onAutoMatch?.({active:f,matched:S,rawQuery:e}))}this.store.set(b=>({suggestions:l,isLoading:!1,isReady:a.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:u,filterInProgress:h,...g?{completedParams:[...b.completedParams,g]}:{}}))}catch(a){if(s===this.fetchVersion){let l=a instanceof Error?a:new Error(String(a));this.store.set({error:l,isLoading:!1}),this.getOnError()?.(l)}}}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}let t=i=>{let s=this.store.get();if(!s.text&&s.completedParams.length===0)return this.doFetch("",[]),!0;let r=v(s.text,s.filterBase,s.filterInProgress),c=s.suggestions.filter(f=>f.type!=="placeholder")[0],l=(c?w(c.options,r):[]).filter(f=>f.is_tappable),d=c?F(c.options,r)!==null:!1,p=r.trim().length>0;if(l.length>0&&!d&&p)return!1;if(s.completedParams.length===0&&s.text.length>0){let f=s.suggestions.filter(g=>g.type==="placeholder").map(g=>g.text).join(" ");if(f.length>0&&f.toLowerCase().startsWith(s.text.toLowerCase()))return!1}let{rawQuery:m,completedParams:u}=y(s.text,s.completedParams),h=m.length<s.lastRawQuery.length,x=Math.abs(m.length-s.lastRawQuery.length);return h||x>=i?(this.doFetch(m,u),!0):!1};this.debounceTimer=setTimeout(()=>{t(me)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},pe),this.slowDebounceTimer=setTimeout(()=>t(1),ue)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var k=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:s}=this.ctx,r=this.getEffectiveColumns(),n=s(),c=this.getTappableIndices(r);switch(e.key){case"ArrowDown":{let a=e.target;if(!(a.selectionStart!=null&&a.selectionStart===a.value.length)&&t.activeDropdownIndex<0)break;if(e.preventDefault(),!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:c[0]??0});break}if(c.length===0)return;let d=c.indexOf(t.activeDropdownIndex),p=d<c.length-1?d+1:0;this.store.set({activeDropdownIndex:c[p]});break}case"ArrowUp":{if(c.length===0||t.activeDropdownIndex<0)break;if(e.preventDefault(),t.activeDropdownIndex<r){this.store.set({activeDropdownIndex:-1});break}let a=c.indexOf(t.activeDropdownIndex),l=a>0?a-1:c.length-1;this.store.set({activeDropdownIndex:c[l]});break}case"ArrowRight":{if(t.activeDropdownIndex<0){let l=e.target;l.selectionStart!=null&&l.selectionStart===l.value.length&&t.actionableSuggestions.length>1&&(e.preventDefault(),this.pillsSetActivePill(1));break}if(t.activeDropdownIndex%r<r-1){let l=t.activeDropdownIndex+1;l<t.filteredOptions.length&&t.filteredOptions[l]?.is_tappable&&(e.preventDefault(),this.store.set({activeDropdownIndex:l}))}break}case"ArrowLeft":{if(t.activeDropdownIndex<0)break;if(t.activeDropdownIndex%r>0){let a=t.activeDropdownIndex-1;a>=0&&t.filteredOptions[a]?.is_tappable&&(e.preventDefault(),this.store.set({activeDropdownIndex:a}))}break}case"Enter":{if(e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable)this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i);else if(n){let{rawQuery:a,completedParams:l}=y(t.text,t.completedParams);n({query:t.text.trim(),raw_query:a,completed_params:l}),this.ctx.afterSubmit?.()}break}case"Tab":{let a=!t.text&&!!t.placeholderText,l=t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable;if(a&&!l){e.preventDefault();let d=t.suggestions.find(p=>p.type==="placeholder");d?this.store.set(p=>({text:t.placeholderText,filterBase:t.placeholderText.length,completedParams:[...p.completedParams,{id:crypto.randomUUID(),placeholder:"",type:d.type,text:t.placeholderText,kind:null,suggestionType:d.type,suggestionPlaceholder:d.text,options:d.options??[]}],suggestions:p.suggestions.filter(m=>m!==d)})):this.store.set({text:t.placeholderText,filterBase:t.placeholderText.length})}else if(l)e.preventDefault(),this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i);else if(t.isDropdownOpen){let d=t.filteredOptions.findIndex(p=>p.is_tappable);d>=0&&(e.preventDefault(),this.clickOrSelect(d,t.filteredOptions,i))}break}case"Escape":this.store.set({activeDropdownIndex:-1});break}}getTappableIndices(e){let i=this.store.get().filteredOptions.map((r,n)=>r.is_tappable?n:-1).filter(r=>r!==-1),s=Array.from({length:e},()=>[]);for(let r of i)s[r%e].push(r);return s.flat()}getEffectiveColumns(){let t=document.getElementById(`${this.ctx.listboxId}-option-0`)?.parentElement;if(!t)return this.ctx.columns;let i=getComputedStyle(t).gridTemplateColumns.split(" ").filter(Boolean).length;return i>0?i:this.ctx.columns}clickOrSelect(e,t,i){let s=document.getElementById(`${i}-option-${e}`);s?s.click():this.ctx.selectOption(t[e])}pillsSetActivePill(e){let t=this.store.get(),i=t.suggestions.filter(c=>c.type!=="placeholder");if(e<0||e>=i.length)return;let s=i[e],r=i.filter((c,a)=>a!==e),n=t.suggestions.filter(c=>c.type==="placeholder");this.store.set({suggestions:[...n,s,...r],pillTapped:!0,activeDropdownIndex:-1})}};var M=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),i=t.suggestions.filter(c=>c.type!=="placeholder");if(e<0||e>=i.length)return;let s=i[e],r=i.filter((c,a)=>a!==e),n=t.suggestions.filter(c=>c.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:c}=y(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:c,selectedPill:s.text,otherPills:r.map(a=>a.text)})}this.store.set({suggestions:[...n,s,...r],pillTapped:!0,activeDropdownIndex:-1})}removeLastParam(){let e=this.store.get();if(e.completedParams.length===0)return;let t=e.completedParams[e.completedParams.length-1],i={type:t.suggestionType,text:t.suggestionPlaceholder,required:!0,options:t.options};this.store.set(s=>({completedParams:s.completedParams.slice(0,-1),suggestions:[i,...s.suggestions],activeDropdownIndex:-1}))}};function ge(o){return o===0?.4:o===1?.3:.15}function L(o,e,t,i,s=!1){let r=o.querySelector(".magicx-aia-pill-list");r||(r=document.createElement("span"),r.className="magicx-aia-pill-list",o.appendChild(r));let n=new Map;for(let a of r.querySelectorAll(".magicx-aia-pill"))n.set(a.dataset.pillKey??"",a);let c=new Set;for(let a=0;a<e.length;a++){let l=e[a],d=`${l.type}-${l.text}`;c.add(d);let p=n.get(d);p||(p=document.createElement("button"),p.type="button",p.dataset.pillKey=d,p.setAttribute("data-aia-pill",""),p.textContent=l.text),p.className=`magicx-aia-pill${s?" magicx-aia-pill--rounded":""}${a===t?" magicx-aia-pill--active":""}`,p.style.opacity=String(ge(a)),p.onclick=()=>i(a),r.children[a]!==p&&r.insertBefore(p,r.children[a]??null)}for(let[a,l]of n)c.has(a)||l.remove()}function R(o){let e=document.createElement("div");return e.id=o,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",t=>t.preventDefault()),e}function _(o,e){let{filteredOptions:t,activeIndex:i,isOpen:s,pills:r,showPills:n,onSelect:c,onHighlight:a,onPillClick:l}=e,d=n&&r.length>0;s&&t.length>0||s&&d?o.classList.add("magicx-aia-dropdown--visible"):o.classList.remove("magicx-aia-dropdown--visible");let u=o.querySelector(".magicx-aia-pill-bar");d?(u||(u=document.createElement("div"),u.className="magicx-aia-pill-bar",u.setAttribute("data-aia-pillbar",""),o.insertBefore(u,o.firstChild)),L(u,r,0,l,!0)):u&&u.remove();let h=o.querySelector(".magicx-aia-grid");t.length>0?(h||(h=document.createElement("div"),h.className="magicx-aia-grid",o.appendChild(h)),he(h,t,i,c,a,e.listboxId)):h&&(h.innerHTML="")}function he(o,e,t,i,s,r){let n=e.map(l=>l.text).join("\0"),c=o.dataset.optionsKey??"",a=n!==c;if(o.dataset.optionsKey=n,a){let l=document.createDocumentFragment();for(let d=0;d<e.length;d++){let p=e[d],m=fe(p,d,t,i,s,r);l.appendChild(m)}o.innerHTML="",o.appendChild(l)}else{let l=o.querySelectorAll(".magicx-aia-option");for(let d=0;d<l.length;d++){let p=l[d],m=d===t;p.setAttribute("aria-selected",String(m)),m?p.classList.add("magicx-aia-option--highlighted"):p.classList.remove("magicx-aia-option--highlighted")}}}function fe(o,e,t,i,s,r){let n=document.createElement("div");n.id=`${r}-option-${e}`,n.setAttribute("role","option"),n.setAttribute("data-aia-option",""),n.setAttribute("aria-selected",String(e===t)),n.tabIndex=o.is_tappable?0:-1;let c=["magicx-aia-option"];e===t&&c.push("magicx-aia-option--highlighted"),o.is_tappable?c.push("magicx-aia-option--tappable"):c.push("magicx-aia-option--non-tappable"),n.className=c.join(" ");let a=document.createElement("div");a.className="magicx-aia-streaks",n.appendChild(a);let l=document.createElement("div");l.className="magicx-aia-streaks-vert",n.appendChild(l);let d=document.createElement("span");if(d.className="magicx-aia-option-content",d.textContent=o.icon?`${o.icon} ${o.text}`:o.text,o.tag){let p=document.createElement("span");p.className="magicx-aia-option-tag",p.textContent=o.tag,d.appendChild(p)}return n.appendChild(d),o.is_tappable&&(n.addEventListener("click",()=>{n.classList.add("magicx-aia-option--pressed"),i(o),setTimeout(()=>n.classList.remove("magicx-aia-option--pressed"),400)}),n.addEventListener("mouseenter",()=>s(e))),n}function Y(o,e){let t=R(e.listboxId);return o.appendChild(t),{dropdown:t}}function H(o,e,t){_(o.dropdown,{suggestions:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,onSelect:t.selectOption,onHighlight:i=>t.store.set({activeDropdownIndex:i}),onPillClick:t.setActivePill})}function J(o,e,t,i,s){let r=o.querySelector(".magicx-aia-sizer-text"),n=o.querySelector(".magicx-aia-placeholder");if(i&&s){r&&(r.style.display="none"),n||(n=document.createElement("span"),n.className="magicx-aia-placeholder",o.insertBefore(n,o.firstChild)),n.style.display="",n.textContent=`${s} `,o.dataset.segmentKey="";return}n&&(n.style.display="none"),r||(r=document.createElement("span"),r.className="magicx-aia-sizer-text",o.insertBefore(r,o.firstChild)),r.style.display="",r.className=`magicx-aia-sizer-text${t?" magicx-aia-sizer-text--visible":""}`;let c=e.map(d=>`${d.type}:${d.value}`).join("\0"),a=o.dataset.segmentKey??"",l=o.dataset.newParamId??"";if(!(c===a&&(t??"")===l)){o.dataset.segmentKey=c,o.dataset.newParamId=t??"",r.innerHTML="";for(let d of e){let p=document.createElement("span");d.type==="completed"&&(d.param.id===t?p.className="magicx-aia-shimmer-revealed magicx-aia-shimmer-sweep":p.className="magicx-aia-segment magicx-aia-segment--completed"),p.textContent=d.value,r.appendChild(p)}e.length===0&&(r.textContent="\xA0")}}var xe='<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 Z(o,e){let{listboxId:t}=e,i=R(t);o.appendChild(i);let s=document.createElement("div");s.className="magicx-aia-input-wrapper",o.appendChild(s);let r=document.createElement("div");r.className="magicx-aia-editor",r.setAttribute("data-aia-editor",""),s.appendChild(r);let n=document.createElement("div");n.className="magicx-aia-sizer",n.setAttribute("aria-hidden","true"),r.appendChild(n);let c=document.createElement("span");n.appendChild(document.createTextNode(" ")),n.appendChild(c);let a=document.createElement("textarea");a.className="magicx-aia-textarea",a.rows=1,a.setAttribute("role","combobox"),a.setAttribute("aria-autocomplete","list"),a.setAttribute("aria-controls",t),a.setAttribute("data-aia-textarea",""),r.appendChild(a);let l=null,d=null;return e.submitButton===void 0?(l=document.createElement("button"),l.type="button",l.className="magicx-aia-submit",l.setAttribute("aria-label","Submit"),l.setAttribute("data-aia-submit",""),l.innerHTML=xe,s.appendChild(l),d=l):e.submitButton!==null&&(d=e.submitButton,d.hasAttribute("data-aia-submit")||d.setAttribute("data-aia-submit",""),s.appendChild(d)),s.addEventListener("click",()=>a.focus()),a.addEventListener("input",()=>{let p=a.value,u=p.length>0&&p[0]!==p[0].toUpperCase()?p[0].toUpperCase()+p.slice(1):p;e.handleChange(u)}),a.addEventListener("keydown",p=>e.handleKeyDown(p)),a.addEventListener("focus",()=>e.store.set({isFocused:!0})),a.addEventListener("blur",()=>e.store.set({isFocused:!1})),d&&d.addEventListener("click",p=>{let m=e.store.get();if(!(!!m.text||m.completedParams.length>0)||!e.onSubmit)return;p.stopPropagation();let{rawQuery:h,completedParams:x}=y(m.text,m.completedParams);e.onSubmit({query:m.text.trim(),raw_query:h,completed_params:x}),e.afterSubmit?.()}),e.autoFocus!==!1&&a.focus(),{textarea:a,dropdown:i,sizer:n,submitButton:l,inlinePillContainer:c}}function B(o,e,t){let{textarea:i,dropdown:s,sizer:r,submitButton:n,inlinePillContainer:c}=o,{pillPlacement:a,setActivePill:l,selectOption:d,store:p}=t;i.value!==e.text&&(i.value=e.text),e.placeholderText?i.placeholder=e.placeholderText:i.removeAttribute("placeholder"),i.setAttribute("aria-expanded",String(e.isDropdownOpen));let m=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(m?i.setAttribute("aria-activedescendant",m):i.removeAttribute("aria-activedescendant"),e.newParamId?i.classList.add("magicx-aia-textarea--hidden"):i.classList.remove("magicx-aia-textarea--hidden"),n){let u=!!e.text||e.completedParams.length>0;n.disabled=!u}J(r,e.segments,e.newParamId,!e.text,e.placeholderText),a==="inline"?L(c,e.actionableSuggestions,0,l):c.innerHTML="",_(s,{suggestions:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:a==="dropdown",onSelect:d,onHighlight:u=>p.set({activeDropdownIndex:u}),onPillClick:l})}function N(o){let e=o,t=new Set;return{get:()=>e,set:i=>{let s=typeof i=="function"?i(e):i,r={...e,...s},n=e;e=r;for(let c of t)c(r,n)},subscribe:i=>(t.add(i),()=>{t.delete(i)})}}var K=!1;function ee(){if(K||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){K=!0;return}K=!0;let o=document.createElement("style");o.setAttribute("data-magicx-aia",""),o.textContent=be,document.head.appendChild(o)}var be=`/* ===================================================================
|
|
2
2
|
Vanilla core styles \u2014 stable BEM class names (magicx-aia-*)
|
|
3
3
|
Auto-injected at runtime on first instantiation.
|
|
4
4
|
=================================================================== */
|
|
@@ -664,5 +664,5 @@ function y(i,e){let t=i,o={},n=[];for(let r of e){let s=(o[r.type]??0)+1;o[r.typ
|
|
|
664
664
|
animation-duration: 0s !important;
|
|
665
665
|
transition-duration: 0s !important;
|
|
666
666
|
}
|
|
667
|
-
`;var
|
|
667
|
+
`;var ye=0;function Se(){return`:ac-${++ye}:`}function te(){return{text:"",completedParams:[],suggestions:[],activeDropdownIndex:-1,newParamId:null,isLoading:!1,isReady:!1,error:null,segments:[],actionableSuggestions:[],filteredOptions:[],placeholderText:"",isDropdownOpen:!1,filterBase:0,filterInProgress:!1,pillTapped:!1,skipNextFetch:!1,lastRawQuery:"",isFocused:!1}}var $=class{constructor(e,t={}){this.store=N(te());this._listboxId=Se();this.modeController=null;this.unsubscribers=[];this.derivedInProgress=!1;this.domRefs=null;this.dropdownRefs=null;this.externalListeners=new Set;this.sessionId=crypto.randomUUID();this.container=e,this.opts=t,this.renderMode=t.renderMode??"full",t.value!==void 0&&this.store.set({text:t.value}),t.completedParams!==void 0&&this.store.set({completedParams:t.completedParams}),this.pillsController=new M(this.store,{onPillSelected:({rawQuery:i,selectedPill:s,otherPills:r})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:s,other_pills:r})}}),this.fetchController=new D(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.opts.onError,()=>this.sessionId,{onAutoMatch:({active:i,matched:s,rawQuery:r})=>{this.fireTelemetry("option",{raw_query:r,selected_option:s.text,other_options:(i.options??[]).filter(n=>n.text!==s.text).map(n=>n.text)})}}),this.keyboardController=new k(this.store,{columns:t.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.opts.onSubmit,afterSubmit:this.renderMode==="full"?()=>this.reset():void 0,selectOption:i=>this.selectOption(i)}),this.unsubscribers.push(this.store.subscribe((i,s)=>{this.recomputeDerived(i,s)})),this.unsubscribers.push(this.store.subscribe((i,s)=>{i.text!==s.text&&this.opts.onChange?.(i.text),i.completedParams!==s.completedParams&&this.opts.onParamsChange?.(i.completedParams),i.isFocused!==s.isFocused&&(i.isFocused?this.opts.onFocus?.():this.opts.onBlur?.()),this.opts.onStateChange?.(i)})),this.renderMode!=="headless"&&(ee(),this.setupContainer()),this.renderMode==="full"?this.buildAndRenderFull():this.renderMode==="dropdown"&&this.buildAndRenderDropdown(),this.fetchController.start()}focus(){this.domRefs?.textarea.focus()}blur(){this.domRefs?.textarea.blur()}reset(){this.store.set({...te(),skipNextFetch:!0}),this.sessionId=crypto.randomUUID(),this.fetchController.doFetch("",[])}destroy(){this.fetchController.dispose(),this.modeController?.destroy(),this.newParamTimer&&clearTimeout(this.newParamTimer),this.suggestionRemovalTimer&&clearTimeout(this.suggestionRemovalTimer),this.externalListeners.clear();for(let e of this.unsubscribers)e();this.unsubscribers=[],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)}removeLastParam(){this.pillsController.removeLastParam()}clearNewParamId(){this.store.set({newParamId:null})}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}handleTextChange(e){this.handleChange(e)}handleKeyDown(e){this.keyboardController.handleKeyDown(e)}setFocused(e){this.store.get().isFocused!==e&&this.store.set({isFocused:e})}subscribe(e){return this.externalListeners.add(e),()=>{this.externalListeners.delete(e)}}getState(){return this.store.get()}get listboxId(){return this._listboxId}get isReady(){return this.store.get().isReady}on(e,t){switch(e){case"submit":return this.opts.onSubmit=t,()=>{this.opts.onSubmit=void 0};case"error":return this.opts.onError=t,()=>{this.opts.onError=void 0};case"change":return this.opts.onChange=t,()=>{this.opts.onChange=void 0};case"paramsChange":return this.opts.onParamsChange=t,()=>{this.opts.onParamsChange=void 0};case"stateChange":return this.opts.onStateChange=t,()=>{this.opts.onStateChange=void 0};case"focus":return this.opts.onFocus=t,()=>{this.opts.onFocus=void 0};case"blur":return this.opts.onBlur=t,()=>{this.opts.onBlur=void 0};default:return()=>{}}}update(e){Object.assign(this.opts,e),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)&&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(),i=t.actionableSuggestions[0];if(!i)return;let{rawQuery:s}=y(t.text,t.completedParams);this.fireTelemetry("option",{raw_query:s,selected_option:e.text,other_options:t.filteredOptions.filter(g=>g.text!==e.text).map(g=>g.text)});let r=t.filterBase,n=t.text.slice(0,r),c=n.length===0&&t.text.length===0,a=n.length===0&&t.text.length>0&&t.placeholderText.length>0&&t.placeholderText.toLowerCase().startsWith(t.text.toLowerCase());(c||a)&&t.placeholderText&&(n=`${t.placeholderText} `);let l=q(n,e.text);l>0&&(n=n.slice(0,n.length-l));let d=n.length>0&&n[n.length-1]!==" ",p=`${n}${d?" ":""}${e.text} `,m=(c||a)&&p.length>0?p[0].toUpperCase()+p.slice(1):p,u=m.toLowerCase().lastIndexOf(e.text.toLowerCase()),h=u>=0?m.slice(u,u+e.text.length):e.text,x={id:crypto.randomUUID(),placeholder:"",type:i.type,text:h,kind:e.kind,suggestionType:i.type,suggestionPlaceholder:i.text,options:i.options??[],metadata:e.metadata},f=t.actionableSuggestions.length-1;this.store.set(g=>({text:m,filterBase:m.length,completedParams:[...g.completedParams,x],newParamId:x.id,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:f>0})),this.suggestionRemovalTimer=window.setTimeout(()=>{this.store.set(g=>({suggestions:g.suggestions.filter(b=>b!==i)}))},400)}fireTelemetry(e,t){let i=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");V({source:i,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}recomputeDerived(e,t){if(this.derivedInProgress)return;this.derivedInProgress=!0;let i=Q(e.text,e.completedParams),s=e.suggestions.filter(g=>g.type!=="placeholder"),r=s[0],n=r?this.opts.optionOverrides?.[r.type]:void 0,c=Math.min(e.filterBase,e.text.length),l=e.lastRawQuery!==""||c>0?v(e.text,c,e.filterInProgress):"",d=r?n?n(l.trim()):r.options??[]:[],p=w(d,l),m=e.suggestions.filter(g=>g.type==="placeholder").map(g=>g.text).join(" "),u=this.opts.dropdownTrigger??"auto",h=this.opts.closeDropdownOnBlur??!0,x=!1;if(u==="auto"){let g=h?e.isFocused:!0;x=!e.isLoading&&p.length>0&&g}else u==="manual"&&(x=!e.isLoading&&p.length>0&&e.pillTapped);this.store.set({segments:i,actionableSuggestions:s,filteredOptions:p,placeholderText:m,isDropdownOpen:x}),this.derivedInProgress=!1;let f=this.store.get();for(let g of this.externalListeners)g(f)}setupContainer(){this.container.classList.add("magicx-aia"),this.container.dataset.pillPlacement=this.renderMode==="dropdown"?"dropdown":this.opts.pillPlacement??"inline",this.container.dataset.optionsPosition=this.opts.optionsPosition??"below",this.container.dataset.animations=this.opts.animations??!0?"on":"off",this.modeController=new P(this.container,this.opts.mode??"auto")}buildAndRenderFull(){let e=this,t={store:this.store,listboxId:this.listboxId,get pillPlacement(){return e.opts.pillPlacement??"inline"},get onSubmit(){return e.opts.onSubmit},afterSubmit:()=>e.reset(),submitButton:this.opts.submitButton,autoFocus:this.opts.autoFocus??!0,selectOption:i=>this.selectOption(i),setActivePill:i=>this.pillsController.setActivePill(i),handleKeyDown:i=>this.keyboardController.handleKeyDown(i),handleChange:i=>this.handleChange(i)};this.domRefs=Z(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&B(this.domRefs,this.store.get(),t)}),B(this.domRefs,this.store.get(),t),this.subscribeNewParamTimer()}buildAndRenderDropdown(){let e={store:this.store,listboxId:this.listboxId,selectOption:t=>this.selectOption(t),setActivePill:t=>this.pillsController.setActivePill(t)};this.dropdownRefs=Y(this.container,e),this.subscribeBatchedRender(()=>{this.dropdownRefs&&H(this.dropdownRefs,this.store.get(),e)}),H(this.dropdownRefs,this.store.get(),e),this.subscribeNewParamTimer()}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.newParamTimer&&clearTimeout(this.newParamTimer),this.newParamTimer=window.setTimeout(()=>{this.store.set({newParamId:null})},650))}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:s}=U(e,t.completedParams);s.length>0&&this.store.set(r=>({completedParams:i,suggestions:[...s.map(n=>({type:n.suggestionType,text:n.suggestionPlaceholder,required:!0,options:n.options})),...r.suggestions]}))}};export{$ as AIAutocomplete,N as createStore};
|
|
668
668
|
//# sourceMappingURL=index.mjs.map
|