@magicx-eng/ai-autocomplete-vanilla 0.1.14 → 0.1.16
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 +28 -11
- package/index.d.mts +96 -0
- package/index.d.ts +96 -0
- package/index.js +194 -65
- package/index.js.map +1 -1
- package/index.mjs +194 -65
- package/index.mjs.map +1 -1
- package/package.json +1 -1
package/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
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=`/* ===================================================================
|
|
1
|
+
function T(i,e){let t=i,n={},s=[];for(let r of e){let o=(n[r.type]??0)+1;n[r.type]=o;let l=`{{${r.type.toUpperCase().replace(/\s+/g,"_")}_${o}}}`,c=t.indexOf(r.text);c!==-1&&(t=t.slice(0,c)+l+t.slice(c+r.text.length)),s.push({...r,placeholder:l})}return{rawQuery:t,completedParams:s}}function O(i,e,t){return e>0||!t?e:i.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function w(i,e,t){let n=i.slice(e);if(t||e===0||i[e-1]===" ")return n;let s=n.indexOf(" ");return s===-1?"":n.slice(s+1)}function Z(i,e){let t=i.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let n=t.split(" "),s=e.toLowerCase();for(let r=0;r<n.length;r++){let o=n.slice(r).join(" ");if(s.startsWith(o.toLowerCase())){let a=t.length-o.length;return i.length-a}}return 0}function I(i,e){if(!i)return[];let t=e.trimStart();if(!t)return i;let n=t.toLowerCase();return i.filter(s=>!s.is_tappable||s.text.toLowerCase().includes(n))}function E(i,e){if(!i)return null;let t=e.trim();if(!t)return null;let n=t.toLowerCase();return i.find(s=>s.is_tappable&&s.text.toLowerCase()===n)??null}var M=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 ee(i,e){let t=[],n=0;for(let r of e){let o=i.indexOf(r.text,n);o!==-1&&(o>n&&t.push({type:"text",value:i.slice(n,o)}),t.push({type:"completed",value:r.text,param:r}),n=o+r.text.length)}let s=i.slice(n);return s&&t.push({type:"text",value:s}),t}function te(i,e){let t=[],n=[],s=0;for(let r of e){let o=i.indexOf(r.text,s);o===-1?n.push(r):(t.push(r),s=o+r.text.length)}return{valid:t,invalid:n}}var k=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 Pe="https://api.ai-autocomplete.com",R=`${Pe}/api/suggest`,ne=new WeakMap;function D(i){return i?.type==="accessToken"}function Ce(i){if(!(!i||D(i)))return i}function _(i){let e=ne.get(i.getAccessToken);return e||(e=new k(i),ne.set(i.getAccessToken,e)),e}function N(i){return{"Content-Type":"application/json",...i?.appIdentifier&&{"X-App-Identifier":i.appIdentifier},...i?.headers}}function F(i){let e=Ce(i),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}function we(i){return(i??R).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function Ee(i){return D(i)?`Bearer ${await _(i).getToken()}`:F(i)}async function ie(i){try{let e=we(i.apiConfig?.endpoint),t=N(i.apiConfig),n=await Ee(i.apiConfig);n&&(t.Authorization=n);let s=JSON.stringify({source:i.source,session_id:i.sessionId,type:i.type,at:new Date().toISOString(),query_data:i.queryData});await fetch(e,{method:"POST",headers:t,body:s})}catch{}}var Ae="0.1.40",oe=!1;function Oe(){return crypto.randomUUID()}function Ie(i,e){return{placeholder:i.placeholder,type:i.type,...e&&{text:i.text},kind:i.kind}}function De(i,e,t,n){let s=e.find(o=>o.type==="contact"&&o.metadata?.contact_account_count)?.metadata?.contact_account_count,r=typeof s=="number"?s:void 0;return{data:{raw_query:i,completed_params:e.map(o=>Ie(o,t)),...r!=null&&{contact_account_count:r}},meta:{request_id:Oe(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:Ae,session_id:n}}}async function se(i,e,t,n,s){return fetch(i,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:n,signal:s})}async function re(i,e,t){let n=t.apiConfig,s=!t.maskCompletedText,r=De(i,e,s,t.sessionId),o=N(n),a=n?.endpoint??R,l=JSON.stringify(r);if(D(n)){let u=_(n),d=await u.getToken(),h=await se(a,o,d,l,t.signal);if(h.status===401){let x=await u.getToken(!0);h=await se(a,o,x,l,t.signal)}if(!h.ok)throw new Error(`API error: ${h.status} ${h.statusText}`);return h.json()}let c=F(n);!c&&!oe&&(oe=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),c&&(o.Authorization=c);let m=await fetch(a,{method:"POST",headers:o,body:l,signal:t.signal});if(!m.ok)throw new Error(`API error: ${m.status} ${m.statusText}`);return m.json()}function ae(i,e){return e?i.map(t=>{let n=e[t.type];if(!n)return t;let s=n("");if(s.length===0)return t;let r=new Set(s.map(a=>a.text)),o=(t.options??[]).filter(a=>!r.has(a.text));return{...t,options:[...s,...o]}}):i}var Le=100,Me=300,ke=2,H=class{constructor(e,t,n,s,r,o,a={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=n;this.getMaskCompletedText=s;this.getOnError=r;this.getSessionId=o;this.callbacks=a;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(n=>{(n.text!==e||n.completedParams!==t)&&(e=n.text,t=n.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let n=new AbortController;this.abortController=n;let s=++this.fetchVersion,r=this.store.get().text.length;this.store.set({isLoading:!0,error:null});try{let o=await re(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:n.signal,apiConfig:this.getApiConfig()});if(s!==this.fetchVersion)return;let a=ae(o.data.suggestions??[],this.getOptionOverrides()),l=o.data.input??[],c=l[l.length-1],m=this.store.get().text,u,d;if(c?.state==="in_progress"){d=!0;let f=m.toLowerCase().lastIndexOf(c.text.toLowerCase());u=f!==-1?f:r}else d=!1,u=r;let x=a.filter(f=>f.type!=="placeholder")[0],b=null;if(x){let f=w(m,u,d),p=E(x.options,f);p&&(b={id:crypto.randomUUID(),placeholder:"",type:x.type,text:p.text,kind:p.kind,suggestionType:x.type,suggestionPlaceholder:x.text,options:x.options??[],metadata:p.metadata},a=a.filter(g=>g!==x),this.callbacks.onAutoMatch?.({active:x,matched:p,rawQuery:e}))}this.store.set(f=>({suggestions:a,isLoading:!1,isReady:o.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:u,filterInProgress:d,...b?{completedParams:[...f.completedParams,b]}:{}}))}catch(o){if(s===this.fetchVersion){let a=o instanceof Error?o:new Error(String(o));this.store.set({error:a,isLoading:!1}),this.getOnError()?.(a)}}}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}let t=n=>{let s=this.store.get();if(!s.text&&s.completedParams.length===0)return this.doFetch("",[]),!0;let r=s.suggestions.filter(g=>g.type==="placeholder").map(g=>g.text).join(" "),o=O(s.text,s.filterBase,r),a=w(s.text,o,s.filterInProgress),c=s.suggestions.filter(g=>g.type!=="placeholder")[0],u=(c?I(c.options,a):[]).filter(g=>g.is_tappable),d=c?E(c.options,a)!==null:!1,h=a.trim().length>0;if(u.length>0&&!d&&h||s.completedParams.length===0&&s.text.length>0&&r.length>0&&r.toLowerCase().startsWith(s.text.toLowerCase()))return!1;let{rawQuery:x,completedParams:b}=T(s.text,s.completedParams),f=x.length<s.lastRawQuery.length,p=Math.abs(x.length-s.lastRawQuery.length);return f||p>=n?(this.doFetch(x,b),!0):!1};this.debounceTimer=setTimeout(()=>{t(ke)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},Le),this.slowDebounceTimer=setTimeout(()=>t(1),Me)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var ce='[contenteditable="false"]',A;function Re(){if(A!==void 0)return A;let i=globalThis.Intl.Segmenter;if(!i)return A=null,null;try{A=new i(void 0,{granularity:"grapheme"})}catch{A=null}return A??null}function B(i,e){let t=i;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(ce))return!0;t=t.parentNode}return!1}function K(i){return(i.ownerDocument??document).createTreeWalker(i,NodeFilter.SHOW_TEXT,{acceptNode(e){return B(e,i)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function j(i){let e=K(i),t="",n=e.nextNode();for(;n;)t+=n.data,n=e.nextNode();return t}function de(i){let e=K(i),t=0,n=e.nextNode();for(;n;)t+=n.data.length,n=e.nextNode();return t}function C(i){let e=(i.ownerDocument??document).getSelection();if(!e||e.rangeCount===0)return null;let t=e.anchorNode,n=e.anchorOffset;if(!t||!i.contains(t))return null;if(t.nodeType===Node.ELEMENT_NODE){let s=t;if(B(s,i)&&s!==i)return null;let r=0;for(let o=0;o<n&&o<s.childNodes.length;o++)r+=ue(s.childNodes[o],i);return r+le(s,i)}return t.nodeType!==Node.TEXT_NODE||B(t,i)?null:le(t,i)+n}function ue(i,e){if(i.nodeType===Node.TEXT_NODE)return B(i,e)?0:i.data.length;if(i.nodeType!==Node.ELEMENT_NODE)return 0;let t=i;if(t.matches(ce))return 0;let n=0;for(let s of Array.from(t.childNodes))n+=ue(s,e);return n}function le(i,e){let t=K(e),n=0,s=t.nextNode();for(;s;){if(s===i||i.nodeType===Node.ELEMENT_NODE&&i.contains(s))return n;n+=s.data.length,s=t.nextNode()}return n}function S(i,e){let t=i.ownerDocument??document,n=t.getSelection();if(!n)return;let s=Math.max(0,Math.min(e,de(i))),r=K(i),o=0,a=null,l=0,c=r.nextNode(),m=null;for(;c;){let d=c.data.length;if(s<o+d){a=c,l=s-o;break}if(s===o+d){let h=r.nextNode();h?(a=h,l=0):(a=c,l=d);break}o+=d,m=c,c=r.nextNode()}let u=t.createRange();if(a){let d=a.parentElement?.closest('strong[data-seg="completed"]');d&&d!==i&&i.contains(d)?l===0?u.setStartBefore(d):l===a.data.length?u.setStartAfter(d):u.setStart(a,l):u.setStart(a,l)}else m?u.setStart(m,m.data.length):u.setStart(i,0);u.collapse(!0),n.removeAllRanges(),n.addRange(u)}function pe(i){let e=C(i);return e==null?!1:e>=de(i)}function me(i,e){if(e<=0)return 0;let t=Re();if(!t)return e-1;let n=i.slice(0,e),s=0;for(let{index:r}of t.segment(n))r<e&&(s=r);return s}function ge(i){return i instanceof HTMLTextAreaElement||i instanceof HTMLInputElement?i.selectionStart!=null&&i.selectionStart===i.value.length:i instanceof HTMLElement&&i.hasAttribute("data-aia-input")?pe(i):!1}function _e(i){return i instanceof HTMLElement&&i.hasAttribute("data-aia-input")?C(i):null}var q=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:n,getOnSubmit:s}=this.ctx,r=this.getEffectiveColumns(),o=s(),a=this.getTappableIndices(r);switch(e.key){case"ArrowDown":{let l=ge(e.target),c=!!t.editingParam;if(!l&&!c&&t.activeDropdownIndex<0)break;if(e.preventDefault(),!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:a[0]??0});break}if(a.length===0)return;let m=a.indexOf(t.activeDropdownIndex),u=m<a.length-1?m+1:0;this.store.set({activeDropdownIndex:a[u]});break}case"ArrowUp":{if(a.length===0||t.activeDropdownIndex<0)break;if(e.preventDefault(),t.activeDropdownIndex<r){this.store.set({activeDropdownIndex:-1});break}let l=a.indexOf(t.activeDropdownIndex),c=l>0?l-1:a.length-1;this.store.set({activeDropdownIndex:a[c]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%r<r-1){let m=t.activeDropdownIndex+1;m<t.filteredOptions.length&&t.filteredOptions[m]?.is_tappable&&this.store.set({activeDropdownIndex:m})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let c=e.target.closest("[data-aia-input]")??e.target,m=t.editingTail;this.ctx.exitEditMode?.(),S(c,m);break}ge(e.target)&&t.actionableSuggestions.length>1&&(e.preventDefault(),this.pillsSetActivePill(1));break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%r>0){let l=t.activeDropdownIndex-1;l>=0&&t.filteredOptions[l]?.is_tappable&&this.store.set({activeDropdownIndex:l})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let l=e.target.closest("[data-aia-input]")??e.target,c=t.editingAnchor;this.ctx.exitEditMode?.(),S(l,c);break}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let l=_e(e.target);if(l==null)break;this.ctx.removeParamAtCaret(l)&&e.preventDefault();break}case"Enter":{if(e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable)this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,n);else if(o){let{rawQuery:l,completedParams:c}=T(t.text,t.completedParams);o({query:t.text.trim(),raw_query:l,completed_params:c}),this.ctx.afterSubmit?.()}break}case"Tab":{let l=!t.text&&!!t.placeholderText,c=t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable;if(l&&!c){e.preventDefault();let m=t.placeholderText;if(this.store.set(u=>({text:m,filterBase:m.length,suggestions:u.suggestions.filter(d=>d.type!=="placeholder")})),e.target instanceof HTMLElement){let u=e.target.closest("[data-aia-input]")??e.target;queueMicrotask(()=>S(u,m.length))}}else if(c)e.preventDefault(),this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,n);else if(t.isDropdownOpen){let m=t.filteredOptions.findIndex(u=>u.is_tappable);m>=0&&(e.preventDefault(),this.clickOrSelect(m,t.filteredOptions,n))}break}case"Escape":{if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){let l=e.target.closest("[data-aia-input]")??e.target,c=t.editingTail;this.ctx.exitEditMode?.(),S(l,c)}this.store.set({activeDropdownIndex:-1});break}}}getTappableIndices(e){let n=this.store.get().filteredOptions.map((r,o)=>r.is_tappable?o:-1).filter(r=>r!==-1),s=Array.from({length:e},()=>[]);for(let r of n)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 n=getComputedStyle(t).gridTemplateColumns.split(" ").filter(Boolean).length;return n>0?n:this.ctx.columns}clickOrSelect(e,t,n){let s=document.getElementById(`${n}-option-${e}`);s?s.click():this.ctx.selectOption(t[e])}pillsSetActivePill(e){let t=this.store.get(),n=t.suggestions.filter(a=>a.type!=="placeholder");if(e<0||e>=n.length)return;let s=n[e],r=n.filter((a,l)=>l!==e),o=t.suggestions.filter(a=>a.type==="placeholder");this.store.set({suggestions:[...o,s,...r],pillTapped:!0,activeDropdownIndex:-1})}};var Q=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),n=t.suggestions.filter(a=>a.type!=="placeholder");if(e<0||e>=n.length)return;let s=n[e],r=n.filter((a,l)=>l!==e),o=t.suggestions.filter(a=>a.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:a}=T(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:a,selectedPill:s.text,otherPills:r.map(l=>l.text)})}this.store.set({suggestions:[...o,s,...r],pillTapped:!0,activeDropdownIndex:-1})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};var he=[125,69];function fe(i){return i===0?.4:i===1?.3:.15}function $(i,e,t,n,s=!1,r=!1){let o=i.querySelector(".magicx-aia-pill-list");if(o||(o=document.createElement("span"),o.className="magicx-aia-pill-list",i.appendChild(o)),r&&e.length===0){o.setAttribute("data-aia-pill-list-loading",""),o.innerHTML="";for(let c=0;c<he.length;c++){let m=he[c],u=document.createElement("span");u.setAttribute("data-aia-pill-skeleton",""),u.className=`magicx-aia-pill magicx-aia-pill--skeleton${s?" magicx-aia-pill--rounded":""}`,u.style.width=`${m}px`,u.style.opacity=String(fe(c)),o.appendChild(u)}return}r?o.setAttribute("data-aia-pill-list-loading",""):o.removeAttribute("data-aia-pill-list-loading");for(let c of o.querySelectorAll("[data-aia-pill-skeleton]"))c.remove();let a=new Map;for(let c of o.querySelectorAll(".magicx-aia-pill"))a.set(c.dataset.pillKey??"",c);let l=new Set;for(let c=0;c<e.length;c++){let m=e[c],u=`${m.type}-${m.text}`;l.add(u);let d=a.get(u);(!d||d.tagName!=="BUTTON")&&(d?.remove(),d=document.createElement("button"),d.type="button",d.tabIndex=-1,d.dataset.pillKey=u,d.setAttribute("data-aia-pill",""),d.setAttribute("contenteditable","false"),d.textContent=m.text,d.addEventListener("mousedown",x=>x.preventDefault()));let h=["magicx-aia-pill"];s&&h.push("magicx-aia-pill--rounded"),c===t&&!r&&h.push("magicx-aia-pill--active"),r&&h.push("magicx-aia-pill--skeleton"),d.className=h.join(" "),d.style.width="",d.style.opacity=String(fe(c)),r?(d.setAttribute("data-aia-loading",""),d.disabled=!0,d.onclick=null):(d.removeAttribute("data-aia-loading"),d.disabled=!1,d.onclick=()=>n(c)),o.children[c]!==d&&o.insertBefore(d,o.children[c]??null)}for(let[c,m]of a)l.has(c)||m.remove()}function G(i){i.querySelector(".magicx-aia-pill-list")?.remove()}var Ne=[159,119,164];function U(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 W(i,e){let{filteredOptions:t,activeIndex:n,isOpen:s,isLoading:r,pills:o,showPills:a,onSelect:l,onHighlight:c,onPillClick:m}=e,u=a&&o.length>0,d=t.length>0;s&&(d||u||r)?i.classList.add("magicx-aia-dropdown--visible"):i.classList.remove("magicx-aia-dropdown--visible"),r?i.setAttribute("data-aia-loading",""):i.removeAttribute("data-aia-loading");let x=u||r&&a,b=i.querySelector(".magicx-aia-pill-bar");x?(b||(b=document.createElement("div"),b.className="magicx-aia-pill-bar",b.setAttribute("data-aia-pillbar",""),i.insertBefore(b,i.firstChild)),$(b,o,0,m,!0,r)):b&&b.remove();let f=i.querySelector(".magicx-aia-grid");d?(f||(f=document.createElement("div"),f.className="magicx-aia-grid",i.appendChild(f)),Fe(f,t,n,l,c,e.listboxId,r)):f&&f.remove();let p=i.querySelector(".magicx-aia-skeleton-bars");if(r&&!d){if(!p){p=document.createElement("div"),p.className="magicx-aia-skeleton-bars",p.setAttribute("data-aia-skeleton-bars","");for(let g of Ne){let y=document.createElement("span");y.className="magicx-aia-skeleton-bar",y.style.width=`${g}px`,p.appendChild(y)}i.appendChild(p)}}else p&&p.remove()}function Fe(i,e,t,n,s,r,o){let a=e.map(d=>d.text).join("\0"),l=i.dataset.optionsKey??"",c=i.dataset.loading??"",m=o?"1":"0",u=a!==l||c!==m;if(i.dataset.optionsKey=a,i.dataset.loading=m,u){let d=document.createDocumentFragment();for(let h=0;h<e.length;h++){let x=e[h],b=He(x,h,t,n,s,r,o);d.appendChild(b)}i.innerHTML="",i.appendChild(d)}else{let d=i.querySelectorAll(".magicx-aia-option");for(let h=0;h<d.length;h++){let x=d[h],b=h===t&&!o;x.setAttribute("aria-selected",String(b)),b?x.classList.add("magicx-aia-option--highlighted"):x.classList.remove("magicx-aia-option--highlighted")}}}function He(i,e,t,n,s,r,o){let a=document.createElement("div");a.id=`${r}-option-${e}`,a.setAttribute("role","option"),a.setAttribute("data-aia-option",""),o&&a.setAttribute("data-aia-loading",""),a.setAttribute("aria-selected",String(e===t&&!o)),a.tabIndex=o||!i.is_tappable?-1:0;let l=["magicx-aia-option"];e===t&&!o&&l.push("magicx-aia-option--highlighted"),i.is_tappable?l.push("magicx-aia-option--tappable"):l.push("magicx-aia-option--non-tappable"),a.className=l.join(" ");let c=document.createElement("div");c.className="magicx-aia-streaks",a.appendChild(c);let m=document.createElement("div");m.className="magicx-aia-streaks-vert",a.appendChild(m);let u=document.createElement("span");if(u.className="magicx-aia-option-content",u.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,u.appendChild(d)}return a.appendChild(u),!o&&i.is_tappable&&(a.addEventListener("click",()=>{a.classList.add("magicx-aia-option--pressed"),n(i),setTimeout(()=>a.classList.remove("magicx-aia-option--pressed"),500)}),a.addEventListener("mouseenter",()=>s(e))),a}function xe(i,e){let t=U(e.listboxId);return i.appendChild(t),{dropdown:t}}function z(i,e,t){W(i.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,onSelect:t.selectOption,onHighlight:n=>t.store.set({activeDropdownIndex:n}),onPillClick:t.setActivePill})}function be(i){let{input:e,segments:t,newParamId:n,editingParamId:s,placeholderText:r,isFocused:o}=i,a=t.length===0;e.dataset.aiaEmpty=a?"true":"false",a&&r?e.dataset.placeholder=r:delete e.dataset.placeholder;let l=t.map(f=>`${f.type}:${f.value}`).join("\0"),c=e.dataset.segKey??"",m=e.dataset.newParamId??"",u=e.dataset.editingParamId??"";if(l===c&&(n??"")===m&&(s??"")===u)return;let d=o?C(e):null;e.dataset.segKey=l,e.dataset.newParamId=n??"",e.dataset.editingParamId=s??"";let h=e.ownerDocument??document,x=h.createDocumentFragment(),b=0;for(let f of t)if(b+=f.value.length,f.type==="completed"){let p=h.createElement("strong");p.dataset.seg="completed",p.dataset.paramId=f.param.id;let g=f.param.id===n,y=f.param.id===s,v=["magicx-aia-segment","magicx-aia-segment--completed"];g&&v.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),y&&v.push("magicx-aia-segment--editing"),p.className=v.join(" "),p.textContent=f.value,x.appendChild(p)}else x.appendChild(h.createTextNode(f.value));e.replaceChildren(x),e.dataset.aiaTextLength=String(b),d!=null&&S(e,Math.max(0,Math.min(d,b)))}var Be='<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 Ke(){let i=document.createElement("div");return i.setAttribute("contenteditable","plaintext-only"),i.contentEditable==="plaintext-only"}function ye(i,e){let{listboxId:t}=e,n=U(t);i.appendChild(n);let s=document.createElement("div");s.className="magicx-aia-input-wrapper",i.appendChild(s);let r=document.createElement("div");r.className="magicx-aia-editor",r.setAttribute("data-aia-editor",""),s.appendChild(r);let o=document.createElement("div");o.className="magicx-aia-input",o.setAttribute("data-aia-input",""),o.setAttribute("contenteditable",Ke()?"plaintext-only":"true"),o.setAttribute("role","combobox"),o.setAttribute("aria-autocomplete","list"),o.setAttribute("aria-haspopup","listbox"),o.setAttribute("aria-controls",t),o.setAttribute("aria-expanded","false"),o.setAttribute("spellcheck","true"),o.setAttribute("enterkeyhint","send"),r.appendChild(o);let a=document.createElement("span");a.className="magicx-aia-pill-list-container",a.setAttribute("data-aia-pill-list-container",""),r.appendChild(a);let l=null,c=null;e.submitButton===void 0?(l=document.createElement("button"),l.type="button",l.className="magicx-aia-submit",l.setAttribute("aria-label","Submit"),l.setAttribute("data-aia-submit",""),l.innerHTML=Be,s.appendChild(l),c=l):e.submitButton!==null&&(c=e.submitButton,c.hasAttribute("data-aia-submit")||c.setAttribute("data-aia-submit",""),s.appendChild(c));let m=new AbortController,{signal:u}=m,d=!1,h=0,x=()=>{let p=j(o),y=p.length>0&&p[0]!==p[0].toUpperCase()?p[0].toUpperCase()+p.slice(1):p;e.handleChange(y)},b=()=>{let p=(o.ownerDocument??document).getSelection();if(!p||p.rangeCount===0)return null;let g=p.anchorNode;return!g||!o.contains(g)?null:(g.nodeType===Node.ELEMENT_NODE?g:g.parentElement)?.closest('strong[data-seg="completed"][data-param-id]')?.dataset.paramId??null};s.addEventListener("click",p=>{p.target?.closest("[data-aia-pill]")||o.focus()},{signal:u}),o.addEventListener("input",()=>{d||(h=performance.now(),x(),e.handleCaretAfterInput(C(o)))},{signal:u});let f=o.ownerDocument??document;return f.addEventListener("selectionchange",()=>{let p=f.getSelection();if(!p||p.rangeCount===0||!o.contains(p.anchorNode))return;let g=b(),y=e.store.get().editingParam?.id??null;if(g&&g!==y){e.startEditingParam(g);return}performance.now()-h<50||e.handleCaretMove(C(o))},{signal:u}),o.addEventListener("compositionstart",()=>{d=!0},{signal:u}),o.addEventListener("compositionend",()=>{d=!1,x()},{signal:u}),o.addEventListener("beforeinput",p=>{let g=p,y=g.inputType;if(y==="insertParagraph"||y==="insertLineBreak"||y==="insertFromDrop"){p.preventDefault();return}if(y.startsWith("insert")||y.startsWith("delete")){let v=y.startsWith("delete")?"":g.data??"";e.replaceEditingRange(v)&&p.preventDefault()}},{signal:u}),o.addEventListener("paste",p=>{p.preventDefault();let g=(p.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!g)return;let y=o.ownerDocument??document,v=y.getSelection();if(!v||v.rangeCount===0)return;let P=v.getRangeAt(0);if(!o.contains(P.startContainer))return;P.deleteContents();let L=y.createTextNode(g);P.insertNode(L),P.setStartAfter(L),P.collapse(!0),v.removeAllRanges(),v.addRange(P),x()},{signal:u}),o.addEventListener("keydown",p=>e.handleKeyDown(p),{signal:u}),o.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:u}),o.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:u}),c&&c.addEventListener("click",p=>{let g=e.store.get();if(!(!!g.text||g.completedParams.length>0)||!e.onSubmit)return;p.stopPropagation();let{rawQuery:v,completedParams:P}=T(g.text,g.completedParams);e.onSubmit({query:g.text.trim(),raw_query:v,completed_params:P}),e.afterSubmit?.()},{signal:u}),e.autoFocus!==!1&&o.focus(),{input:o,inlinePillContainer:a,dropdown:n,submitButton:l,abort:m}}function V(i,e,t){let{input:n,inlinePillContainer:s,dropdown:r,submitButton:o}=i,{pillPlacement:a,setActivePill:l,selectOption:c,store:m}=t;n.setAttribute("aria-expanded",String(e.isDropdownOpen));let u=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(u?n.setAttribute("aria-activedescendant",u):n.removeAttribute("aria-activedescendant"),o){let f=!!e.text||e.completedParams.length>0;o.disabled=!f}let d=n.dataset.newParamId??"",h=e.newParamId!==null&&e.newParamId!==d;if(be({input:n,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused}),a==="inline"){let f=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;f||e.actionableSuggestions.length>0?$(s,e.actionableSuggestions,0,l,!1,f):G(s)}else G(s);h?(n.focus(),S(n,e.caretOffset??e.text.length)):e.isFocused&&j(n)!==e.text&&S(n,e.text.length);let x=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:null,b=x??e.actionableSuggestions[0];W(r,{suggestions:b?[{...b,options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation,listboxId:t.listboxId,pills:x?[x]:e.actionableSuggestions,showPills:a==="dropdown",onSelect:c,onHighlight:f=>m.set({activeDropdownIndex:f}),onPillClick:l})}function X(i){let e=i,t=new Set;return{get:()=>e,set:n=>{let s=typeof n=="function"?n(e):n,r={...e,...s},o=e;e=r;for(let a of t)a(r,o)},subscribe:n=>(t.add(n),()=>{t.delete(n)})}}var J=!1;function ve(){if(J||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){J=!0;return}J=!0;let i=document.createElement("style");i.setAttribute("data-magicx-aia",""),i.textContent=qe,document.head.appendChild(i)}var qe=`/* ===================================================================
|
|
2
2
|
Vanilla core styles \u2014 stable BEM class names (magicx-aia-*)
|
|
3
3
|
Auto-injected at runtime on first instantiation.
|
|
4
4
|
=================================================================== */
|
|
@@ -6,7 +6,10 @@ function y(o,e){let t=o,i={},s=[];for(let r of e){let n=(i[r.type]??0)+1;i[r.typ
|
|
|
6
6
|
/* --- Container --- */
|
|
7
7
|
.magicx-aia {
|
|
8
8
|
position: relative;
|
|
9
|
-
font
|
|
9
|
+
/* Inherits the host page's font by default. Consumers can pin a specific
|
|
10
|
+
font on the library via \`--aia-font-family: 'Custom Font'\` without
|
|
11
|
+
affecting the surrounding page. */
|
|
12
|
+
font-family: var(--aia-font-family, inherit);
|
|
10
13
|
container-type: inline-size;
|
|
11
14
|
}
|
|
12
15
|
|
|
@@ -22,71 +25,89 @@ function y(o,e){let t=o,i={},s=[];for(let r of e){let n=(i[r.type]??0)+1;i[r.typ
|
|
|
22
25
|
gap: 0px;
|
|
23
26
|
}
|
|
24
27
|
|
|
25
|
-
/* --- Editor area (
|
|
28
|
+
/* --- Editor area (wraps the editable input + inline pill list sibling) --- */
|
|
26
29
|
.magicx-aia-editor {
|
|
27
30
|
position: relative;
|
|
28
31
|
flex: 1;
|
|
29
32
|
min-width: 0;
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
/* --- Sizer (overlay for sizing + segment display) --- */
|
|
33
|
-
.magicx-aia-sizer {
|
|
34
|
-
position: relative;
|
|
35
|
-
z-index: 1;
|
|
36
|
-
pointer-events: none;
|
|
37
|
-
white-space: pre-wrap;
|
|
38
|
-
word-break: break-word;
|
|
33
|
+
min-height: 38px;
|
|
34
|
+
line-height: 38px;
|
|
39
35
|
font-family: inherit;
|
|
40
36
|
font-size: var(--aia-written-text-font-size, 19px);
|
|
41
|
-
|
|
37
|
+
white-space: pre-wrap;
|
|
38
|
+
word-break: break-word;
|
|
39
|
+
overflow-wrap: anywhere;
|
|
42
40
|
}
|
|
43
41
|
|
|
44
|
-
|
|
45
|
-
|
|
42
|
+
/* --- Editable input (contentEditable; inline so pills flow alongside) --- */
|
|
43
|
+
.magicx-aia-input {
|
|
44
|
+
display: inline;
|
|
45
|
+
outline: none;
|
|
46
|
+
background: transparent;
|
|
47
|
+
color: var(--aia-written-text-color, var(--aia-color-text-default, #fff));
|
|
48
|
+
caret-color: var(
|
|
49
|
+
--aia-caret-color,
|
|
50
|
+
var(--aia-written-text-color, var(--aia-color-text-default, #fff))
|
|
51
|
+
);
|
|
52
|
+
font-weight: 200;
|
|
46
53
|
}
|
|
47
54
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
55
|
+
/* Empty inline contentEditables don't have an inline box, so the browser has
|
|
56
|
+
nowhere to render the caret. Switching to inline-block gives it presence;
|
|
57
|
+
the min-width is just wide enough for the caret line. */
|
|
58
|
+
.magicx-aia-input[data-aia-empty="true"] {
|
|
59
|
+
display: inline-block;
|
|
60
|
+
min-width: 1px;
|
|
61
|
+
vertical-align: top;
|
|
51
62
|
}
|
|
52
63
|
|
|
53
|
-
/*
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
64
|
+
/* Completed params render as inline bold runs. Specificity stays at (0,2,0)
|
|
65
|
+
so consumers can override with \`.magicx-aia-input strong\`. */
|
|
66
|
+
:where(.magicx-aia-input) strong {
|
|
67
|
+
font-weight: 500;
|
|
68
|
+
letter-spacing: -0.01em;
|
|
57
69
|
}
|
|
58
70
|
|
|
59
|
-
/*
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
71
|
+
/* Re-edit highlight \u2014 applied to the bold param being re-edited. The DOM
|
|
72
|
+
keeps a Selection range over the strong so the browser still handles
|
|
73
|
+
typing / backspace as a range replacement; we hide the native selection
|
|
74
|
+
paint and the caret so the only visual cue is this outline. */
|
|
75
|
+
:where(.magicx-aia-input) strong.magicx-aia-segment--editing {
|
|
76
|
+
outline: 1.5px solid var(--aia-edit-outline, currentColor);
|
|
77
|
+
outline-offset: 1px;
|
|
78
|
+
border-radius: 4px;
|
|
79
|
+
caret-color: transparent;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
:where(.magicx-aia-input) strong.magicx-aia-segment--editing::selection {
|
|
68
83
|
background: transparent;
|
|
69
|
-
color:
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
font-family: inherit;
|
|
75
|
-
font-size: var(--aia-written-text-font-size, 19px);
|
|
76
|
-
line-height: 38px;
|
|
77
|
-
white-space: pre-wrap;
|
|
78
|
-
word-break: break-word;
|
|
79
|
-
outline: none;
|
|
80
|
-
resize: none;
|
|
81
|
-
overflow: hidden;
|
|
84
|
+
color: inherit;
|
|
85
|
+
}
|
|
86
|
+
:where(.magicx-aia-input) strong.magicx-aia-segment--editing::-moz-selection {
|
|
87
|
+
background: transparent;
|
|
88
|
+
color: inherit;
|
|
82
89
|
}
|
|
83
90
|
|
|
84
|
-
|
|
91
|
+
/* Placeholder via ::before so it doesn't enter the editable DOM. */
|
|
92
|
+
.magicx-aia-input[data-aia-empty="true"][data-placeholder]::before {
|
|
93
|
+
content: attr(data-placeholder);
|
|
85
94
|
color: var(--aia-color-text-muted, #c1c4cb);
|
|
95
|
+
opacity: 0.7;
|
|
96
|
+
pointer-events: none;
|
|
86
97
|
}
|
|
87
98
|
|
|
88
|
-
|
|
89
|
-
|
|
99
|
+
/* Inline pill list container \u2014 a non-editable sibling of the editable that
|
|
100
|
+
flows immediately after it on the same line. The leading margin gives the
|
|
101
|
+
pills a visible gap from the typed text. */
|
|
102
|
+
.magicx-aia-pill-list-container {
|
|
103
|
+
display: inline;
|
|
104
|
+
margin-left: 8px;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/* Hide the leading margin when there are no pills so an empty container
|
|
108
|
+
doesn't bias the cursor's resting position to the right. */
|
|
109
|
+
.magicx-aia-pill-list-container:empty {
|
|
110
|
+
margin-left: 0;
|
|
90
111
|
}
|
|
91
112
|
|
|
92
113
|
/* --- Submit button --- */
|
|
@@ -110,7 +131,7 @@ function y(o,e){let t=o,i={},s=[];for(let r of e){let n=(i[r.type]??0)+1;i[r.typ
|
|
|
110
131
|
opacity: 0.85;
|
|
111
132
|
}
|
|
112
133
|
|
|
113
|
-
/* --- Dropdown --- */
|
|
134
|
+
/* --- Dropdown (glassmorphism \u2014 matches the React build) --- */
|
|
114
135
|
.magicx-aia-dropdown {
|
|
115
136
|
position: absolute;
|
|
116
137
|
left: 0;
|
|
@@ -118,24 +139,27 @@ function y(o,e){let t=o,i={},s=[];for(let r of e){let n=(i[r.type]??0)+1;i[r.typ
|
|
|
118
139
|
top: 100%;
|
|
119
140
|
max-width: 516px;
|
|
120
141
|
margin-top: 6px;
|
|
121
|
-
|
|
142
|
+
display: flex;
|
|
143
|
+
flex-direction: column;
|
|
122
144
|
overflow: hidden;
|
|
145
|
+
container-type: inline-size;
|
|
123
146
|
z-index: 10;
|
|
124
147
|
opacity: 0;
|
|
125
148
|
pointer-events: none;
|
|
126
149
|
transition: opacity 400ms cubic-bezier(0.4, 0, 0.2, 1);
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
)
|
|
137
|
-
|
|
138
|
-
|
|
150
|
+
box-shadow:
|
|
151
|
+
hsla(0, 0%, 100%, 1) -3.2px -3.2px 3.2px -3.2px inset,
|
|
152
|
+
hsla(0, 0%, 100%, 1) 6.4px 6.4px 1.6px -8px inset,
|
|
153
|
+
var(--aia-dropdown-bg, transparent) -6.4px 6.4px 1.6px -8px inset,
|
|
154
|
+
var(--aia-dropdown-bg, transparent) 6.4px -6.4px 1.6px -8px inset,
|
|
155
|
+
hsla(0, 0%, 100%, 0.15) -1.6px 0px 0px -1.6px inset,
|
|
156
|
+
hsla(0, 0%, 100%, 0.15) 0px -1.6px 0px -1.6px inset,
|
|
157
|
+
hsla(0, 0%, 100%, 0.3) 0px 1.6px 0px 0px inset,
|
|
158
|
+
hsla(0, 0%, 100%, 0.3) 1.6px 0px 0px 0px inset,
|
|
159
|
+
inset 0 0 30px 5px hsla(0, 0%, 0%, 0.05),
|
|
160
|
+
hsla(0, 0%, 0%, 0.08) 0px 0px 30px 2px;
|
|
161
|
+
backdrop-filter: blur(30px);
|
|
162
|
+
border-radius: 28px;
|
|
139
163
|
}
|
|
140
164
|
|
|
141
165
|
.magicx-aia-dropdown--visible {
|
|
@@ -148,6 +172,67 @@ function y(o,e){let t=o,i={},s=[];for(let r of e){let n=(i[r.type]??0)+1;i[r.typ
|
|
|
148
172
|
padding: 27px 27px 0px 27px;
|
|
149
173
|
}
|
|
150
174
|
|
|
175
|
+
/* --- Fallback loading skeleton bars (only when no cached options) --- */
|
|
176
|
+
.magicx-aia-skeleton-bars {
|
|
177
|
+
display: flex;
|
|
178
|
+
flex-direction: column;
|
|
179
|
+
gap: 20px;
|
|
180
|
+
padding: 25px;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
.magicx-aia-skeleton-bar {
|
|
184
|
+
display: block;
|
|
185
|
+
height: 19px;
|
|
186
|
+
border-radius: 999px;
|
|
187
|
+
background: var(--aia-skeleton-bg, var(--aia-pill-bg, rgba(189, 189, 189, 0.51)));
|
|
188
|
+
opacity: 0.5;
|
|
189
|
+
animation: magicx-aia-skeleton-pulse 1.4s ease-in-out infinite;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
.magicx-aia-skeleton-bar:nth-child(2) {
|
|
193
|
+
animation-delay: 150ms;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
.magicx-aia-skeleton-bar:nth-child(3) {
|
|
197
|
+
animation-delay: 300ms;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
@keyframes magicx-aia-skeleton-pulse {
|
|
201
|
+
0%,
|
|
202
|
+
100% {
|
|
203
|
+
opacity: 0.5;
|
|
204
|
+
}
|
|
205
|
+
50% {
|
|
206
|
+
opacity: 0.25;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/* --- Loading mask on real options (preserves layout, hides text) --- */
|
|
211
|
+
.magicx-aia-option[data-aia-loading] {
|
|
212
|
+
cursor: default;
|
|
213
|
+
animation: magicx-aia-option-skeleton-pulse 1.4s ease-in-out infinite;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
.magicx-aia-option[data-aia-loading] .magicx-aia-option-content {
|
|
217
|
+
color: transparent;
|
|
218
|
+
background: var(--aia-skeleton-bg, var(--aia-pill-bg, rgba(189, 189, 189, 0.51)));
|
|
219
|
+
border-radius: 999px;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
.magicx-aia-option[data-aia-loading] .magicx-aia-option-tag {
|
|
223
|
+
display: none;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
@keyframes magicx-aia-option-skeleton-pulse {
|
|
227
|
+
0%,
|
|
228
|
+
100% {
|
|
229
|
+
filter: brightness(1);
|
|
230
|
+
}
|
|
231
|
+
50% {
|
|
232
|
+
filter: brightness(0.55);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
151
236
|
/* --- Pill list --- */
|
|
152
237
|
.magicx-aia-pill-list {
|
|
153
238
|
position: relative;
|
|
@@ -176,7 +261,7 @@ function y(o,e){let t=o,i={},s=[];for(let r of e){let n=(i[r.type]??0)+1;i[r.typ
|
|
|
176
261
|
transparent
|
|
177
262
|
);
|
|
178
263
|
color: var(--aia-pill-color, var(--aia-color-text-muted, #c1c4cb));
|
|
179
|
-
font-family:
|
|
264
|
+
font-family: inherit;
|
|
180
265
|
font-size: var(--aia-pill-font-size, 19px);
|
|
181
266
|
line-height: 30px;
|
|
182
267
|
cursor: pointer;
|
|
@@ -208,6 +293,41 @@ function y(o,e){let t=o,i={},s=[];for(let r of e){let n=(i[r.type]??0)+1;i[r.typ
|
|
|
208
293
|
outline: 1px solid #5a5b8a;
|
|
209
294
|
}
|
|
210
295
|
|
|
296
|
+
/* Real pill rendered as a skeleton (mirrored from cached pills during loading).
|
|
297
|
+
Preserves the pill's full box so width/height match the previous state. */
|
|
298
|
+
.magicx-aia-pill[data-aia-loading] {
|
|
299
|
+
pointer-events: none;
|
|
300
|
+
cursor: default;
|
|
301
|
+
color: transparent;
|
|
302
|
+
animation: magicx-aia-pill-skeleton-pulse 1.4s ease-in-out infinite;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/* Fallback placeholder pills (used when there are no cached pills yet). */
|
|
306
|
+
.magicx-aia-pill--skeleton {
|
|
307
|
+
pointer-events: none;
|
|
308
|
+
cursor: default;
|
|
309
|
+
color: transparent;
|
|
310
|
+
background: var(--aia-skeleton-bg, var(--aia-pill-bg, rgba(189, 189, 189, 0.51)));
|
|
311
|
+
box-shadow: none;
|
|
312
|
+
backdrop-filter: none;
|
|
313
|
+
animation: magicx-aia-pill-skeleton-pulse 1.4s ease-in-out infinite;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
.magicx-aia-pill--skeleton:hover,
|
|
317
|
+
.magicx-aia-pill[data-aia-loading]:hover {
|
|
318
|
+
filter: none;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
@keyframes magicx-aia-pill-skeleton-pulse {
|
|
322
|
+
0%,
|
|
323
|
+
100% {
|
|
324
|
+
filter: brightness(1);
|
|
325
|
+
}
|
|
326
|
+
50% {
|
|
327
|
+
filter: brightness(0.55);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
211
331
|
@keyframes magicx-aia-fadeIn {
|
|
212
332
|
from {
|
|
213
333
|
opacity: 0;
|
|
@@ -218,6 +338,9 @@ function y(o,e){let t=o,i={},s=[];for(let r of e){let n=(i[r.type]??0)+1;i[r.typ
|
|
|
218
338
|
.magicx-aia-grid {
|
|
219
339
|
display: grid;
|
|
220
340
|
grid-template-columns: minmax(0, 250px);
|
|
341
|
+
/* Pack rows from the top instead of stretching to fill the grid container. */
|
|
342
|
+
grid-auto-rows: min-content;
|
|
343
|
+
align-content: start;
|
|
221
344
|
justify-content: start;
|
|
222
345
|
padding: 8px 8px;
|
|
223
346
|
max-height: 192px;
|
|
@@ -250,8 +373,10 @@ function y(o,e){let t=o,i={},s=[];for(let r of e){let n=(i[r.type]??0)+1;i[r.typ
|
|
|
250
373
|
position: relative;
|
|
251
374
|
overflow: visible;
|
|
252
375
|
display: flex;
|
|
253
|
-
align-
|
|
254
|
-
|
|
376
|
+
/* Top-align so single-line and multi-line options in the same row share
|
|
377
|
+
the same baseline at the top edge of the cell. */
|
|
378
|
+
align-items: flex-start;
|
|
379
|
+
font-family: inherit;
|
|
255
380
|
font-size: var(--aia-option-font-size, 19px);
|
|
256
381
|
line-height: 24px;
|
|
257
382
|
color: var(--aia-option-color, var(--aia-color-text-muted, #c1c4cb));
|
|
@@ -616,6 +741,8 @@ function y(o,e){let t=o,i={},s=[];for(let r of e){let n=(i[r.type]??0)+1;i[r.typ
|
|
|
616
741
|
|
|
617
742
|
--aia-color-text-muted: #6b7280;
|
|
618
743
|
|
|
744
|
+
--aia-skeleton-bg: rgba(189, 189, 189, 0.51);
|
|
745
|
+
|
|
619
746
|
--aia-streak-rgb: 99, 102, 241;
|
|
620
747
|
--aia-streak-glass-bg: rgba(99, 102, 241, 0.1);
|
|
621
748
|
}
|
|
@@ -640,6 +767,8 @@ function y(o,e){let t=o,i={},s=[];for(let r of e){let n=(i[r.type]??0)+1;i[r.typ
|
|
|
640
767
|
|
|
641
768
|
--aia-color-text-muted: #c1c4cb;
|
|
642
769
|
|
|
770
|
+
--aia-skeleton-bg: #333539;
|
|
771
|
+
|
|
643
772
|
--aia-streak-rgb: 255, 255, 255;
|
|
644
773
|
--aia-streak-glass-bg: rgba(255, 255, 255, 0.1);
|
|
645
774
|
}
|
|
@@ -664,5 +793,5 @@ function y(o,e){let t=o,i={},s=[];for(let r of e){let n=(i[r.type]??0)+1;i[r.typ
|
|
|
664
793
|
animation-duration: 0s !important;
|
|
665
794
|
transition-duration: 0s !important;
|
|
666
795
|
}
|
|
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};
|
|
796
|
+
`;var Qe=0;function $e(){return`:ac-${++Qe}:`}var Se=500;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,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:null,inSelectionAnimation:!1}}var Y=class{constructor(e,t={}){this.store=X(Te());this._listboxId=$e();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 Q(this.store,{onPillSelected:({rawQuery:n,selectedPill:s,otherPills:r})=>{this.fireTelemetry("pill",{raw_query:n,selected_pill:s,other_pills:r})}}),this.fetchController=new H(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.opts.onError,()=>this.sessionId,{onAutoMatch:({active:n,matched:s,rawQuery:r})=>{this.fireTelemetry("option",{raw_query:r,selected_option:s.text,other_options:(n.options??[]).filter(o=>o.text!==s.text).map(o=>o.text)})}}),this.keyboardController=new q(this.store,{columns:t.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.opts.onSubmit,afterSubmit:this.renderMode==="full"?()=>this.reset():void 0,selectOption:n=>this.selectOption(n),removeParamAtCaret:n=>this.removeParamAtCaret(n),exitEditMode:()=>this.exitEditMode()}),this.unsubscribers.push(this.store.subscribe((n,s)=>{this.recomputeDerived(n,s)})),this.unsubscribers.push(this.store.subscribe((n,s)=>{n.text!==s.text&&this.opts.onChange?.(n.text),n.completedParams!==s.completedParams&&this.opts.onParamsChange?.(n.completedParams),n.isFocused!==s.isFocused&&(n.isFocused?this.opts.onFocus?.():this.opts.onBlur?.()),this.opts.onStateChange?.(n)})),this.renderMode!=="headless"&&(ve(),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(){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.selectionAnimationTimer&&clearTimeout(this.selectionAnimationTimer),this.externalListeners.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)}removeLastParam(){this.pillsController.removeLastParam()}removeParamAtCaret(e){let t=this.store.get(),{text:n,completedParams:s}=t,r=0;for(let o=0;o<s.length;o++){let a=s[o],l=n.indexOf(a.text,r);if(l===-1)continue;let c=l,m=l+a.text.length;if(e>c&&e<=m){let u=me(n,e),d=n.slice(0,u)+n.slice(e),h=s.filter((x,b)=>b!==o);return this.store.set(x=>({text:d,filterBase:Math.min(x.filterBase,d.length),completedParams:h,pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(u),!0}r=m}return!1}scheduleSetCursor(e){queueMicrotask(()=>{let t=this.domRefs;t?S(t.input,e):this.opts.setCursor?.(e)})}clearNewParamId(){this.store.set({newParamId:null})}startEditingParam(e){let t=this.store.get();if(t.editingParam?.id===e)return;let n=t.completedParams.find(o=>o.id===e);if(!n)return;let s=0,r=-1;for(let o of t.completedParams){let a=t.text.indexOf(o.text,s);if(a!==-1){if(o.id===e){r=a;break}s=a+o.text.length}}r<0||this.store.set({editingParam:n,editingAnchor:r,editingTail:r+n.text.length,caretOffset:r+n.text.length,activeDropdownIndex:-1})}replaceEditingRange(e){let t=this.store.get(),n=t.editingParam,s=t.editingAnchor,r=t.editingTail;if(!n||s==null||r==null||!t.completedParams.some(l=>l.id===n.id))return!1;let o=t.text.slice(0,s)+e+t.text.slice(r),a=s+e.length;return this.store.set(l=>({text:o,completedParams:l.completedParams.filter(c=>c.id!==n.id),editingTail:a,caretOffset:a,activeDropdownIndex:-1})),this.scheduleSetCursor(a),this.maybePromoteEditExactMatch(),!0}exitEditMode(){this.store.get().editingParam&&this.store.set({editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1})}handleCaretAfterInput(e){let t=this.store.get(),n={caretOffset:e};t.editingParam&&t.editingAnchor!=null&&e!=null&&(e<t.editingAnchor?(n.editingParam=null,n.editingAnchor=null,n.editingTail=null,n.activeDropdownIndex=-1):t.editingTail!=null&&(n.editingTail=Math.max(t.editingTail,e))),this.store.set(n),this.maybePromoteEditExactMatch()}handleCaretMove(e){let t=this.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null&&e!=null&&(e<t.editingAnchor||e>t.editingTail)){this.store.set({caretOffset:e,editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1});return}this.store.set({caretOffset:e})}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();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null){this.selectOptionInEditMode(e);return}let n=t.actionableSuggestions[0];if(!n)return;let{rawQuery:s}=T(t.text,t.completedParams);this.fireTelemetry("option",{raw_query:s,selected_option:e.text,other_options:t.filteredOptions.filter(p=>p.text!==e.text).map(p=>p.text)});let r=t.filterBase,o=t.text.slice(0,r),a=o.length===0&&t.text.length===0,l=o.length===0&&t.text.length>0&&t.placeholderText.length>0&&t.placeholderText.toLowerCase().startsWith(t.text.toLowerCase());(a||l)&&t.placeholderText&&(o=`${t.placeholderText} `);let c=Z(o,e.text);c>0&&(o=o.slice(0,o.length-c));let m=o.length>0&&o[o.length-1]!==" ",u=`${o}${m?" ":""}${e.text} `,d=(a||l)&&u.length>0?u[0].toUpperCase()+u.slice(1):u,h=d.toLowerCase().lastIndexOf(e.text.toLowerCase()),x=h>=0?d.slice(h,h+e.text.length):e.text,b={id:crypto.randomUUID(),placeholder:"",type:n.type,text:x,kind:e.kind,suggestionType:n.type,suggestionPlaceholder:n.text,options:n.options??[],metadata:e.metadata},f=t.actionableSuggestions.length-1;this.store.set(p=>({text:d,filterBase:d.length,completedParams:[...p.completedParams,b],newParamId:b.id,caretOffset:d.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:f>0,inSelectionAnimation:!0})),this.startSelectionAnimationTimer(),this.suggestionRemovalTimer&&clearTimeout(this.suggestionRemovalTimer),f>0&&(this.suggestionRemovalTimer=window.setTimeout(()=>{this.store.set(p=>({suggestions:p.suggestions.filter(g=>g!==n)}))},Se))}startSelectionAnimationTimer(){this.selectionAnimationTimer&&clearTimeout(this.selectionAnimationTimer),this.selectionAnimationTimer=window.setTimeout(()=>{this.store.set({inSelectionAnimation:!1})},Se)}selectOptionInEditMode(e){let t=this.store.get(),n=t.editingParam,s=t.editingAnchor,r=t.editingTail;if(!n||s==null||r==null)return;this.fireTelemetry("option",{raw_query:T(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:n.options.filter(p=>p.text!==e.text).map(p=>p.text)});let o=t.text.slice(0,s),a=t.text.slice(r),l=s===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,c=a.length===0||a[0]!==" ",m=c?`${l} `:l,u=o+m+a,d=s+m.length+(c?0:1),h={id:crypto.randomUUID(),placeholder:"",type:n.suggestionType,text:l,kind:e.kind,suggestionType:n.suggestionType,suggestionPlaceholder:n.suggestionPlaceholder,options:n.options,metadata:e.metadata},x=t.completedParams.findIndex(p=>p.id===n.id),b=t.completedParams.filter(p=>p.id!==n.id),f=x>=0?Math.min(x,b.length):b.length;b.splice(f,0,h),this.store.set({text:u,completedParams:b,newParamId:h.id,filterBase:d,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:d,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.startSelectionAnimationTimer(),this.scheduleSetCursor(d)}fireTelemetry(e,t){let n=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");ie({source:n,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}recomputeDerived(e,t){if(this.derivedInProgress)return;this.derivedInProgress=!0;let n=ee(e.text,e.completedParams),s=e.suggestions.filter(g=>g.type!=="placeholder"),r=s[0],o=r?this.opts.optionOverrides?.[r.type]:void 0,a=e.suggestions.filter(g=>g.type==="placeholder").map(g=>g.text).join(" "),l=O(e.text,Math.min(e.filterBase,e.text.length),a),m=e.lastRawQuery!==""||l>0?w(e.text,l,e.filterInProgress):"",u=r?o?o(m.trim()):r.options??[]:[],d=e.editingParam!=null&&e.editingAnchor!=null,h;if(d&&e.editingParam&&e.editingAnchor!=null){let g=e.editingParam.id,y=e.completedParams.some(L=>L.id===g),v=e.caretOffset??e.editingAnchor,P=y?"":e.text.slice(e.editingAnchor,v);h=I(e.editingParam.options,P)}else h=I(u,m);let x=this.opts.dropdownTrigger??"auto",b=this.opts.closeDropdownOnBlur??!0,f=!1;if(d){let g=b?e.isFocused:!0;f=h.length>0&&g}else if(x==="auto"){let g=b?e.isFocused:!0,y=e.text.replace(/\s+$/,"").length,v=e.caretOffset==null||e.caretOffset>=y;f=(h.length>0||e.isLoading)&&g&&v}else x==="manual"&&(f=(h.length>0||e.isLoading)&&e.pillTapped);this.store.set({segments:n,actionableSuggestions:s,filteredOptions:h,placeholderText:a,isDropdownOpen:f}),this.derivedInProgress=!1;let p=this.store.get();for(let g of this.externalListeners)g(p)}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 M(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:n=>this.selectOption(n),setActivePill:n=>this.pillsController.setActivePill(n),handleKeyDown:n=>this.keyboardController.handleKeyDown(n),handleChange:n=>this.handleChange(n),startEditingParam:n=>this.startEditingParam(n),handleCaretAfterInput:n=>this.handleCaretAfterInput(n),handleCaretMove:n=>this.handleCaretMove(n),replaceEditingRange:n=>this.replaceEditingRange(n)};this.domRefs=ye(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&V(this.domRefs,this.store.get(),t)}),V(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=xe(this.container,e),this.subscribeBatchedRender(()=>{this.dropdownRefs&&z(this.dropdownRefs,this.store.get(),e)}),z(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:n,invalid:s}=te(e,t.completedParams);s.length>0&&this.store.set({completedParams:n}),this.maybePromoteExactMatch(e)}maybePromoteExactMatch(e){let t=this.store.get(),s=t.suggestions.filter(g=>g.type!=="placeholder")[0];if(!s?.options)return;let r=t.suggestions.filter(g=>g.type==="placeholder").map(g=>g.text).join(" "),o=O(e,t.filterBase,r),a=w(e,o,t.filterInProgress),l=E(s.options,a);if(!l)return;let c=l.text.toLowerCase(),m=e.toLowerCase().lastIndexOf(c),u=m>=0?m:Math.max(0,e.length-l.text.length),d=u+l.text.length,h=e.slice(u,d),x=e,f=d<e.length&&e[d]===" "?d+1:d,p={id:crypto.randomUUID(),placeholder:"",type:s.type,text:h,kind:l.kind,suggestionType:s.type,suggestionPlaceholder:s.text,options:s.options??[],metadata:l.metadata};this.store.set(g=>({text:x,completedParams:[...g.completedParams,p],suggestions:g.suggestions.filter(y=>y!==s),filterBase:f,newParamId:p.id,caretOffset:f,activeDropdownIndex:-1}))}maybePromoteEditExactMatch(){let e=this.store.get(),t=e.editingParam,n=e.editingAnchor,s=e.editingTail;if(!t||n==null||s==null||e.completedParams.some(y=>y.id===t.id))return;let r=e.text.slice(n,s),o=E(t.options,r);if(!o)return;let a=o.text.toLowerCase(),l=r.toLowerCase().lastIndexOf(a),c=n+Math.max(0,l),m=c+o.text.length,u=e.text.slice(c,m),d=e.text,x=m<e.text.length&&e.text[m]===" "?m+1:m,b={id:crypto.randomUUID(),placeholder:"",type:t.suggestionType,text:u,kind:o.kind,suggestionType:t.suggestionType,suggestionPlaceholder:t.suggestionPlaceholder,options:t.options,metadata:o.metadata},f=e.completedParams.length,p=0;for(let y=0;y<e.completedParams.length;y++){let v=d.indexOf(e.completedParams[y].text,p);if(v!==-1){if(v>=x){f=y;break}p=v+e.completedParams[y].text.length}}let g=[...e.completedParams];g.splice(f,0,b),this.store.set(()=>({text:d,completedParams:g,newParamId:b.id,filterBase:x,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:x,activeDropdownIndex:-1})),this.scheduleSetCursor(x)}};export{Y as AIAutocomplete,X as createStore};
|
|
668
797
|
//# sourceMappingURL=index.mjs.map
|