@magicx-eng/ai-autocomplete-vanilla 0.1.15 → 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 +5 -1
- package/index.d.mts +8 -0
- package/index.d.ts +8 -0
- package/index.js +44 -33
- package/index.js.map +1 -1
- package/index.mjs +44 -33
- package/index.mjs.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -19,6 +19,7 @@ A framework-agnostic vanilla JS/TypeScript library that provides a guided AI-pow
|
|
|
19
19
|
- **Accessible** — ARIA combobox 1.2 pattern with `role="listbox"`, `aria-activedescendant`
|
|
20
20
|
- **IME-safe** — composition events are buffered so input text is committed once, after composition ends
|
|
21
21
|
- **Animations** — option selection streak animation, text shimmer on newly added params
|
|
22
|
+
- **Loading skeleton** — while a fetch is in flight, the dropdown and inline pills keep the previous layout (same count and widths) with their text masked and a shimmer pulse. The skeleton is held back until the selection streak animation finishes, so taps don't visually "stutter" into loading.
|
|
22
23
|
- **Lightweight** — ~10 KB gzipped, styles auto-injected at runtime
|
|
23
24
|
- **TypeScript first** — full type definitions shipped with the package
|
|
24
25
|
- **SSR-safe** — no top-level `document`/`window` access
|
|
@@ -235,7 +236,9 @@ unsub();
|
|
|
235
236
|
| `activeDropdownIndex` | `number` | Highlighted option index (-1 = none) |
|
|
236
237
|
| `isDropdownOpen` | `boolean` | Whether the dropdown should be visible |
|
|
237
238
|
| `newParamId` | `string \| null` | ID of the most recently added param (for shimmer animation) |
|
|
238
|
-
| `isLoading` | `boolean` | Fetch in progress |
|
|
239
|
+
| `isLoading` | `boolean` | Fetch in progress. The Tier 1 / Tier 2 renderers gate the loading skeleton additionally on `!inSelectionAnimation` and `!editingParam`. |
|
|
240
|
+
| `inSelectionAnimation` | `boolean` | True for the 500 ms after a user-initiated option tap so the streak animation can finish before the dropdown switches to the loading skeleton. |
|
|
241
|
+
| `editingParam` | `CompletedParamState \| null` | When non-null, the user is re-editing a bold completed param; cached options remain visible and the loading skeleton is suppressed. |
|
|
239
242
|
| `isReady` | `boolean` | Server indicates query is complete |
|
|
240
243
|
| `error` | `Error \| null` | Last fetch error |
|
|
241
244
|
|
|
@@ -358,6 +361,7 @@ Override these on the container element. All built-in defaults use `:where()` (z
|
|
|
358
361
|
| `--aia-scrollbar-thumb` | `rgba(0, 0, 0, 0.3)` | `rgba(0, 0, 0, 0.3)` | Color of the option list's scrollbar thumb (Firefox + WebKit). |
|
|
359
362
|
| `--aia-streak-rgb` | `99, 102, 241` | `255, 255, 255` | Comma-separated RGB triplet used to tint the option-selection streak animation (consumed via `rgba(var(--aia-streak-rgb), …)`). |
|
|
360
363
|
| `--aia-streak-glass-bg` | `rgba(99, 102, 241, 0.1)` | `rgba(255, 255, 255, 0.1)` | Background fill for the streak's glass-pill effect. |
|
|
364
|
+
| `--aia-skeleton-bg` | `rgba(189, 189, 189, 0.51)` | `#333539` | Fill color for the loading skeleton bars and the masked text in cached pills/options. |
|
|
361
365
|
|
|
362
366
|
### Per-mode Overrides
|
|
363
367
|
|
package/index.d.mts
CHANGED
|
@@ -101,6 +101,12 @@ interface CoreState {
|
|
|
101
101
|
editingTail: number | null;
|
|
102
102
|
/** Current caret offset within the editor. Tracked via DOM `selectionchange`. */
|
|
103
103
|
caretOffset: number | null;
|
|
104
|
+
/**
|
|
105
|
+
* True for ~500ms after a user-initiated option selection so the streak
|
|
106
|
+
* animation can finish before the dropdown switches to its loading skeleton.
|
|
107
|
+
* Set by selectOption / selectOptionInEditMode, cleared by a timer.
|
|
108
|
+
*/
|
|
109
|
+
inSelectionAnimation: boolean;
|
|
104
110
|
}
|
|
105
111
|
/**
|
|
106
112
|
* Render mode:
|
|
@@ -178,6 +184,7 @@ declare class AIAutocomplete {
|
|
|
178
184
|
private dropdownRefs;
|
|
179
185
|
private newParamTimer;
|
|
180
186
|
private suggestionRemovalTimer;
|
|
187
|
+
private selectionAnimationTimer;
|
|
181
188
|
private externalListeners;
|
|
182
189
|
private sessionId;
|
|
183
190
|
constructor(container: HTMLElement, opts?: CoreOptions);
|
|
@@ -250,6 +257,7 @@ declare class AIAutocomplete {
|
|
|
250
257
|
on(event: string, callback: (...args: unknown[]) => void): () => void;
|
|
251
258
|
update(opts: Partial<CoreOptions>): void;
|
|
252
259
|
selectOption(option: SuggestionOption): void;
|
|
260
|
+
private startSelectionAnimationTimer;
|
|
253
261
|
private selectOptionInEditMode;
|
|
254
262
|
private fireTelemetry;
|
|
255
263
|
private recomputeDerived;
|
package/index.d.ts
CHANGED
|
@@ -101,6 +101,12 @@ interface CoreState {
|
|
|
101
101
|
editingTail: number | null;
|
|
102
102
|
/** Current caret offset within the editor. Tracked via DOM `selectionchange`. */
|
|
103
103
|
caretOffset: number | null;
|
|
104
|
+
/**
|
|
105
|
+
* True for ~500ms after a user-initiated option selection so the streak
|
|
106
|
+
* animation can finish before the dropdown switches to its loading skeleton.
|
|
107
|
+
* Set by selectOption / selectOptionInEditMode, cleared by a timer.
|
|
108
|
+
*/
|
|
109
|
+
inSelectionAnimation: boolean;
|
|
104
110
|
}
|
|
105
111
|
/**
|
|
106
112
|
* Render mode:
|
|
@@ -178,6 +184,7 @@ declare class AIAutocomplete {
|
|
|
178
184
|
private dropdownRefs;
|
|
179
185
|
private newParamTimer;
|
|
180
186
|
private suggestionRemovalTimer;
|
|
187
|
+
private selectionAnimationTimer;
|
|
181
188
|
private externalListeners;
|
|
182
189
|
private sessionId;
|
|
183
190
|
constructor(container: HTMLElement, opts?: CoreOptions);
|
|
@@ -250,6 +257,7 @@ declare class AIAutocomplete {
|
|
|
250
257
|
on(event: string, callback: (...args: unknown[]) => void): () => void;
|
|
251
258
|
update(opts: Partial<CoreOptions>): void;
|
|
252
259
|
selectOption(option: SuggestionOption): void;
|
|
260
|
+
private startSelectionAnimationTimer;
|
|
253
261
|
private selectOptionInEditMode;
|
|
254
262
|
private fireTelemetry;
|
|
255
263
|
private recomputeDerived;
|
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 Oe=(i,e)=>{for(var t in e)z(i,t,{get:e[t],enumerable:!0})},Ie=(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 Ae=i=>Ie(z({},"__esModule",{value:!0}),i);var Ze={};Oe(Ze,{AIAutocomplete:()=>G,createStore:()=>j});module.exports=Ae(Ze);function P(i,e){let t=i,n={},s=[];for(let r of e){let o=(n[r.type]??0)+1;n[r.type]=o;let c=`{{${r.type.toUpperCase().replace(/\s+/g,"_")}_${o}}}`,l=t.indexOf(r.text);l!==-1&&(t=t.slice(0,l)+c+t.slice(l+r.text.length)),s.push({...r,placeholder:c})}return{rawQuery:t,completedParams:s}}function I(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 A(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 H(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()}`:H(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.39",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 He(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=He(i,e,s,t.sessionId),o=N(n),a=n?.endpoint??R,c=JSON.stringify(r);if(D(n)){let d=_(n),u=await d.getToken(),x=await re(a,o,u,c,t.signal);if(x.status===401){let f=await d.getToken(!0);x=await re(a,o,f,c,t.signal)}if(!x.ok)throw new Error(`API error: ${x.status} ${x.statusText}`);return x.json()}let l=H(n);!l&&!se&&(se=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),l&&(o.Authorization=l);let p=await fetch(a,{method:"POST",headers:o,body:c,signal:t.signal});if(!p.ok)throw new Error(`API error: ${p.status} ${p.statusText}`);return p.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 Fe=100,Be=300,Ke=2,F=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()),c=o.data.input??[],l=c[c.length-1],p=this.store.get().text,d,u;if(l?.state==="in_progress"){u=!0;let h=p.toLowerCase().lastIndexOf(l.text.toLowerCase());d=h!==-1?h:r}else u=!1,d=r;let f=a.filter(h=>h.type!=="placeholder")[0],b=null;if(f){let h=w(p,d,u),m=E(f.options,h);m&&(b={id:crypto.randomUUID(),placeholder:"",type:f.type,text:m.text,kind:m.kind,suggestionType:f.type,suggestionPlaceholder:f.text,options:f.options??[],metadata:m.metadata},a=a.filter(g=>g!==f),this.callbacks.onAutoMatch?.({active:f,matched:m,rawQuery:e}))}this.store.set(h=>({suggestions:a,isLoading:!1,isReady:o.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:d,filterInProgress:u,...b?{completedParams:[...h.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=I(s.text,s.filterBase,r),a=w(s.text,o,s.filterInProgress),l=s.suggestions.filter(g=>g.type!=="placeholder")[0],d=(l?A(l.options,a):[]).filter(g=>g.is_tappable),u=l?E(l.options,a)!==null:!1,x=a.trim().length>0;if(d.length>0&&!u&&x||s.completedParams.length===0&&s.text.length>0&&r.length>0&&r.toLowerCase().startsWith(s.text.toLowerCase()))return!1;let{rawQuery:f,completedParams:b}=P(s.text,s.completedParams),h=f.length<s.lastRawQuery.length,m=Math.abs(f.length-s.lastRawQuery.length);return h||m>=n?(this.doFetch(f,b),!0):!1};this.debounceTimer=setTimeout(()=>{t(Ke)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},Fe),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"]',O;function qe(){if(O!==void 0)return O;let i=globalThis.Intl.Segmenter;if(!i)return O=null,null;try{O=new i(void 0,{granularity:"grapheme"})}catch{O=null}return O??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 pe(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+ce(s,i)}return t.nodeType!==Node.TEXT_NODE||B(t,i)?null:ce(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(de))return 0;let n=0;for(let s of Array.from(t.childNodes))n+=ue(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,pe(i))),r=K(i),o=0,a=null,c=0,l=r.nextNode(),p=null;for(;l;){let u=l.data.length;if(s<o+u){a=l,c=s-o;break}if(s===o+u){let x=r.nextNode();x?(a=x,c=0):(a=l,c=u);break}o+=u,p=l,l=r.nextNode()}let d=t.createRange();if(a){let u=a.parentElement?.closest('strong[data-seg="completed"]');u&&u!==i&&i.contains(u)?c===0?d.setStartBefore(u):c===a.data.length?d.setStartAfter(u):d.setStart(a,c):d.setStart(a,c)}else p?d.setStart(p,p.data.length):d.setStart(i,0);d.collapse(!0),n.removeAllRanges(),n.addRange(d)}function me(i){let e=C(i);return e==null?!1:e>=pe(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 $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 c=he(e.target),l=!!t.editingParam;if(!c&&!l&&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 p=a.indexOf(t.activeDropdownIndex),d=p<a.length-1?p+1:0;this.store.set({activeDropdownIndex:a[d]});break}case"ArrowUp":{if(a.length===0||t.activeDropdownIndex<0)break;if(e.preventDefault(),t.activeDropdownIndex<r){this.store.set({activeDropdownIndex:-1});break}let c=a.indexOf(t.activeDropdownIndex),l=c>0?c-1:a.length-1;this.store.set({activeDropdownIndex:a[l]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%r<r-1){let p=t.activeDropdownIndex+1;p<t.filteredOptions.length&&t.filteredOptions[p]?.is_tappable&&this.store.set({activeDropdownIndex:p})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let l=e.target.closest("[data-aia-input]")??e.target,p=t.editingTail;this.ctx.exitEditMode?.(),S(l,p);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 c=t.activeDropdownIndex-1;c>=0&&t.filteredOptions[c]?.is_tappable&&this.store.set({activeDropdownIndex:c})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let c=e.target.closest("[data-aia-input]")??e.target,l=t.editingAnchor;this.ctx.exitEditMode?.(),S(c,l);break}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let c=$e(e.target);if(c==null)break;this.ctx.removeParamAtCaret(c)&&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:c,completedParams:l}=P(t.text,t.completedParams);o({query:t.text.trim(),raw_query:c,completed_params:l}),this.ctx.afterSubmit?.()}break}case"Tab":{let c=!t.text&&!!t.placeholderText,l=t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable;if(c&&!l){e.preventDefault();let p=t.placeholderText;if(this.store.set(d=>({text:p,filterBase:p.length,suggestions:d.suggestions.filter(u=>u.type!=="placeholder")})),e.target instanceof HTMLElement){let d=e.target.closest("[data-aia-input]")??e.target;queueMicrotask(()=>S(d,p.length))}}else if(l)e.preventDefault(),this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,n);else if(t.isDropdownOpen){let p=t.filteredOptions.findIndex(d=>d.is_tappable);p>=0&&(e.preventDefault(),this.clickOrSelect(p,t.filteredOptions,n))}break}case"Escape":{if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){let c=e.target.closest("[data-aia-input]")??e.target,l=t.editingTail;this.ctx.exitEditMode?.(),S(c,l)}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,c)=>c!==e),o=t.suggestions.filter(a=>a.type==="placeholder");this.store.set({suggestions:[...o,s,...r],pillTapped:!0,activeDropdownIndex:-1})}};var $=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,c)=>c!==e),o=t.suggestions.filter(a=>a.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:a}=P(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:a,selectedPill:s.text,otherPills:r.map(c=>c.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 Q(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){o.setAttribute("data-aia-pill-list-loading",""),o.innerHTML="";for(let l=0;l<fe.length;l++){let p=fe[l],d=document.createElement("span");d.setAttribute("data-aia-pill-skeleton",""),d.className=`magicx-aia-pill magicx-aia-pill--skeleton${s?" magicx-aia-pill--rounded":""}`,d.style.width=`${p}px`,d.style.opacity=String(xe(l)),o.appendChild(d)}return}o.removeAttribute("data-aia-pill-list-loading");let a=new Map;for(let l of o.querySelectorAll(".magicx-aia-pill"))a.set(l.dataset.pillKey??"",l);let c=new Set;for(let l=0;l<e.length;l++){let p=e[l],d=`${p.type}-${p.text}`;c.add(d);let u=a.get(d);(!u||u.tagName!=="BUTTON")&&(u?.remove(),u=document.createElement("button"),u.type="button",u.tabIndex=-1,u.dataset.pillKey=d,u.setAttribute("data-aia-pill",""),u.setAttribute("contenteditable","false"),u.textContent=p.text,u.addEventListener("mousedown",x=>x.preventDefault())),u.className=`magicx-aia-pill${s?" magicx-aia-pill--rounded":""}${l===t?" magicx-aia-pill--active":""}`,u.style.width="",u.style.opacity=String(xe(l)),u.onclick=()=>n(l),o.children[l]!==u&&o.insertBefore(u,o.children[l]??null)}for(let[l,p]of a)c.has(l)||p.remove();for(let l of o.querySelectorAll("[data-aia-pill-skeleton]"))l.remove()}function X(i){i.querySelector(".magicx-aia-pill-list")?.remove()}var Qe=[159,119,164],Ue=[115,122];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:c,onHighlight:l,onPillClick:p}=e,d=a&&o.length>0,u=s&&t.length>0;s&&(r||u||d)?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 f=i.querySelector(".magicx-aia-skeleton");if(r){if(i.querySelector(".magicx-aia-pill-bar")?.remove(),i.querySelector(".magicx-aia-grid")?.remove(),!f)f=We(a),i.appendChild(f);else{let m=f.querySelector(".magicx-aia-skeleton-pills");a&&!m?f.insertBefore(be(),f.firstChild):!a&&m&&m.remove()}return}f&&f.remove();let b=i.querySelector(".magicx-aia-pill-bar");d?(b||(b=document.createElement("div"),b.className="magicx-aia-pill-bar",b.setAttribute("data-aia-pillbar",""),i.insertBefore(b,i.firstChild)),Q(b,o,0,p,!0)):b&&b.remove();let h=i.querySelector(".magicx-aia-grid");t.length>0?(h||(h=document.createElement("div"),h.className="magicx-aia-grid",i.appendChild(h)),je(h,t,n,c,l,e.listboxId)):h&&(h.innerHTML="")}function We(i){let e=document.createElement("div");e.className="magicx-aia-skeleton",e.setAttribute("data-aia-skeleton",""),i&&e.appendChild(be());let t=document.createElement("div");t.className="magicx-aia-skeleton-bars";for(let n of Qe){let s=document.createElement("span");s.className="magicx-aia-skeleton-bar",s.style.width=`${n}px`,t.appendChild(s)}return e.appendChild(t),e}function be(){let i=document.createElement("div");i.className="magicx-aia-skeleton-pills",i.setAttribute("data-aia-skeleton-pills","");for(let e of Ue){let t=document.createElement("span");t.className="magicx-aia-skeleton-pill",t.style.width=`${e}px`,i.appendChild(t)}return i}function je(i,e,t,n,s,r){let o=e.map(l=>l.text).join("\0"),a=i.dataset.optionsKey??"",c=o!==a;if(i.dataset.optionsKey=o,c){let l=document.createDocumentFragment();for(let p=0;p<e.length;p++){let d=e[p],u=Ge(d,p,t,n,s,r);l.appendChild(u)}i.innerHTML="",i.appendChild(l)}else{let l=i.querySelectorAll(".magicx-aia-option");for(let p=0;p<l.length;p++){let d=l[p],u=p===t;d.setAttribute("aria-selected",String(u)),u?d.classList.add("magicx-aia-option--highlighted"):d.classList.remove("magicx-aia-option--highlighted")}}}function Ge(i,e,t,n,s,r){let o=document.createElement("div");o.id=`${r}-option-${e}`,o.setAttribute("role","option"),o.setAttribute("data-aia-option",""),o.setAttribute("aria-selected",String(e===t)),o.tabIndex=i.is_tappable?0:-1;let a=["magicx-aia-option"];e===t&&a.push("magicx-aia-option--highlighted"),i.is_tappable?a.push("magicx-aia-option--tappable"):a.push("magicx-aia-option--non-tappable"),o.className=a.join(" ");let c=document.createElement("div");c.className="magicx-aia-streaks",o.appendChild(c);let l=document.createElement("div");l.className="magicx-aia-streaks-vert",o.appendChild(l);let p=document.createElement("span");if(p.className="magicx-aia-option-content",p.textContent=i.icon?`${i.icon} ${i.text}`:i.text,i.tag){let d=document.createElement("span");d.className="magicx-aia-option-tag",d.textContent=i.tag,p.appendChild(d)}return o.appendChild(p),i.is_tappable&&(o.addEventListener("click",()=>{o.classList.add("magicx-aia-option--pressed"),n(i),setTimeout(()=>o.classList.remove("magicx-aia-option--pressed"),400)}),o.addEventListener("mouseenter",()=>s(e))),o}function ye(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,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,onSelect:t.selectOption,onHighlight:n=>t.store.set({activeDropdownIndex:n}),onPillClick:t.setActivePill})}function ve(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 c=t.map(h=>`${h.type}:${h.value}`).join("\0"),l=e.dataset.segKey??"",p=e.dataset.newParamId??"",d=e.dataset.editingParamId??"";if(c===l&&(n??"")===p&&(s??"")===d)return;let u=o?C(e):null;e.dataset.segKey=c,e.dataset.newParamId=n??"",e.dataset.editingParamId=s??"";let x=e.ownerDocument??document,f=x.createDocumentFragment(),b=0;for(let h of t)if(b+=h.value.length,h.type==="completed"){let m=x.createElement("strong");m.dataset.seg="completed",m.dataset.paramId=h.param.id;let g=h.param.id===n,y=h.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"),m.className=v.join(" "),m.textContent=h.value,f.appendChild(m)}else f.appendChild(x.createTextNode(h.value));e.replaceChildren(f),e.dataset.aiaTextLength=String(b),u!=null&&S(e,Math.max(0,Math.min(u,b)))}var ze='<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 Ve(){let i=document.createElement("div");return i.setAttribute("contenteditable","plaintext-only"),i.contentEditable==="plaintext-only"}function Se(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",Ve()?"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 c=null,l=null;e.submitButton===void 0?(c=document.createElement("button"),c.type="button",c.className="magicx-aia-submit",c.setAttribute("aria-label","Submit"),c.setAttribute("data-aia-submit",""),c.innerHTML=ze,s.appendChild(c),l=c):e.submitButton!==null&&(l=e.submitButton,l.hasAttribute("data-aia-submit")||l.setAttribute("data-aia-submit",""),s.appendChild(l));let p=new AbortController,{signal:d}=p,u=!1,x=0,f=()=>{let m=V(o),y=m.length>0&&m[0]!==m[0].toUpperCase()?m[0].toUpperCase()+m.slice(1):m;e.handleChange(y)},b=()=>{let m=(o.ownerDocument??document).getSelection();if(!m||m.rangeCount===0)return null;let g=m.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",m=>{m.target?.closest("[data-aia-pill]")||o.focus()},{signal:d}),o.addEventListener("input",()=>{u||(x=performance.now(),f(),e.handleCaretAfterInput(C(o)))},{signal:d});let h=o.ownerDocument??document;return h.addEventListener("selectionchange",()=>{let m=h.getSelection();if(!m||m.rangeCount===0||!o.contains(m.anchorNode))return;let g=b(),y=e.store.get().editingParam?.id??null;if(g&&g!==y){e.startEditingParam(g);return}performance.now()-x<50||e.handleCaretMove(C(o))},{signal:d}),o.addEventListener("compositionstart",()=>{u=!0},{signal:d}),o.addEventListener("compositionend",()=>{u=!1,f()},{signal:d}),o.addEventListener("beforeinput",m=>{let g=m,y=g.inputType;if(y==="insertParagraph"||y==="insertLineBreak"||y==="insertFromDrop"){m.preventDefault();return}if(y.startsWith("insert")||y.startsWith("delete")){let v=y.startsWith("delete")?"":g.data??"";e.replaceEditingRange(v)&&m.preventDefault()}},{signal:d}),o.addEventListener("paste",m=>{m.preventDefault();let g=(m.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 T=v.getRangeAt(0);if(!o.contains(T.startContainer))return;T.deleteContents();let L=y.createTextNode(g);T.insertNode(L),T.setStartAfter(L),T.collapse(!0),v.removeAllRanges(),v.addRange(T),f()},{signal:d}),o.addEventListener("keydown",m=>e.handleKeyDown(m),{signal:d}),o.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:d}),o.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:d}),l&&l.addEventListener("click",m=>{let g=e.store.get();if(!(!!g.text||g.completedParams.length>0)||!e.onSubmit)return;m.stopPropagation();let{rawQuery:v,completedParams:T}=P(g.text,g.completedParams);e.onSubmit({query:g.text.trim(),raw_query:v,completed_params:T}),e.afterSubmit?.()},{signal:d}),e.autoFocus!==!1&&o.focus(),{input:o,inlinePillContainer:a,dropdown:n,submitButton:c,abort:p}}function Y(i,e,t){let{input:n,inlinePillContainer:s,dropdown:r,submitButton:o}=i,{pillPlacement:a,setActivePill:c,selectOption:l,store:p}=t;n.setAttribute("aria-expanded",String(e.isDropdownOpen));let d=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(d?n.setAttribute("aria-activedescendant",d):n.removeAttribute("aria-activedescendant"),o){let h=!!e.text||e.completedParams.length>0;o.disabled=!h}let u=n.dataset.newParamId??"",x=e.newParamId!==null&&e.newParamId!==u;if(ve({input:n,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused}),a==="inline"){let h=e.isLoading&&!e.editingParam;h||e.actionableSuggestions.length>0?Q(s,e.actionableSuggestions,0,c,!1,h):X(s)}else X(s);x?(n.focus(),S(n,e.caretOffset??e.text.length)):e.isFocused&&V(n)!==e.text&&S(n,e.text.length);let f=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:null,b=f??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,listboxId:t.listboxId,pills:f?[f]:e.actionableSuggestions,showPills:a==="dropdown",onSelect:l,onHighlight:h=>p.set({activeDropdownIndex:h}),onPillClick:c})}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 Pe(){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=Xe,document.head.appendChild(i)}var Xe=`/* ===================================================================
|
|
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=`/* ===================================================================
|
|
2
2
|
Vanilla core styles \u2014 stable BEM class names (magicx-aia-*)
|
|
3
3
|
Auto-injected at runtime on first instantiation.
|
|
4
4
|
=================================================================== */
|
|
@@ -172,37 +172,12 @@
|
|
|
172
172
|
padding: 27px 27px 0px 27px;
|
|
173
173
|
}
|
|
174
174
|
|
|
175
|
-
/* ---
|
|
176
|
-
.magicx-aia-skeleton {
|
|
177
|
-
display: flex;
|
|
178
|
-
flex-direction: column;
|
|
179
|
-
gap: 20px;
|
|
180
|
-
padding: 25px;
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
.magicx-aia-skeleton-pills {
|
|
184
|
-
display: flex;
|
|
185
|
-
gap: 5px;
|
|
186
|
-
align-items: center;
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
.magicx-aia-skeleton-pill {
|
|
190
|
-
display: inline-block;
|
|
191
|
-
height: 30px;
|
|
192
|
-
border-radius: 999px;
|
|
193
|
-
background: var(--aia-skeleton-bg, var(--aia-pill-bg, rgba(189, 189, 189, 0.51)));
|
|
194
|
-
opacity: 0.5;
|
|
195
|
-
animation: magicx-aia-skeleton-pulse 1.4s ease-in-out infinite;
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
.magicx-aia-skeleton-pills .magicx-aia-skeleton-pill:nth-child(2) {
|
|
199
|
-
opacity: 0.3;
|
|
200
|
-
}
|
|
201
|
-
|
|
175
|
+
/* --- Fallback loading skeleton bars (only when no cached options) --- */
|
|
202
176
|
.magicx-aia-skeleton-bars {
|
|
203
177
|
display: flex;
|
|
204
178
|
flex-direction: column;
|
|
205
179
|
gap: 20px;
|
|
180
|
+
padding: 25px;
|
|
206
181
|
}
|
|
207
182
|
|
|
208
183
|
.magicx-aia-skeleton-bar {
|
|
@@ -232,6 +207,32 @@
|
|
|
232
207
|
}
|
|
233
208
|
}
|
|
234
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
|
+
|
|
235
236
|
/* --- Pill list --- */
|
|
236
237
|
.magicx-aia-pill-list {
|
|
237
238
|
position: relative;
|
|
@@ -292,18 +293,28 @@
|
|
|
292
293
|
outline: 1px solid #5a5b8a;
|
|
293
294
|
}
|
|
294
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). */
|
|
295
306
|
.magicx-aia-pill--skeleton {
|
|
296
307
|
pointer-events: none;
|
|
297
308
|
cursor: default;
|
|
298
|
-
|
|
299
|
-
padding: 0;
|
|
309
|
+
color: transparent;
|
|
300
310
|
background: var(--aia-skeleton-bg, var(--aia-pill-bg, rgba(189, 189, 189, 0.51)));
|
|
301
311
|
box-shadow: none;
|
|
302
312
|
backdrop-filter: none;
|
|
303
313
|
animation: magicx-aia-pill-skeleton-pulse 1.4s ease-in-out infinite;
|
|
304
314
|
}
|
|
305
315
|
|
|
306
|
-
.magicx-aia-pill--skeleton:hover
|
|
316
|
+
.magicx-aia-pill--skeleton:hover,
|
|
317
|
+
.magicx-aia-pill[data-aia-loading]:hover {
|
|
307
318
|
filter: none;
|
|
308
319
|
}
|
|
309
320
|
|
|
@@ -313,7 +324,7 @@
|
|
|
313
324
|
filter: brightness(1);
|
|
314
325
|
}
|
|
315
326
|
50% {
|
|
316
|
-
filter: brightness(0.
|
|
327
|
+
filter: brightness(0.55);
|
|
317
328
|
}
|
|
318
329
|
}
|
|
319
330
|
|
|
@@ -782,5 +793,5 @@
|
|
|
782
793
|
animation-duration: 0s !important;
|
|
783
794
|
transition-duration: 0s !important;
|
|
784
795
|
}
|
|
785
|
-
`;var Je=0;function Ye(){return`:ac-${++Je}:`}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}}var G=class{constructor(e,t={}){this.store=j(Te());this._listboxId=Ye();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 $(this.store,{onPillSelected:({rawQuery:n,selectedPill:s,otherPills:r})=>{this.fireTelemetry("pill",{raw_query:n,selected_pill:s,other_pills:r})}}),this.fetchController=new F(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"&&(Pe(),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.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],c=n.indexOf(a.text,r);if(c===-1)continue;let l=c,p=c+a.text.length;if(e>l&&e<=p){let d=ge(n,e),u=n.slice(0,d)+n.slice(e),x=s.filter((f,b)=>b!==o);return this.store.set(f=>({text:u,filterBase:Math.min(f.filterBase,u.length),completedParams:x,pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(d),!0}r=p}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(c=>c.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(c=>({text:o,completedParams:c.completedParams.filter(l=>l.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}=P(t.text,t.completedParams);this.fireTelemetry("option",{raw_query:s,selected_option:e.text,other_options:t.filteredOptions.filter(m=>m.text!==e.text).map(m=>m.text)});let r=t.filterBase,o=t.text.slice(0,r),a=o.length===0&&t.text.length===0,c=o.length===0&&t.text.length>0&&t.placeholderText.length>0&&t.placeholderText.toLowerCase().startsWith(t.text.toLowerCase());(a||c)&&t.placeholderText&&(o=`${t.placeholderText} `);let l=ee(o,e.text);l>0&&(o=o.slice(0,o.length-l));let p=o.length>0&&o[o.length-1]!==" ",d=`${o}${p?" ":""}${e.text} `,u=(a||c)&&d.length>0?d[0].toUpperCase()+d.slice(1):d,x=u.toLowerCase().lastIndexOf(e.text.toLowerCase()),f=x>=0?u.slice(x,x+e.text.length):e.text,b={id:crypto.randomUUID(),placeholder:"",type:n.type,text:f,kind:e.kind,suggestionType:n.type,suggestionPlaceholder:n.text,options:n.options??[],metadata:e.metadata},h=t.actionableSuggestions.length-1;this.store.set(m=>({text:u,filterBase:u.length,completedParams:[...m.completedParams,b],newParamId:b.id,caretOffset:u.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:h>0})),this.suggestionRemovalTimer=window.setTimeout(()=>{this.store.set(m=>({suggestions:m.suggestions.filter(g=>g!==n)}))},400)}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:P(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:n.options.filter(m=>m.text!==e.text).map(m=>m.text)});let o=t.text.slice(0,s),a=t.text.slice(r),c=s===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,l=a.length===0||a[0]!==" ",p=l?`${c} `:c,d=o+p+a,u=s+p.length+(l?0:1),x={id:crypto.randomUUID(),placeholder:"",type:n.suggestionType,text:c,kind:e.kind,suggestionType:n.suggestionType,suggestionPlaceholder:n.suggestionPlaceholder,options:n.options,metadata:e.metadata},f=t.completedParams.findIndex(m=>m.id===n.id),b=t.completedParams.filter(m=>m.id!==n.id),h=f>=0?Math.min(f,b.length):b.length;b.splice(h,0,x),this.store.set({text:d,completedParams:b,newParamId:x.id,filterBase:u,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:u,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0}),this.scheduleSetCursor(u)}fireTelemetry(e,t){let n=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");oe({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=te(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(" "),c=I(e.text,Math.min(e.filterBase,e.text.length),a),p=e.lastRawQuery!==""||c>0?w(e.text,c,e.filterInProgress):"",d=r?o?o(p.trim()):r.options??[]:[],u=e.editingParam!=null&&e.editingAnchor!=null,x;if(u&&e.editingParam&&e.editingAnchor!=null){let g=e.editingParam.id,y=e.completedParams.some(L=>L.id===g),v=e.caretOffset??e.editingAnchor,T=y?"":e.text.slice(e.editingAnchor,v);x=A(e.editingParam.options,T)}else x=A(d,p);let f=this.opts.dropdownTrigger??"auto",b=this.opts.closeDropdownOnBlur??!0,h=!1;if(u){let g=b?e.isFocused:!0;h=x.length>0&&g}else if(f==="auto"){let g=b?e.isFocused:!0,y=e.text.replace(/\s+$/,"").length,v=e.caretOffset==null||e.caretOffset>=y;h=(x.length>0||e.isLoading)&&g&&v}else f==="manual"&&(h=(x.length>0||e.isLoading)&&e.pillTapped);this.store.set({segments:n,actionableSuggestions:s,filteredOptions:x,placeholderText:a,isDropdownOpen:h}),this.derivedInProgress=!1;let m=this.store.get();for(let g of this.externalListeners)g(m)}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=Se(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&Y(this.domRefs,this.store.get(),t)}),Y(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=ye(this.container,e),this.subscribeBatchedRender(()=>{this.dropdownRefs&&J(this.dropdownRefs,this.store.get(),e)}),J(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}=ne(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=I(e,t.filterBase,r),a=w(e,o,t.filterInProgress),c=E(s.options,a);if(!c)return;let l=c.text.toLowerCase(),p=e.toLowerCase().lastIndexOf(l),d=p>=0?p:Math.max(0,e.length-c.text.length),u=d+c.text.length,x=e.slice(d,u),f=e,h=u<e.length&&e[u]===" "?u+1:u,m={id:crypto.randomUUID(),placeholder:"",type:s.type,text:x,kind:c.kind,suggestionType:s.type,suggestionPlaceholder:s.text,options:s.options??[],metadata:c.metadata};this.store.set(g=>({text:f,completedParams:[...g.completedParams,m],suggestions:g.suggestions.filter(y=>y!==s),filterBase:h,newParamId:m.id,caretOffset:h,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(),c=r.toLowerCase().lastIndexOf(a),l=n+Math.max(0,c),p=l+o.text.length,d=e.text.slice(l,p),u=e.text,f=p<e.text.length&&e.text[p]===" "?p+1:p,b={id:crypto.randomUUID(),placeholder:"",type:t.suggestionType,text:d,kind:o.kind,suggestionType:t.suggestionType,suggestionPlaceholder:t.suggestionPlaceholder,options:t.options,metadata:o.metadata},h=e.completedParams.length,m=0;for(let y=0;y<e.completedParams.length;y++){let v=u.indexOf(e.completedParams[y].text,m);if(v!==-1){if(v>=f){h=y;break}m=v+e.completedParams[y].text.length}}let g=[...e.completedParams];g.splice(h,0,b),this.store.set(()=>({text:u,completedParams:g,newParamId:b.id,filterBase:f,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:f,activeDropdownIndex:-1})),this.scheduleSetCursor(f)}};0&&(module.exports={AIAutocomplete,createStore});
|
|
796
|
+
`;var Ve=0;function Xe(){return`:ac-${++Ve}:`}var Te=500;function Pe(){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 G=class{constructor(e,t={}){this.store=j(Pe());this._listboxId=Xe();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"&&(Se(),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({...Pe(),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=ge(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=ee(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)}))},Te))}startSelectionAnimationTimer(){this.selectionAnimationTimer&&clearTimeout(this.selectionAnimationTimer),this.selectionAnimationTimer=window.setTimeout(()=>{this.store.set({inSelectionAnimation:!1})},Te)}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");oe({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=te(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=ve(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&Y(this.domRefs,this.store.get(),t)}),Y(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=be(this.container,e),this.subscribeBatchedRender(()=>{this.dropdownRefs&&J(this.dropdownRefs,this.store.get(),e)}),J(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}=ne(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)}};0&&(module.exports={AIAutocomplete,createStore});
|
|
786
797
|
//# sourceMappingURL=index.js.map
|