@magicx-eng/ai-autocomplete-vanilla 0.1.16 → 0.1.17
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 +13 -1
- package/index.js.map +1 -1
- package/index.mjs +13 -1
- package/index.mjs.map +1 -1
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var z=Object.defineProperty;var Ce=Object.getOwnPropertyDescriptor;var we=Object.getOwnPropertyNames;var Ee=Object.prototype.hasOwnProperty;var Ae=(i,e)=>{for(var t in e)z(i,t,{get:e[t],enumerable:!0})},Oe=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of we(e))!Ee.call(i,s)&&s!==t&&z(i,s,{get:()=>e[s],enumerable:!(n=Ce(e,s))||n.enumerable});return i};var Ie=i=>Oe(z({},"__esModule",{value:!0}),i);var Je={};Ae(Je,{AIAutocomplete:()=>G,createStore:()=>j});module.exports=Ie(Je);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 ee(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 te(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 ne(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 De="https://api.ai-autocomplete.com",R=`${De}/api/suggest`,ie=new WeakMap;function D(i){return i?.type==="accessToken"}function Le(i){if(!(!i||D(i)))return i}function _(i){let e=ie.get(i.getAccessToken);return e||(e=new k(i),ie.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=Le(i),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}function Me(i){return(i??R).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function ke(i){return D(i)?`Bearer ${await _(i).getToken()}`:F(i)}async function oe(i){try{let e=Me(i.apiConfig?.endpoint),t=N(i.apiConfig),n=await ke(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 Re="0.1.40",se=!1;function _e(){return crypto.randomUUID()}function Ne(i,e){return{placeholder:i.placeholder,type:i.type,...e&&{text:i.text},kind:i.kind}}function Fe(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=>Ne(o,t)),...r!=null&&{contact_account_count:r}},meta:{request_id:_e(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:Re,session_id:n}}}async function re(i,e,t,n,s){return fetch(i,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:n,signal:s})}async function ae(i,e,t){let n=t.apiConfig,s=!t.maskCompletedText,r=Fe(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 re(a,o,d,l,t.signal);if(h.status===401){let x=await u.getToken(!0);h=await re(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&&!se&&(se=!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 le(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 He=100,Be=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 ae(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:n.signal,apiConfig:this.getApiConfig()});if(s!==this.fetchVersion)return;let a=le(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)},He),this.slowDebounceTimer=setTimeout(()=>t(1),Be)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var de='[contenteditable="false"]',A;function qe(){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(de))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 V(i){let e=K(i),t="",n=e.nextNode();for(;n;)t+=n.data,n=e.nextNode();return t}function ue(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+=pe(s.childNodes[o],i);return r+ce(s,i)}return t.nodeType!==Node.TEXT_NODE||B(t,i)?null:ce(t,i)+n}function pe(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(de))return 0;let n=0;for(let s of Array.from(t.childNodes))n+=pe(s,e);return n}function ce(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,ue(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 me(i){let e=C(i);return e==null?!1:e>=ue(i)}function ge(i,e){if(e<=0)return 0;let t=qe();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 he(i){return i instanceof HTMLTextAreaElement||i instanceof HTMLInputElement?i.selectionStart!=null&&i.selectionStart===i.value.length:i instanceof HTMLElement&&i.hasAttribute("data-aia-input")?me(i):!1}function Qe(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=he(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}he(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=Qe(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 fe=[125,69];function xe(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<fe.length;c++){let m=fe[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(xe(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(xe(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 X(i){i.querySelector(".magicx-aia-pill-list")?.remove()}var $e=[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)),Ue(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 $e){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 Ue(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=We(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 We(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 be(i,e){let t=U(e.listboxId);return i.appendChild(t),{dropdown:t}}function J(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 ye(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 je='<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 Ge(){let i=document.createElement("div");return i.setAttribute("contenteditable","plaintext-only"),i.contentEditable==="plaintext-only"}function ve(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",Ge()?"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=je,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=V(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 Y(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(ye({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):X(s)}else X(s);h?(n.focus(),S(n,e.caretOffset??e.text.length)):e.isFocused&&V(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 j(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 Z=!1;function Se(){if(Z||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){Z=!0;return}Z=!0;let i=document.createElement("style");i.setAttribute("data-magicx-aia",""),i.textContent=ze,document.head.appendChild(i)}var ze=`/* ===================================================================
|
|
1
|
+
"use strict";var z=Object.defineProperty;var Ce=Object.getOwnPropertyDescriptor;var we=Object.getOwnPropertyNames;var Ee=Object.prototype.hasOwnProperty;var Ae=(i,e)=>{for(var t in e)z(i,t,{get:e[t],enumerable:!0})},Oe=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of we(e))!Ee.call(i,s)&&s!==t&&z(i,s,{get:()=>e[s],enumerable:!(n=Ce(e,s))||n.enumerable});return i};var Ie=i=>Oe(z({},"__esModule",{value:!0}),i);var Je={};Ae(Je,{AIAutocomplete:()=>G,createStore:()=>j});module.exports=Ie(Je);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 ee(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 te(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 ne(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 De="https://api.ai-autocomplete.com",R=`${De}/api/suggest`,ie=new WeakMap;function D(i){return i?.type==="accessToken"}function Le(i){if(!(!i||D(i)))return i}function _(i){let e=ie.get(i.getAccessToken);return e||(e=new k(i),ie.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=Le(i),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}function Me(i){return(i??R).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function ke(i){return D(i)?`Bearer ${await _(i).getToken()}`:F(i)}async function oe(i){try{let e=Me(i.apiConfig?.endpoint),t=N(i.apiConfig),n=await ke(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 Re="0.1.41",se=!1;function _e(){return crypto.randomUUID()}function Ne(i,e){return{placeholder:i.placeholder,type:i.type,...e&&{text:i.text},kind:i.kind}}function Fe(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=>Ne(o,t)),...r!=null&&{contact_account_count:r}},meta:{request_id:_e(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:Re,session_id:n}}}async function re(i,e,t,n,s){return fetch(i,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:n,signal:s})}async function ae(i,e,t){let n=t.apiConfig,s=!t.maskCompletedText,r=Fe(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 re(a,o,d,l,t.signal);if(h.status===401){let x=await u.getToken(!0);h=await re(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&&!se&&(se=!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 le(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 He=100,Be=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 ae(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:n.signal,apiConfig:this.getApiConfig()});if(s!==this.fetchVersion)return;let a=le(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)},He),this.slowDebounceTimer=setTimeout(()=>t(1),Be)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var de='[contenteditable="false"]',A;function qe(){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(de))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 V(i){let e=K(i),t="",n=e.nextNode();for(;n;)t+=n.data,n=e.nextNode();return t}function ue(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+=pe(s.childNodes[o],i);return r+ce(s,i)}return t.nodeType!==Node.TEXT_NODE||B(t,i)?null:ce(t,i)+n}function pe(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(de))return 0;let n=0;for(let s of Array.from(t.childNodes))n+=pe(s,e);return n}function ce(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,ue(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 me(i){let e=C(i);return e==null?!1:e>=ue(i)}function ge(i,e){if(e<=0)return 0;let t=qe();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 he(i){return i instanceof HTMLTextAreaElement||i instanceof HTMLInputElement?i.selectionStart!=null&&i.selectionStart===i.value.length:i instanceof HTMLElement&&i.hasAttribute("data-aia-input")?me(i):!1}function Qe(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=he(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}he(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=Qe(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 fe=[125,69];function xe(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<fe.length;c++){let m=fe[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(xe(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(xe(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 X(i){i.querySelector(".magicx-aia-pill-list")?.remove()}var $e=[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)),Ue(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 $e){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 Ue(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=We(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 We(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 be(i,e){let t=U(e.listboxId);return i.appendChild(t),{dropdown:t}}function J(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 ye(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 je='<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 Ge(){let i=document.createElement("div");return i.setAttribute("contenteditable","plaintext-only"),i.contentEditable==="plaintext-only"}function ve(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",Ge()?"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=je,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=V(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 Y(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(ye({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):X(s)}else X(s);h?(n.focus(),S(n,e.caretOffset??e.text.length)):e.isFocused&&V(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 j(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 Z=!1;function Se(){if(Z||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){Z=!0;return}Z=!0;let i=document.createElement("style");i.setAttribute("data-magicx-aia",""),i.textContent=ze,document.head.appendChild(i)}var ze=`/* ===================================================================
|
|
2
2
|
Vanilla core styles \u2014 stable BEM class names (magicx-aia-*)
|
|
3
3
|
Auto-injected at runtime on first instantiation.
|
|
4
4
|
=================================================================== */
|
|
@@ -720,6 +720,18 @@
|
|
|
720
720
|
* 3. These built-in defaults
|
|
721
721
|
*/
|
|
722
722
|
|
|
723
|
+
/*
|
|
724
|
+
* Library-scoped box-sizing reset. The SDK's pill / option / wrapper styles
|
|
725
|
+
* mix explicit dimensions with padding (e.g. .magicx-aia-pill has height:36px
|
|
726
|
+
* + padding:13px) and were authored assuming \`border-box\`. In consumer apps
|
|
727
|
+
* without a global \`* { box-sizing: border-box }\` reset the pill rendered
|
|
728
|
+
* ~62px tall instead of 36px. Scoping the reset to \`.magicx-aia\` descendants
|
|
729
|
+
* keeps the library self-contained without leaking onto consumer markup.
|
|
730
|
+
*/
|
|
731
|
+
:where(.magicx-aia, .magicx-aia *, .magicx-aia *::before, .magicx-aia *::after) {
|
|
732
|
+
box-sizing: border-box;
|
|
733
|
+
}
|
|
734
|
+
|
|
723
735
|
/* Light mode defaults (base) */
|
|
724
736
|
:where(.magicx-aia),
|
|
725
737
|
:where(.magicx-aia[data-mode="light"]) {
|