@cloudflare/ai-search-snippet 0.0.27 → 0.0.29
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/dist/main.d.ts +4 -1
- package/dist/search-snippet.es.js +171 -144
- package/dist/search-snippet.es.js.map +1 -1
- package/dist/search-snippet.umd.js +42 -34
- package/dist/search-snippet.umd.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
(function(p,h){typeof exports=="object"&&typeof module<"u"?h(exports):typeof define=="function"&&define.amd?define(["exports"],h):(p=typeof globalThis<"u"?globalThis:p||self,h(p.SearchSnippet={}))})(this,(function(p){"use strict";var
|
|
1
|
+
(function(p,h){typeof exports=="object"&&typeof module<"u"?h(exports):typeof define=="function"&&define.amd?define(["exports"],h):(p=typeof globalThis<"u"?globalThis:p||self,h(p.SearchSnippet={}))})(this,(function(p){"use strict";var Z=Object.defineProperty;var Q=(p,h,w)=>h in p?Z(p,h,{enumerable:!0,configurable:!0,writable:!0,value:w}):p[h]=w;var a=(p,h,w)=>Q(p,typeof h!="symbol"?h+"":h,w);const h=["Searching...","Digging through results...","Scanning the knowledge base...","Finding the best matches...","Sifting through the data...","Almost there...","Looking far and wide...","Connecting the dots...","Rummaging through pages...","Hunting down answers..."];function L(c,i){let e;return function(...s){const r=()=>{clearTimeout(e),c(...s)};clearTimeout(e),e=setTimeout(r,i)}}function d(c){const i=document.createElement("div");return i.textContent=c,i.innerHTML}function I(c){return new DOMParser().parseFromString(c,"text/html").documentElement.textContent||""}function O(c){const i=new Date(c),t=new Date().getTime()-i.getTime();if(t<6e4)return"Just now";if(t<36e5){const s=Math.floor(t/6e4);return`${s} ${s===1?"minute":"minutes"} ago`}if(t<864e5){const s=Math.floor(t/36e5);return`${s} ${s===1?"hour":"hours"} ago`}return i.toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function z(c){return new Date(c).toLocaleDateString(void 0,{month:"short",day:"numeric"})}function T(c="id"){return`${c}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}function u(c,i){return c!==null?c:i}function m(c,i){return c===null?i:c==="true"||c===""}function x(c,i){if(c===null)return i;const e=Number.parseInt(c,10);return Number.isNaN(e)?i:e}function v(c,i){return new CustomEvent(c,{detail:i,bubbles:!0,composed:!0,cancelable:!0})}function k(c){if(!c)throw new Error("API URL is required");return new A(c)}class A{constructor(i){a(this,"activeRequests",new Map);a(this,"baseUrl");this.baseUrl=i.replace(/\/$/,"")}request(i={},e,t){const s=e==="search"?"snippet-search":"snippet-chat-completions";return fetch(`${this.baseUrl}/${e}`,{method:"POST",body:JSON.stringify({messages:[{role:"user",content:i.query}],stream:i.streaming,max_results:i.maxResults,...e==="search"&&{ai_search_options:{retrieval:{metadata_only:!0}}}}),headers:{"Content-Type":"application/json","cf-ai-search-source":s},signal:t})}async search(i,e={}){const t=this.generateRequestId(),s=new AbortController,r=e.signal||s.signal;this.registerRequest(t,s);try{const n=await this.request({query:i,streaming:!1,maxResults:e.maxResults||30},"search",r);if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);if(!n.body)throw new Error("Response body is empty");const o=await n.json();if(o.success&&o.result)return o.result.chunks.map(l=>({type:"result",id:l.id,title:I(l.item.metadata?.title),description:l.item.metadata?.description?I(l.item.metadata?.description):"",timestamp:l.item.timestamp??void 0,url:l.item.key,image:l.item.metadata?.image||void 0,metadata:l.item.metadata}));throw o.success===!1?new Error(o.error):new Error("Unknown error")}finally{this.unregisterRequest(t)}}async*searchStream(i,e){const t=this.generateRequestId(),s=new AbortController,r=e?.signal||s.signal;this.registerRequest(t,s);const n=await this.request({query:i,streaming:!0},"ai-search",r);if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);if(!n.body)throw new Error("Response body is empty");let o="";const l=n.body.getReader(),b=new TextDecoder;for(;;){const{done:g,value:M}=await l.read();if(g)break;const J=b.decode(M,{stream:!0});o+=J}yield{type:"result",id:"",title:"",description:o.replaceAll("data: ","").trim().split(`
|
|
2
2
|
|
|
3
|
-
`).map(
|
|
3
|
+
`).map(g=>JSON.parse(g)).map(g=>g.response).join(""),url:"",metadata:{}}}async*chat(i,e){const t=new AbortController,s=e?.signal||t.signal,r=await this.request({query:i,streaming:!1},"chat/completions",s);if(!r.ok)throw new Error(`HTTP error! status: ${r.status}`);if(!r.body)throw new Error("Response body is empty");yield{type:"text",message:(await r.json()).choices.map(o=>o.message.content).join("")}}cancelRequest(i){const e=this.activeRequests.get(i);e&&(e.controller.abort(),this.unregisterRequest(i))}cancelAllRequests(){for(const[i]of this.activeRequests)this.cancelRequest(i)}registerRequest(i,e){this.activeRequests.set(i,{id:i,controller:e,timestamp:Date.now()})}unregisterRequest(i){this.activeRequests.delete(i)}generateRequestId(){return`req-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}}const C=`Powered by <a href="https://workers.cloudflare.com/product/ai-search" target="_blank" rel="noopener noreferrer">Cloudflare AI Search <svg width="32" height="10" viewBox="0 0 412 186" xmlns="http://www.w3.org/2000/svg" aria-label="Cloudflare" role="img">
|
|
4
4
|
<path fill="#f38020" d="m280.8395,183.31456c11,-26 -4,-38 -19,-38l-148,-2c-4,0 -4,-6 1,-7l150,-2c17,-1 37,-15 43,-33c0,0 10,-21 9,-24a97,97 0 0 0 -187,-11c-38,-25 -78,9 -69,46c-48,3 -65,46 -60,72c0,1 1,2 3,2l274,0c1,0 3,-1 3,-3z"/>
|
|
5
5
|
<path fill="#faae40" d="m330.8395,81.31456c-4,0 -6,-1 -7,1l-5,21c-5,16 3,30 20,31l32,2c4,0 4,6 -1,7l-33,1c-36,4 -46,39 -46,39c0,2 0,3 2,3l113,0l3,-2a81,81 0 0 0 -78,-103"/>
|
|
6
6
|
</svg></a>`,$=`
|
|
@@ -320,7 +320,7 @@
|
|
|
320
320
|
.chat-message-bubble a:hover {
|
|
321
321
|
text-decoration: none;
|
|
322
322
|
}
|
|
323
|
-
`,
|
|
323
|
+
`,S=`
|
|
324
324
|
:host {
|
|
325
325
|
/* Colors - Light Mode */
|
|
326
326
|
--search-snippet-primary-color: #2563eb;
|
|
@@ -754,9 +754,9 @@
|
|
|
754
754
|
padding: var(--search-snippet-spacing-xs) 0;
|
|
755
755
|
text-align: center;
|
|
756
756
|
}
|
|
757
|
-
`;function
|
|
758
|
-
`),t=[];let s=!1,r="";for(let n=0;n<e.length;n++){const
|
|
759
|
-
`)}function
|
|
757
|
+
`;function j(c){let i=c;i=V(i),i=i.replace(/```([\s\S]*?)```/g,(n,o)=>`<pre><code>${o.trim()}</code></pre>`);const e=i.split(`
|
|
758
|
+
`),t=[];let s=!1,r="";for(let n=0;n<e.length;n++){const o=e[n],l=o.match(/^(#{1,6})\s+(.+)$/);if(l){const g=l[1].length,M=l[2];t.push(`<h${g}>${y(M)}</h${g}>`);continue}if(o.match(/^---+$/)){t.push("<hr />");continue}if(o.match(/^>\s+/)){const g=o.replace(/^>\s+/,"");t.push(`<blockquote>${y(g)}</blockquote>`);continue}const b=o.match(/^[-*]\s+(.+)$/);if(b){(!s||r!=="ul")&&(s&&t.push(`</${r}>`),t.push("<ul>"),s=!0,r="ul"),t.push(`<li>${y(b[1])}</li>`);continue}const f=o.match(/^\d+\.\s+(.+)$/);if(f){(!s||r!=="ol")&&(s&&t.push(`</${r}>`),t.push("<ol>"),s=!0,r="ol"),t.push(`<li>${y(f[1])}</li>`);continue}if(s&&(t.push(`</${r}>`),s=!1,r=""),o.trim()===""){t.push("<br />");continue}t.push(`<p>${y(o)}</p>`)}return s&&t.push(`</${r}>`),t.join(`
|
|
759
|
+
`)}function y(c){let i=c;return i=i.replace(/`([^`]+)`/g,"<code>$1</code>"),i=i.replace(/\*\*\*(.+?)\*\*\*/g,"<strong><em>$1</em></strong>"),i=i.replace(/___(.+?)___/g,"<strong><em>$1</em></strong>"),i=i.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),i=i.replace(/__(.+?)__/g,"<strong>$1</strong>"),i=i.replace(/\*(.+?)\*/g,"<em>$1</em>"),i=i.replace(/_(.+?)_/g,"<em>$1</em>"),i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'),i}function V(c){const i={"&":"&","<":"<",">":">",'"':""","'":"'"};return c.replace(/[&<>"']/g,e=>i[e]||e)}class B{constructor(i,e,t){a(this,"container");a(this,"client");a(this,"props");a(this,"inputElement",null);a(this,"messagesContainer",null);a(this,"sendButton",null);a(this,"messages",[]);a(this,"isStreaming",!1);a(this,"currentStreamingMessageId",null);a(this,"loadingMessageInterval",null);a(this,"loadingMessageIndex",0);a(this,"handleInputResize",null);a(this,"handleInputKeydown",null);a(this,"handleSendClick",null);this.container=i,this.client=e,this.props=t,this.render(),this.attachEventListeners()}render(){this.container.innerHTML=`
|
|
760
760
|
<div class="chat-container">
|
|
761
761
|
<div class="chat-messages">
|
|
762
762
|
<div class="chat-empty">
|
|
@@ -784,7 +784,7 @@
|
|
|
784
784
|
</div>
|
|
785
785
|
</div>
|
|
786
786
|
</div>
|
|
787
|
-
`,this.messagesContainer=this.container.querySelector(".chat-messages"),this.inputElement=this.container.querySelector(".chat-input"),this.sendButton=this.container.querySelector(".chat-send-button")}attachEventListeners(){!this.inputElement||!this.sendButton||(this.handleInputResize=i=>{const e=i.target;e.style.height="auto",e.style.height=`${e.scrollHeight}px`},this.inputElement.addEventListener("input",this.handleInputResize),this.handleInputKeydown=i=>{i.key==="Enter"&&!i.shiftKey&&(i.preventDefault(),this.handleSendMessage())},this.inputElement.addEventListener("keydown",this.handleInputKeydown),this.handleSendClick=()=>{this.handleSendMessage()},this.sendButton.addEventListener("click",this.handleSendClick))}async handleSendMessage(){if(!this.inputElement||this.isStreaming)return;const i=this.inputElement.value.trim();i.length!==0&&(this.inputElement.value="",this.inputElement.style.height="auto",await this.sendMessage(i))}async sendMessage(i){const e={id:T("msg"),role:"user",content:i,timestamp:Date.now()};this.addMessage(e),this.renderMessages(!0),this.setStreamingState(!0);const t=T("msg"),s={id:t,role:"assistant",content:"",timestamp:Date.now()};this.addMessage(s),this.currentStreamingMessageId=t,this.renderMessages(!0);try{const r=this.client.chat(i);let n="";for await(const l of r)if(l.type==="text"&&l.message)n+=l.message,this.updateStreamingMessage(t,n);else if(l.type==="error"){this.showErrorInMessage(t,l.message||"Unknown error");break}const
|
|
787
|
+
`,this.messagesContainer=this.container.querySelector(".chat-messages"),this.inputElement=this.container.querySelector(".chat-input"),this.sendButton=this.container.querySelector(".chat-send-button")}attachEventListeners(){!this.inputElement||!this.sendButton||(this.handleInputResize=i=>{const e=i.target;e.style.height="auto",e.style.height=`${e.scrollHeight}px`},this.inputElement.addEventListener("input",this.handleInputResize),this.handleInputKeydown=i=>{i.key==="Enter"&&!i.shiftKey&&(i.preventDefault(),this.handleSendMessage())},this.inputElement.addEventListener("keydown",this.handleInputKeydown),this.handleSendClick=()=>{this.handleSendMessage()},this.sendButton.addEventListener("click",this.handleSendClick))}async handleSendMessage(){if(!this.inputElement||this.isStreaming)return;const i=this.inputElement.value.trim();i.length!==0&&(this.inputElement.value="",this.inputElement.style.height="auto",await this.sendMessage(i))}async sendMessage(i){const e={id:T("msg"),role:"user",content:i,timestamp:Date.now()};this.addMessage(e),this.renderMessages(!0),this.setStreamingState(!0);const t=T("msg"),s={id:t,role:"assistant",content:"",timestamp:Date.now()};this.addMessage(s),this.currentStreamingMessageId=t,this.renderMessages(!0);try{const r=this.client.chat(i);let n="";for await(const l of r)if(l.type==="text"&&l.message)n+=l.message,this.updateStreamingMessage(t,n);else if(l.type==="error"){this.showErrorInMessage(t,l.message||"Unknown error");break}const o=this.messages.findIndex(l=>l.id===t);o!==-1&&(this.messages[o].content=n),this.container.dispatchEvent(v("message",{message:s}))}catch(r){this.showErrorInMessage(t,r.message),this.container.dispatchEvent(v("error",{error:{message:r.message,code:"CHAT_ERROR"}}))}finally{this.setStreamingState(!1),this.renderMessages(),this.currentStreamingMessageId=null}}addMessage(i){this.messages.push(i),this.renderMessages()}updateStreamingMessage(i,e){const t=this.messages.findIndex(s=>s.id===i);t!==-1&&(this.messages[t].content=e,this.renderMessages(!0))}showErrorInMessage(i,e){const t=this.messages.findIndex(s=>s.id===i);t!==-1&&(this.messages[t].content=`Error: ${e}`,this.renderMessages())}renderMessages(i=!1){if(!this.messagesContainer)return;if(this.messages.length===0){this.messagesContainer.innerHTML=`
|
|
788
788
|
<div class="chat-empty">
|
|
789
789
|
<svg class="chat-empty-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
790
790
|
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
|
|
@@ -799,15 +799,15 @@
|
|
|
799
799
|
<div class="chat-message-avatar">${s}</div>
|
|
800
800
|
<div class="chat-message-content">
|
|
801
801
|
<div class="chat-message-bubble">
|
|
802
|
-
${i.content?`<div class="chat-message-text">${
|
|
802
|
+
${i.content?`<div class="chat-message-text">${j(i.content)}</div>`:""}
|
|
803
803
|
${e?`<div class="chat-streaming"><span class="chat-streaming-dot"></span><span class="chat-streaming-dot"></span><span class="chat-streaming-dot"></span><span class="loading-text">${h[this.loadingMessageIndex]}</span></div>`:""}
|
|
804
804
|
</div>
|
|
805
805
|
<div class="chat-message-metadata">
|
|
806
|
-
<span class="chat-message-time">${
|
|
806
|
+
<span class="chat-message-time">${O(i.timestamp)}</span>
|
|
807
807
|
</div>
|
|
808
808
|
</div>
|
|
809
809
|
</div>
|
|
810
|
-
`}scrollToBottom(){this.messagesContainer&&requestAnimationFrame(()=>{this.messagesContainer&&(this.messagesContainer.scrollTop=this.messagesContainer.scrollHeight)})}setStreamingState(i){this.isStreaming=i,this.inputElement&&(this.inputElement.disabled=i),this.sendButton&&(this.sendButton.disabled=i,this.sendButton.innerHTML=i?'<div class="loading"></div>':"<span>Send</span>"),i?this.startLoadingMessages():this.clearLoadingMessages()}startLoadingMessages(){this.loadingMessageIndex=Math.floor(Math.random()*h.length),this.loadingMessageInterval=setInterval(()=>{this.loadingMessageIndex=(this.loadingMessageIndex+1)%h.length,this.isStreaming&&this.renderMessages(!0)},2500)}clearLoadingMessages(){this.loadingMessageInterval&&(clearInterval(this.loadingMessageInterval),this.loadingMessageInterval=null)}getMessages(){return[...this.messages]}clearMessages(){this.messages=[],this.renderMessages()}setMessages(i){this.messages=[...i],this.renderMessages()}destroy(){this.clearLoadingMessages(),this.isStreaming&&this.client.cancelAllRequests(),this.inputElement&&(this.handleInputResize&&this.inputElement.removeEventListener("input",this.handleInputResize),this.handleInputKeydown&&this.inputElement.removeEventListener("keydown",this.handleInputKeydown)),this.sendButton&&this.handleSendClick&&this.sendButton.removeEventListener("click",this.handleSendClick),this.handleInputResize=null,this.handleInputKeydown=null,this.handleSendClick=null}}const q="chat-bubble-snippet";class R extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"client",null);a(this,"chatView",null);a(this,"container",null);a(this,"isExpanded",!1);a(this,"isMinimized",!1);a(this,"handleBubbleClick",null);a(this,"handleCloseClick",null);a(this,"handleMinimizeClick",null);a(this,"handleClearClick",null);this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["api-url","placeholder","theme","hide-branding"]}connectedCallback(){this.render(),this.initializeClient(),this.dispatchEvent(v("ready",void 0))}disconnectedCallback(){this.cleanup()}attributeChangedCallback(e,t,s){t!==s&&(e==="api-url"?this.initializeClient():e==="theme"&&this.updateTheme(s))}getProps(){return{apiUrl:u(this.getAttribute("api-url"),"
|
|
810
|
+
`}scrollToBottom(){this.messagesContainer&&requestAnimationFrame(()=>{this.messagesContainer&&(this.messagesContainer.scrollTop=this.messagesContainer.scrollHeight)})}setStreamingState(i){this.isStreaming=i,this.inputElement&&(this.inputElement.disabled=i),this.sendButton&&(this.sendButton.disabled=i,this.sendButton.innerHTML=i?'<div class="loading"></div>':"<span>Send</span>"),i?this.startLoadingMessages():this.clearLoadingMessages()}startLoadingMessages(){this.loadingMessageIndex=Math.floor(Math.random()*h.length),this.loadingMessageInterval=setInterval(()=>{this.loadingMessageIndex=(this.loadingMessageIndex+1)%h.length,this.isStreaming&&this.renderMessages(!0)},2500)}clearLoadingMessages(){this.loadingMessageInterval&&(clearInterval(this.loadingMessageInterval),this.loadingMessageInterval=null)}getMessages(){return[...this.messages]}clearMessages(){this.messages=[],this.renderMessages()}setMessages(i){this.messages=[...i],this.renderMessages()}destroy(){this.clearLoadingMessages(),this.isStreaming&&this.client.cancelAllRequests(),this.inputElement&&(this.handleInputResize&&this.inputElement.removeEventListener("input",this.handleInputResize),this.handleInputKeydown&&this.inputElement.removeEventListener("keydown",this.handleInputKeydown)),this.sendButton&&this.handleSendClick&&this.sendButton.removeEventListener("click",this.handleSendClick),this.handleInputResize=null,this.handleInputKeydown=null,this.handleSendClick=null}}const q="chat-bubble-snippet";class R extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"client",null);a(this,"chatView",null);a(this,"container",null);a(this,"isExpanded",!1);a(this,"isMinimized",!1);a(this,"handleBubbleClick",null);a(this,"handleCloseClick",null);a(this,"handleMinimizeClick",null);a(this,"handleClearClick",null);this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["api-url","placeholder","theme","hide-branding"]}connectedCallback(){this.render(),this.initializeClient(),this.dispatchEvent(v("ready",void 0))}disconnectedCallback(){this.cleanup()}attributeChangedCallback(e,t,s){t!==s&&(e==="api-url"?this.initializeClient():e==="theme"&&this.updateTheme(s))}getProps(){return{apiUrl:u(this.getAttribute("api-url"),""),placeholder:u(this.getAttribute("placeholder"),"Type a message..."),theme:u(this.getAttribute("theme"),"auto"),hideBranding:m(this.getAttribute("hide-branding"),!1)}}initializeClient(){const e=this.getProps();if(!e.apiUrl){console.error("ChatBubbleSnippet: api-url attribute is required"),this.client=null;return}try{this.client=k(e.apiUrl)}catch(t){console.error("ChatBubbleSnippet:",t)}}render(){const e=document.createElement("style");e.textContent=`${S}
|
|
811
811
|
${$}
|
|
812
812
|
${this.getBubbleStyles()}`,this.container=document.createElement("div"),this.container.className="chat-bubble-widget",this.container.innerHTML=this.getBaseHTML(),this.shadow.innerHTML="",this.shadow.appendChild(e),this.shadow.appendChild(this.container),this.attachEventListeners()}getBubbleStyles(){return`
|
|
813
813
|
.chat-bubble-widget {
|
|
@@ -982,9 +982,13 @@ ${this.getBubbleStyles()}`,this.container=document.createElement("div"),this.con
|
|
|
982
982
|
</div>
|
|
983
983
|
</div>
|
|
984
984
|
<div class="chat-content"></div>
|
|
985
|
-
${this.getProps().hideBranding?"":`<div class="powered-by">${
|
|
985
|
+
${this.getProps().hideBranding?"":`<div class="powered-by">${C}</div>`}
|
|
986
986
|
</div>
|
|
987
|
-
`}attachEventListeners(){const e=this.shadow.querySelector(".bubble-button"),t=this.shadow.querySelector(".close-button"),s=this.shadow.querySelector(".minimize-button"),r=this.shadow.querySelector(".clear-button");this.handleBubbleClick=()=>this.toggleChat(),this.handleCloseClick=()=>this.closeChat(),this.handleMinimizeClick=()=>this.toggleMinimize(),this.handleClearClick=()=>this.clearChat(),e?.addEventListener("click",this.handleBubbleClick),t?.addEventListener("click",this.handleCloseClick),s?.addEventListener("click",this.handleMinimizeClick),r?.addEventListener("click",this.handleClearClick)}removeEventListeners(){const e=this.shadow.querySelector(".bubble-button"),t=this.shadow.querySelector(".close-button"),s=this.shadow.querySelector(".minimize-button"),r=this.shadow.querySelector(".clear-button");this.handleBubbleClick&&e?.removeEventListener("click",this.handleBubbleClick),this.handleCloseClick&&t?.removeEventListener("click",this.handleCloseClick),this.handleMinimizeClick&&s?.removeEventListener("click",this.handleMinimizeClick),this.handleClearClick&&r?.removeEventListener("click",this.handleClearClick),this.handleBubbleClick=null,this.handleCloseClick=null,this.handleMinimizeClick=null,this.handleClearClick=null}toggleChat(){this.isExpanded=!this.isExpanded;const e=this.shadow.querySelector(".bubble-button"),t=this.shadow.querySelector(".chat-window");this.isExpanded?(e?.classList.add("hidden"),t?.classList.add("expanded"),this.initializeChatView()):(e?.classList.remove("hidden"),t?.classList.remove("expanded"))}closeChat(){this.isExpanded=!1,this.isMinimized=!1;const e=this.shadow.querySelector(".bubble-button"),t=this.shadow.querySelector(".chat-window");e?.classList.remove("hidden"),t?.classList.remove("expanded","minimized")}toggleMinimize(){this.isMinimized=!this.isMinimized;const e=this.shadow.querySelector(".chat-window");this.isMinimized?e?.classList.add("minimized"):e?.classList.remove("minimized")}initializeChatView(){if(this.chatView
|
|
987
|
+
`}attachEventListeners(){const e=this.shadow.querySelector(".bubble-button"),t=this.shadow.querySelector(".close-button"),s=this.shadow.querySelector(".minimize-button"),r=this.shadow.querySelector(".clear-button");this.handleBubbleClick=()=>this.toggleChat(),this.handleCloseClick=()=>this.closeChat(),this.handleMinimizeClick=()=>this.toggleMinimize(),this.handleClearClick=()=>this.clearChat(),e?.addEventListener("click",this.handleBubbleClick),t?.addEventListener("click",this.handleCloseClick),s?.addEventListener("click",this.handleMinimizeClick),r?.addEventListener("click",this.handleClearClick)}removeEventListeners(){const e=this.shadow.querySelector(".bubble-button"),t=this.shadow.querySelector(".close-button"),s=this.shadow.querySelector(".minimize-button"),r=this.shadow.querySelector(".clear-button");this.handleBubbleClick&&e?.removeEventListener("click",this.handleBubbleClick),this.handleCloseClick&&t?.removeEventListener("click",this.handleCloseClick),this.handleMinimizeClick&&s?.removeEventListener("click",this.handleMinimizeClick),this.handleClearClick&&r?.removeEventListener("click",this.handleClearClick),this.handleBubbleClick=null,this.handleCloseClick=null,this.handleMinimizeClick=null,this.handleClearClick=null}toggleChat(){this.isExpanded=!this.isExpanded;const e=this.shadow.querySelector(".bubble-button"),t=this.shadow.querySelector(".chat-window");this.isExpanded?(e?.classList.add("hidden"),t?.classList.add("expanded"),this.initializeChatView()):(e?.classList.remove("hidden"),t?.classList.remove("expanded"))}closeChat(){this.isExpanded=!1,this.isMinimized=!1;const e=this.shadow.querySelector(".bubble-button"),t=this.shadow.querySelector(".chat-window");e?.classList.remove("hidden"),t?.classList.remove("expanded","minimized")}toggleMinimize(){this.isMinimized=!this.isMinimized;const e=this.shadow.querySelector(".chat-window");this.isMinimized?e?.classList.add("minimized"):e?.classList.remove("minimized")}initializeChatView(){if(this.chatView)return;const e=this.shadow.querySelector(".chat-content");if(!e)return;if(!this.client){e.innerHTML=`
|
|
988
|
+
<div style="padding: 16px; color: var(--search-snippet-error-color, #ef4444); font-family: var(--search-snippet-font-family, sans-serif); font-size: var(--search-snippet-font-size-base, 14px);">
|
|
989
|
+
<strong>Error:</strong> The <code>api-url</code> attribute is required. Please provide a valid API URL.
|
|
990
|
+
</div>
|
|
991
|
+
`;return}const t=this.getProps();this.chatView=new B(e,this.client,t)}updateTheme(e){(e==="light"||e==="dark"?e:null)===null&&this.hasAttribute("theme")&&this.getAttribute("theme")!=="auto"&&this.removeAttribute("theme")}cleanup(){this.removeEventListeners(),this.client&&this.client.cancelAllRequests(),this.chatView&&this.chatView.destroy()}clearChat(){this.chatView?.clearMessages()}async sendMessage(e){this.chatView&&await this.chatView.sendMessage(e)}getMessages(){return this.chatView?.getMessages()||[]}}customElements.get(q)||customElements.define(q,R);const H="chat-page-snippet",N="chat-page-sessions";class _ extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"client",null);a(this,"chatView",null);a(this,"container",null);a(this,"sessions",[]);a(this,"currentSessionId",null);a(this,"sidebarCollapsed",!1);a(this,"handleClearClick",null);a(this,"handleNewChatClick",null);a(this,"handleToggleSidebarClick",null);a(this,"handleChatListClick",null);a(this,"handleMessageEvent",null);this.shadow=this.attachShadow({mode:"open"}),this.loadSessions()}static get observedAttributes(){return["api-url","placeholder","theme","hide-branding"]}connectedCallback(){this.render(),this.initializeClient(),this.setupView(),this.dispatchEvent(v("ready",void 0))}disconnectedCallback(){this.saveCurrentSession(),this.cleanup()}attributeChangedCallback(e,t,s){t!==s&&(e==="api-url"?(this.initializeClient(),this.setupView()):e==="theme"&&this.updateTheme(s))}getProps(){return{apiUrl:u(this.getAttribute("api-url"),""),placeholder:u(this.getAttribute("placeholder"),"Type a message..."),theme:u(this.getAttribute("theme"),"auto"),hideBranding:m(this.getAttribute("hide-branding"),!1)}}initializeClient(){const e=this.getProps();if(!e.apiUrl){console.error("ChatPageSnippet: api-url attribute is required"),this.client=null;return}try{this.client=k(e.apiUrl)}catch(t){console.error("ChatPageSnippet:",t)}}render(){const e=document.createElement("style");e.textContent=`${S}
|
|
988
992
|
${$}
|
|
989
993
|
${this.getPageStyles()}`,this.container=document.createElement("div"),this.container.className="chat-page-container",this.container.innerHTML=this.getBaseHTML(),this.shadow.innerHTML="",this.shadow.appendChild(e),this.shadow.appendChild(this.container),this.attachEventListeners()}getPageStyles(){return`
|
|
990
994
|
:host {
|
|
@@ -1271,7 +1275,7 @@ ${this.getPageStyles()}`,this.container=document.createElement("div"),this.conta
|
|
|
1271
1275
|
New Chat
|
|
1272
1276
|
</button>
|
|
1273
1277
|
<div class="chat-list"></div>
|
|
1274
|
-
${this.getProps().hideBranding?"":`<div class="powered-by">${
|
|
1278
|
+
${this.getProps().hideBranding?"":`<div class="powered-by">${C}</div>`}
|
|
1275
1279
|
</div>
|
|
1276
1280
|
<div class="chat-main">
|
|
1277
1281
|
<div class="chat-page-header">
|
|
@@ -1301,7 +1305,11 @@ ${this.getPageStyles()}`,this.container=document.createElement("div"),this.conta
|
|
|
1301
1305
|
<div class="container"></div>
|
|
1302
1306
|
</div>
|
|
1303
1307
|
</div>
|
|
1304
|
-
`}attachEventListeners(){const e=this.shadow.querySelector(".clear-button"),t=this.shadow.querySelector(".new-chat-button"),s=this.shadow.querySelector(".toggle-sidebar-button"),r=this.shadow.querySelector(".chat-list");this.handleClearClick=()=>this.clearCurrentChat(),this.handleNewChatClick=()=>this.createNewChat(),this.handleToggleSidebarClick=()=>this.toggleSidebar(),this.handleChatListClick=n=>this.onChatListClick(n),e?.addEventListener("click",this.handleClearClick),t?.addEventListener("click",this.handleNewChatClick),s?.addEventListener("click",this.handleToggleSidebarClick),r?.addEventListener("click",this.handleChatListClick)}removeEventListeners(){const e=this.shadow.querySelector(".clear-button"),t=this.shadow.querySelector(".new-chat-button"),s=this.shadow.querySelector(".toggle-sidebar-button"),r=this.shadow.querySelector(".chat-list"),n=this.shadow.querySelector(".container");this.handleClearClick&&e?.removeEventListener("click",this.handleClearClick),this.handleNewChatClick&&t?.removeEventListener("click",this.handleNewChatClick),this.handleToggleSidebarClick&&s?.removeEventListener("click",this.handleToggleSidebarClick),this.handleChatListClick&&r?.removeEventListener("click",this.handleChatListClick),this.handleMessageEvent&&n&&n.removeEventListener("message",this.handleMessageEvent),this.handleClearClick=null,this.handleNewChatClick=null,this.handleToggleSidebarClick=null,this.handleChatListClick=null,this.handleMessageEvent=null}setupView(){
|
|
1308
|
+
`}attachEventListeners(){const e=this.shadow.querySelector(".clear-button"),t=this.shadow.querySelector(".new-chat-button"),s=this.shadow.querySelector(".toggle-sidebar-button"),r=this.shadow.querySelector(".chat-list");this.handleClearClick=()=>this.clearCurrentChat(),this.handleNewChatClick=()=>this.createNewChat(),this.handleToggleSidebarClick=()=>this.toggleSidebar(),this.handleChatListClick=n=>this.onChatListClick(n),e?.addEventListener("click",this.handleClearClick),t?.addEventListener("click",this.handleNewChatClick),s?.addEventListener("click",this.handleToggleSidebarClick),r?.addEventListener("click",this.handleChatListClick)}removeEventListeners(){const e=this.shadow.querySelector(".clear-button"),t=this.shadow.querySelector(".new-chat-button"),s=this.shadow.querySelector(".toggle-sidebar-button"),r=this.shadow.querySelector(".chat-list"),n=this.shadow.querySelector(".container");this.handleClearClick&&e?.removeEventListener("click",this.handleClearClick),this.handleNewChatClick&&t?.removeEventListener("click",this.handleNewChatClick),this.handleToggleSidebarClick&&s?.removeEventListener("click",this.handleToggleSidebarClick),this.handleChatListClick&&r?.removeEventListener("click",this.handleChatListClick),this.handleMessageEvent&&n&&n.removeEventListener("message",this.handleMessageEvent),this.handleClearClick=null,this.handleNewChatClick=null,this.handleToggleSidebarClick=null,this.handleChatListClick=null,this.handleMessageEvent=null}setupView(){const e=this.shadow.querySelector(".container");if(!this.client){e&&(e.innerHTML=`
|
|
1309
|
+
<div style="padding: 16px; color: var(--search-snippet-error-color, #ef4444); font-family: var(--search-snippet-font-family, sans-serif); font-size: var(--search-snippet-font-size-base, 14px);">
|
|
1310
|
+
<strong>Error:</strong> The <code>api-url</code> attribute is required. Please provide a valid API URL.
|
|
1311
|
+
</div>
|
|
1312
|
+
`);return}if(!e)return;const t=this.getProps();if(this.chatView=new B(e,this.client,t),this.sessions.length===0)this.createNewChat();else{const s=this.sessions[0];this.switchToSession(s.id)}this.handleMessageEvent=()=>{this.saveCurrentSession(),this.updateSessionTitle(),this.renderChatList()},e.addEventListener("message",this.handleMessageEvent),this.renderChatList()}generateSessionId(){return`session_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}loadSessions(){try{const e=localStorage.getItem(N);e&&(this.sessions=JSON.parse(e),this.sessions.sort((t,s)=>s.updatedAt-t.updatedAt))}catch(e){console.error("Failed to load chat sessions:",e)}}saveSessions(){try{localStorage.setItem(N,JSON.stringify(this.sessions))}catch(e){console.error("Failed to save chat sessions:",e)}}saveCurrentSession(){if(!this.currentSessionId||!this.chatView)return;const e=this.sessions.findIndex(t=>t.id===this.currentSessionId);e!==-1&&(this.sessions[e].messages=this.chatView.getMessages(),this.sessions[e].updatedAt=Date.now(),this.saveSessions())}updateSessionTitle(){if(!this.currentSessionId)return;const e=this.sessions.find(t=>t.id===this.currentSessionId);if(e&&e.messages.length>0&&e.title==="New Chat"){const t=e.messages.find(s=>s.role==="user");t&&(e.title=t.content.slice(0,50)+(t.content.length>50?"...":""),this.saveSessions())}}createNewChat(){this.saveCurrentSession();const e={id:this.generateSessionId(),title:"New Chat",messages:[],createdAt:Date.now(),updatedAt:Date.now()};this.sessions.unshift(e),this.currentSessionId=e.id,this.saveSessions(),this.chatView?.clearMessages(),this.renderChatList()}switchToSession(e){if(e===this.currentSessionId)return;this.saveCurrentSession();const t=this.sessions.find(s=>s.id===e);t&&this.chatView&&(this.currentSessionId=e,this.chatView.setMessages(t.messages),this.renderChatList())}deleteSession(e){const t=this.sessions.findIndex(s=>s.id===e);t!==-1&&(this.sessions.splice(t,1),this.saveSessions(),e===this.currentSessionId&&(this.sessions.length>0?this.switchToSession(this.sessions[0].id):this.createNewChat()),this.renderChatList())}clearCurrentChat(){if(!this.currentSessionId)return;const e=this.sessions.find(t=>t.id===this.currentSessionId);e&&(e.messages=[],e.title="New Chat",e.updatedAt=Date.now(),this.saveSessions()),this.chatView?.clearMessages(),this.renderChatList()}toggleSidebar(){this.sidebarCollapsed=!this.sidebarCollapsed,this.shadow.querySelector(".chat-sidebar")?.classList.toggle("collapsed",this.sidebarCollapsed)}onChatListClick(e){const t=e.target,s=t.closest(".chat-list-item-delete");if(s){e.stopPropagation();const n=s.getAttribute("data-session-id");n&&this.deleteSession(n);return}const r=t.closest(".chat-list-item");if(r){const n=r.getAttribute("data-session-id");n&&this.switchToSession(n)}}renderChatList(){const e=this.shadow.querySelector(".chat-list");if(e){if(this.sessions.length===0){e.innerHTML='<div class="chat-list-empty">No chats yet</div>';return}e.innerHTML=this.sessions.map(t=>this.renderChatListItem(t)).join("")}}renderChatListItem(e){const t=e.id===this.currentSessionId,s=this.formatDate(e.updatedAt);return`
|
|
1305
1313
|
<div class="chat-list-item ${t?"active":""}" data-session-id="${e.id}">
|
|
1306
1314
|
<div class="chat-list-item-content">
|
|
1307
1315
|
<div class="chat-list-item-title">${this.escapeHTML(e.title)}</div>
|
|
@@ -1313,7 +1321,7 @@ ${this.getPageStyles()}`,this.container=document.createElement("div"),this.conta
|
|
|
1313
1321
|
</svg>
|
|
1314
1322
|
</button>
|
|
1315
1323
|
</div>
|
|
1316
|
-
`}formatDate(e){const t=new Date(e),r=new Date().getTime()-t.getTime(),n=Math.floor(r/(1e3*60*60*24));return n===0?t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):n===1?"Yesterday":n<7?t.toLocaleDateString(void 0,{weekday:"long"}):t.toLocaleDateString(void 0,{month:"short",day:"numeric"})}escapeHTML(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}updateTheme(e){(e==="light"||e==="dark"?e:null)===null&&this.hasAttribute("theme")&&this.getAttribute("theme")!=="auto"&&this.removeAttribute("theme")}cleanup(){this.removeEventListeners(),this.client&&this.client.cancelAllRequests(),this.chatView&&this.chatView.destroy()}clearChat(){this.clearCurrentChat()}async sendMessage(e){this.chatView&&(await this.chatView.sendMessage(e),this.saveCurrentSession())}getMessages(){return this.chatView?.getMessages()||[]}getSessions(){return[...this.sessions]}getCurrentSession(){return this.sessions.find(e=>e.id===this.currentSessionId)||null}}customElements.get(H)||customElements.define(H,_);const
|
|
1324
|
+
`}formatDate(e){const t=new Date(e),r=new Date().getTime()-t.getTime(),n=Math.floor(r/(1e3*60*60*24));return n===0?t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):n===1?"Yesterday":n<7?t.toLocaleDateString(void 0,{weekday:"long"}):t.toLocaleDateString(void 0,{month:"short",day:"numeric"})}escapeHTML(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}updateTheme(e){(e==="light"||e==="dark"?e:null)===null&&this.hasAttribute("theme")&&this.getAttribute("theme")!=="auto"&&this.removeAttribute("theme")}cleanup(){this.removeEventListeners(),this.client&&this.client.cancelAllRequests(),this.chatView&&this.chatView.destroy()}clearChat(){this.clearCurrentChat()}async sendMessage(e){this.chatView&&(await this.chatView.sendMessage(e),this.saveCurrentSession())}getMessages(){return this.chatView?.getMessages()||[]}getSessions(){return[...this.sessions]}getCurrentSession(){return this.sessions.find(e=>e.id===this.currentSessionId)||null}}customElements.get(H)||customElements.define(H,_);const K=`
|
|
1317
1325
|
/* Search view states */
|
|
1318
1326
|
.search-view {
|
|
1319
1327
|
transition: var(--search-snippet-transition-slow);
|
|
@@ -1683,8 +1691,8 @@ a.search-result-item:focus-visible {
|
|
|
1683
1691
|
border-radius: 2px;
|
|
1684
1692
|
font-weight: var(--search-snippet-font-weight-medium);
|
|
1685
1693
|
}
|
|
1686
|
-
`,
|
|
1687
|
-
${
|
|
1694
|
+
`,P="search-bar-snippet",G=10,F=100;class E extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"client",null);a(this,"container",null);a(this,"inputElement",null);a(this,"resultsContainer",null);a(this,"searchButton",null);a(this,"debouncedSearch",null);a(this,"currentSearchController",null);a(this,"loadingMessageInterval",null);a(this,"loadingMessageIndex",0);a(this,"handleInputChange",null);a(this,"handleInputKeydownEnter",null);a(this,"handleInputKeydownEscape",null);a(this,"handleSearchButtonClick",null);this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["api-url","placeholder","max-results","debounce-ms","theme","hide-branding","show-url","show-date","hide-thumbnails","see-more"]}connectedCallback(){this.initializeClient(),this.render(),this.dispatchEvent(v("ready",void 0))}disconnectedCallback(){this.cleanup()}attributeChangedCallback(e,t,s){t!==s&&(e==="api-url"?this.initializeClient():e==="theme"&&this.updateTheme(s))}getProps(){return{apiUrl:u(this.getAttribute("api-url"),""),placeholder:u(this.getAttribute("placeholder"),"Search..."),maxResults:x(this.getAttribute("max-results"),10),debounceMs:x(this.getAttribute("debounce-ms"),300),theme:u(this.getAttribute("theme"),"auto"),hideBranding:m(this.getAttribute("hide-branding"),!1),showUrl:m(this.getAttribute("show-url"),!1),showDate:m(this.getAttribute("show-date"),!1),hideThumbnails:m(this.getAttribute("hide-thumbnails"),!1),seeMore:u(this.getAttribute("see-more"),"")}}initializeClient(){const e=this.getProps();if(!e.apiUrl){console.error("SearchBarSnippet: api-url attribute is required"),this.client=null,this.showMissingApiUrlError();return}try{this.client=k(e.apiUrl)}catch(t){console.error("SearchBarSnippet:",t)}}render(){const e=this.getProps(),t=r=>this.performSearch(r);this.debouncedSearch=L(t,e.debounceMs||400);const s=document.createElement("style");s.textContent=`${S}
|
|
1695
|
+
${K}`,this.container=document.createElement("div"),this.container.className="container",this.container.innerHTML=`
|
|
1688
1696
|
<div class="search-view">
|
|
1689
1697
|
<div class="search-input-wrapper">
|
|
1690
1698
|
<svg xmlns="http://www.w3.org/2000/svg" class="search-icon" height="24px" viewBox="0 -960 960 960" width="24px" fill="currentColor"><path d="M784-120 532-372q-30 24-69 38t-83 14q-109 0-184.5-75.5T120-580q0-109 75.5-184.5T380-840q109 0 184.5 75.5T640-580q0 44-14 83t-38 69l252 252-56 56ZM380-400q75 0 127.5-52.5T560-580q0-75-52.5-127.5T380-760q-75 0-127.5 52.5T200-580q0 75 52.5 127.5T380-400Z"/></svg>
|
|
@@ -1706,23 +1714,23 @@ ${U}`,this.container=document.createElement("div"),this.container.className="con
|
|
|
1706
1714
|
</div>
|
|
1707
1715
|
</div>
|
|
1708
1716
|
</div>
|
|
1709
|
-
`,this.shadow.innerHTML="",this.shadow.appendChild(s),this.shadow.appendChild(this.container),this.inputElement=this.container.querySelector(".search-input"),this.resultsContainer=this.container.querySelector(".search-results-wrapper"),this.searchButton=this.container.querySelector(".search-submit-button"),this.attachEventListeners()}attachEventListeners(){this.inputElement&&(this.handleInputChange=e=>{const s=e.target.value.trim();s.length>0&&this.debouncedSearch?this.debouncedSearch(s):this.showEmptyState()},this.inputElement.addEventListener("input",this.handleInputChange),this.handleInputKeydownEnter=e=>{if(e.key==="Enter"){const t=e.target.value.trim();t.length>0&&this.performSearch(t)}},this.inputElement.addEventListener("keydown",this.handleInputKeydownEnter),this.handleInputKeydownEscape=e=>{e.key==="Escape"&&this.inputElement&&(this.inputElement.value="")},window.addEventListener("keydown",this.handleInputKeydownEscape),this.searchButton&&(this.handleSearchButtonClick=()=>{const e=this.inputElement?.value.trim()||"";e.length>0&&this.performSearch(e)},this.searchButton.addEventListener("click",this.handleSearchButtonClick)))}async performSearch(e){if(this.client){this.currentSearchController&&(this.currentSearchController.abort(),this.currentSearchController=null),this.currentSearchController=new AbortController,this.showLoadingState();try{const t=await this.client.search(e,{streaming:!1,signal:this.currentSearchController.signal});this.displayResults(
|
|
1710
|
-
<a href="${d(
|
|
1717
|
+
`,this.shadow.innerHTML="",this.shadow.appendChild(s),this.shadow.appendChild(this.container),this.inputElement=this.container.querySelector(".search-input"),this.resultsContainer=this.container.querySelector(".search-results-wrapper"),this.searchButton=this.container.querySelector(".search-submit-button"),this.attachEventListeners(),this.client||this.showMissingApiUrlError()}attachEventListeners(){this.inputElement&&(this.handleInputChange=e=>{const s=e.target.value.trim();s.length>0&&this.debouncedSearch?this.debouncedSearch(s):this.showEmptyState()},this.inputElement.addEventListener("input",this.handleInputChange),this.handleInputKeydownEnter=e=>{if(e.key==="Enter"){const t=e.target.value.trim();t.length>0&&this.performSearch(t)}},this.inputElement.addEventListener("keydown",this.handleInputKeydownEnter),this.handleInputKeydownEscape=e=>{e.key==="Escape"&&this.inputElement&&(this.inputElement.value="")},window.addEventListener("keydown",this.handleInputKeydownEscape),this.searchButton&&(this.handleSearchButtonClick=()=>{const e=this.inputElement?.value.trim()||"";e.length>0&&this.performSearch(e)},this.searchButton.addEventListener("click",this.handleSearchButtonClick)))}async performSearch(e){if(!this.client){this.showMissingApiUrlError();return}this.currentSearchController&&(this.currentSearchController.abort(),this.currentSearchController=null),this.currentSearchController=new AbortController,this.showLoadingState();try{const t=await this.client.search(e,{streaming:!1,signal:this.currentSearchController.signal,maxResults:F}),s=this.getProps(),r=t.slice(0,s.maxResults||G);this.displayResults(r,e,t.length)}catch(t){if(t.name==="AbortError")return;this.showErrorState(t.message)}finally{this.currentSearchController=null}}displayResults(e,t,s=e.length){if(this.clearLoadingInterval(),!this.resultsContainer)return;if(e.length===0){this.showNoResultsState(t);return}const r=this.getProps(),n=r.hideBranding?"":`<div class="powered-by-inline">${C}</div>`,o=s>e.length,l=o?`Showing ${e.length} of ${s} results`:`Found ${s} result${s===1?"":"s"}`,b=r.seeMore&&o?`<div class="search-footer">
|
|
1718
|
+
<a href="${d(r.seeMore+encodeURIComponent(t))}" class="search-see-more">
|
|
1711
1719
|
<span>See more results</span>
|
|
1712
1720
|
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>
|
|
1713
1721
|
</a>
|
|
1714
|
-
</div>`:"",
|
|
1722
|
+
</div>`:"",f=`
|
|
1715
1723
|
<div class="search-header">
|
|
1716
1724
|
<div class="search-count">
|
|
1717
|
-
|
|
1725
|
+
${l}
|
|
1718
1726
|
</div>
|
|
1719
|
-
${
|
|
1727
|
+
${n}
|
|
1720
1728
|
</div>
|
|
1721
1729
|
<div class="search-results">
|
|
1722
|
-
${e.map(
|
|
1730
|
+
${e.map(g=>this.renderResult(g)).join("")}
|
|
1723
1731
|
</div>
|
|
1724
|
-
${
|
|
1725
|
-
`;this.resultsContainer.innerHTML=
|
|
1732
|
+
${b}
|
|
1733
|
+
`;this.resultsContainer.innerHTML=f,this.attachResultHandlers()}renderResult(e){const t=this.getProps(),s=t.hideThumbnails?"":this.renderResultImage(e.image,e.title),r=e.url?d(e.url):"#",n=t.showDate&&e.timestamp!==void 0?`<div class="search-result-date">${d(z(e.timestamp))}</div>`:"",o=t.showUrl&&e.url||n?`<div class="search-result-metadata">
|
|
1726
1734
|
${t.showUrl&&e.url?`<span class="search-result-url">${d(e.url)}</span>`:'<span class="search-result-url search-result-url-empty"></span>'}
|
|
1727
1735
|
${n}
|
|
1728
1736
|
</div>`:"";return`
|
|
@@ -1731,7 +1739,7 @@ ${U}`,this.container=document.createElement("div"),this.container.className="con
|
|
|
1731
1739
|
<div class="search-result-content">
|
|
1732
1740
|
<div class="search-result-title">${d(e.title||"")}</div>
|
|
1733
1741
|
<div class="search-result-snippet">${d(e.description||"")}</div>
|
|
1734
|
-
${
|
|
1742
|
+
${o}
|
|
1735
1743
|
</div>
|
|
1736
1744
|
</a>
|
|
1737
1745
|
`}renderResultImage(e,t){const s='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/></svg>';return e?`
|
|
@@ -1780,7 +1788,7 @@ ${U}`,this.container=document.createElement("div"),this.container.className="con
|
|
|
1780
1788
|
<div class="error">
|
|
1781
1789
|
<strong>Error:</strong> ${d(e)}
|
|
1782
1790
|
</div>
|
|
1783
|
-
`)}updateTheme(e){const t=e==="light"||e==="dark"||e==="auto"?e:"auto";t==="auto"?this.removeAttribute("theme"):this.setAttribute("theme",t)}cleanup(){this.clearLoadingInterval(),this.currentSearchController&&(this.currentSearchController.abort(),this.currentSearchController=null),this.client&&this.client.cancelAllRequests(),this.inputElement&&(this.handleInputChange&&this.inputElement.removeEventListener("input",this.handleInputChange),this.handleInputKeydownEnter&&this.inputElement.removeEventListener("keydown",this.handleInputKeydownEnter),this.handleInputKeydownEscape&&window.removeEventListener("keydown",this.handleInputKeydownEscape)),this.searchButton&&this.handleSearchButtonClick&&this.searchButton.removeEventListener("click",this.handleSearchButtonClick),this.handleInputChange=null,this.handleInputKeydownEnter=null,this.handleInputKeydownEscape=null,this.handleSearchButtonClick=null}async search(e){await this.performSearch(e)}}customElements.get(
|
|
1791
|
+
`)}showMissingApiUrlError(){this.resultsContainer&&this.showErrorState("The api-url attribute is required. Please provide a valid API URL.")}updateTheme(e){const t=e==="light"||e==="dark"||e==="auto"?e:"auto";t==="auto"?this.removeAttribute("theme"):this.setAttribute("theme",t)}cleanup(){this.clearLoadingInterval(),this.currentSearchController&&(this.currentSearchController.abort(),this.currentSearchController=null),this.client&&this.client.cancelAllRequests(),this.inputElement&&(this.handleInputChange&&this.inputElement.removeEventListener("input",this.handleInputChange),this.handleInputKeydownEnter&&this.inputElement.removeEventListener("keydown",this.handleInputKeydownEnter),this.handleInputKeydownEscape&&window.removeEventListener("keydown",this.handleInputKeydownEscape)),this.searchButton&&this.handleSearchButtonClick&&this.searchButton.removeEventListener("click",this.handleSearchButtonClick),this.handleInputChange=null,this.handleInputKeydownEnter=null,this.handleInputKeydownEscape=null,this.handleSearchButtonClick=null}async search(e){await this.performSearch(e)}}customElements.get(P)||customElements.define(P,E);const Y=`
|
|
1784
1792
|
/* Modal backdrop */
|
|
1785
1793
|
.modal-backdrop {
|
|
1786
1794
|
position: fixed;
|
|
@@ -2217,8 +2225,8 @@ a.modal-result-item:focus-visible {
|
|
|
2217
2225
|
.modal-container.open {
|
|
2218
2226
|
animation: modal-slide-in var(--search-snippet-transition) ease-out;
|
|
2219
2227
|
}
|
|
2220
|
-
`,
|
|
2221
|
-
${
|
|
2228
|
+
`,D="search-modal-snippet",W=10,X=100;class U extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"client",null);a(this,"backdrop",null);a(this,"modal",null);a(this,"inputElement",null);a(this,"resultsContainer",null);a(this,"footerCount",null);a(this,"isOpen",!1);a(this,"results",[]);a(this,"activeIndex",-1);a(this,"debouncedSearch",null);a(this,"currentSearchController",null);a(this,"loadingMessageInterval",null);a(this,"loadingMessageIndex",0);a(this,"handleGlobalKeydown",null);a(this,"handleInputChange",null);a(this,"handleInputKeydown",null);a(this,"handleBackdropClick",null);a(this,"savedBodyStyles",null);a(this,"savedHtmlOverflow",null);this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["api-url","placeholder","max-results","theme","shortcut","use-meta-key","debounce-ms","hide-branding","show-url","show-date","hide-thumbnails","see-more"]}connectedCallback(){this.initializeClient(),this.render(),this.attachGlobalKeyboardShortcut(),this.dispatchEvent(v("ready",void 0))}disconnectedCallback(){this.cleanup()}attributeChangedCallback(e,t,s){t!==s&&(e==="api-url"?this.initializeClient():e==="theme"&&this.updateTheme(s))}getProps(){return{apiUrl:u(this.getAttribute("api-url"),""),placeholder:u(this.getAttribute("placeholder"),"Search..."),maxResults:x(this.getAttribute("max-results"),10),debounceMs:x(this.getAttribute("debounce-ms"),300),theme:u(this.getAttribute("theme"),"auto"),shortcut:u(this.getAttribute("shortcut"),"k"),useMetaKey:this.getAttribute("use-meta-key")!=="false",hideBranding:m(this.getAttribute("hide-branding"),!1),showUrl:m(this.getAttribute("show-url"),!1),showDate:m(this.getAttribute("show-date"),!1),hideThumbnails:m(this.getAttribute("hide-thumbnails"),!1),seeMore:u(this.getAttribute("see-more"),"")}}initializeClient(){const e=this.getProps();if(!e.apiUrl){console.error("SearchModalSnippet: api-url attribute is required"),this.client=null,this.showMissingApiUrlError();return}try{this.client=k(e.apiUrl)}catch(t){console.error("SearchModalSnippet:",t)}}render(){const e=this.getProps(),t=o=>this.performSearch(o);this.debouncedSearch=L(t,e.debounceMs||300);const s=document.createElement("style");s.textContent=`${S}
|
|
2229
|
+
${Y}`;const r=e.hideBranding?"":`<div class="powered-by-inline">${C}</div>`,n=document.createElement("div");n.innerHTML=`
|
|
2222
2230
|
<div class="modal-backdrop" role="presentation"></div>
|
|
2223
2231
|
<div class="modal-container" role="dialog" aria-modal="true" aria-labelledby="modal-title">
|
|
2224
2232
|
<div class="modal-header">
|
|
@@ -2261,12 +2269,12 @@ ${G}`;const r=e.hideBranding?"":`<div class="powered-by-inline">${x}</div>`,n=do
|
|
|
2261
2269
|
${r}
|
|
2262
2270
|
</div>
|
|
2263
2271
|
</div>
|
|
2264
|
-
`,this.shadow.innerHTML="",this.shadow.appendChild(s),this.shadow.appendChild(n),this.backdrop=this.shadow.querySelector(".modal-backdrop"),this.modal=this.shadow.querySelector(".modal-container"),this.inputElement=this.shadow.querySelector(".modal-search-input"),this.resultsContainer=this.shadow.querySelector(".modal-results"),this.footerCount=this.shadow.querySelector(".modal-results-count"),this.attachEventListeners()}attachGlobalKeyboardShortcut(){const e=this.getProps(),t=e.shortcut?.toLowerCase()||"k";this.handleGlobalKeydown=s=>{(e.useMetaKey&&s.metaKey||s.ctrlKey)&&s.key.toLowerCase()===t&&!this.isOpen&&(s.preventDefault(),this.open())},document.addEventListener("keydown",this.handleGlobalKeydown)}attachEventListeners(){!this.inputElement||!this.backdrop||(this.handleInputChange=e=>{const s=e.target.value.trim();s.length>0&&this.debouncedSearch?this.debouncedSearch(s):(this.results=[],this.activeIndex=-1,this.showEmptyState())},this.inputElement.addEventListener("input",this.handleInputChange),this.handleInputKeydown=e=>{switch(e.key){case"ArrowDown":e.preventDefault(),this.navigateResults(1);break;case"ArrowUp":e.preventDefault(),this.navigateResults(-1);break;case"Enter":e.preventDefault(),this.selectActiveResult();break;case"Escape":e.preventDefault(),this.close();break}},this.inputElement.addEventListener("keydown",this.handleInputKeydown),this.handleBackdropClick=e=>{e.target===this.backdrop&&this.close()},this.backdrop.addEventListener("click",this.handleBackdropClick))}navigateResults(e){if(this.results.length===0)return;const t=this.activeIndex+e;t<0?this.activeIndex=this.results.length-1:t>=this.results.length?this.activeIndex=0:this.activeIndex=t,this.updateActiveResult()}updateActiveResult(){const e=this.resultsContainer?.querySelectorAll(".modal-result-item");e&&(e.forEach((t,s)=>{s===this.activeIndex?(t.classList.add("active"),t.setAttribute("aria-selected","true"),t.scrollIntoView({block:"nearest"})):(t.classList.remove("active"),t.setAttribute("aria-selected","false"))}),this.inputElement&&this.activeIndex>=0?this.inputElement.setAttribute("aria-activedescendant",`result-${this.activeIndex}`):this.inputElement&&this.inputElement.removeAttribute("aria-activedescendant"))}selectActiveResult(){if(this.activeIndex<0||this.activeIndex>=this.results.length){const s=this.inputElement?.value.trim();s&&s.length>0&&this.performSearch(s);return}const e=this.results[this.activeIndex];this.dispatchEvent(v("result-select",{result:e,index:this.activeIndex}));const t=this.resultsContainer?.querySelector(`.modal-result-item[data-index="${this.activeIndex}"]`);t&&e.url&&t.click(),this.close()}async performSearch(e){if(this.client){this.currentSearchController&&(this.currentSearchController.abort(),this.currentSearchController=null),this.currentSearchController=new AbortController,this.showLoadingState();try{const t=await this.client.search(e,{streaming:!1,signal:this.currentSearchController.signal}),s=this.getProps();this.results=t.slice(0,s.maxResults||
|
|
2272
|
+
`,this.shadow.innerHTML="",this.shadow.appendChild(s),this.shadow.appendChild(n),this.backdrop=this.shadow.querySelector(".modal-backdrop"),this.modal=this.shadow.querySelector(".modal-container"),this.inputElement=this.shadow.querySelector(".modal-search-input"),this.resultsContainer=this.shadow.querySelector(".modal-results"),this.footerCount=this.shadow.querySelector(".modal-results-count"),this.attachEventListeners(),this.client||this.showMissingApiUrlError()}attachGlobalKeyboardShortcut(){const e=this.getProps(),t=e.shortcut?.toLowerCase()||"k";this.handleGlobalKeydown=s=>{(e.useMetaKey&&s.metaKey||s.ctrlKey)&&s.key.toLowerCase()===t&&!this.isOpen&&(s.preventDefault(),this.open())},document.addEventListener("keydown",this.handleGlobalKeydown)}attachEventListeners(){!this.inputElement||!this.backdrop||(this.handleInputChange=e=>{const s=e.target.value.trim();s.length>0&&this.debouncedSearch?this.debouncedSearch(s):(this.results=[],this.activeIndex=-1,this.showEmptyState())},this.inputElement.addEventListener("input",this.handleInputChange),this.handleInputKeydown=e=>{switch(e.key){case"ArrowDown":e.preventDefault(),this.navigateResults(1);break;case"ArrowUp":e.preventDefault(),this.navigateResults(-1);break;case"Enter":e.preventDefault(),this.selectActiveResult();break;case"Escape":e.preventDefault(),this.close();break}},this.inputElement.addEventListener("keydown",this.handleInputKeydown),this.handleBackdropClick=e=>{e.target===this.backdrop&&this.close()},this.backdrop.addEventListener("click",this.handleBackdropClick))}navigateResults(e){if(this.results.length===0)return;const t=this.activeIndex+e;t<0?this.activeIndex=this.results.length-1:t>=this.results.length?this.activeIndex=0:this.activeIndex=t,this.updateActiveResult()}updateActiveResult(){const e=this.resultsContainer?.querySelectorAll(".modal-result-item");e&&(e.forEach((t,s)=>{s===this.activeIndex?(t.classList.add("active"),t.setAttribute("aria-selected","true"),t.scrollIntoView({block:"nearest"})):(t.classList.remove("active"),t.setAttribute("aria-selected","false"))}),this.inputElement&&this.activeIndex>=0?this.inputElement.setAttribute("aria-activedescendant",`result-${this.activeIndex}`):this.inputElement&&this.inputElement.removeAttribute("aria-activedescendant"))}selectActiveResult(){if(this.activeIndex<0||this.activeIndex>=this.results.length){const s=this.inputElement?.value.trim();s&&s.length>0&&this.performSearch(s);return}const e=this.results[this.activeIndex];this.dispatchEvent(v("result-select",{result:e,index:this.activeIndex}));const t=this.resultsContainer?.querySelector(`.modal-result-item[data-index="${this.activeIndex}"]`);t&&e.url&&t.click(),this.close()}async performSearch(e){if(!this.client){this.showMissingApiUrlError();return}this.currentSearchController&&(this.currentSearchController.abort(),this.currentSearchController=null),this.currentSearchController=new AbortController,this.showLoadingState();try{const t=await this.client.search(e,{streaming:!1,signal:this.currentSearchController.signal,maxResults:X}),s=this.getProps();this.results=t.slice(0,s.maxResults||W),this.activeIndex=this.results.length>0?0:-1,this.displayResults(this.results,e,t.length)}catch(t){if(t.name==="AbortError")return;this.showErrorState(t.message)}finally{this.currentSearchController=null}}displayResults(e,t,s=e.length){if(console.log({results:e,query:t,totalResults:s}),this.clearLoadingInterval(),!this.resultsContainer)return;if(e.length===0){this.showNoResultsState(t);return}const r=this.getProps(),n=e.map((f,g)=>this.renderResult(f,g)).join(""),o=s>e.length,l=o?`Showing ${e.length} of ${s} results`:`${s} result${s===1?"":"s"}`,b=r.seeMore&&o?`<a href="${d(r.seeMore+encodeURIComponent(t))}" class="modal-see-more">
|
|
2265
2273
|
<span>See more results</span>
|
|
2266
2274
|
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>
|
|
2267
|
-
</a>`:"";this.resultsContainer.innerHTML=
|
|
2275
|
+
</a>`:"";this.resultsContainer.innerHTML=n+b,this.footerCount&&(this.footerCount.textContent=l),this.inputElement&&this.inputElement.setAttribute("aria-expanded","true"),this.attachResultHandlers(),this.updateActiveResult()}renderResult(e,t){const s=this.getProps(),r=s.hideThumbnails?"":this.renderResultImage(e.image,e.title),n=e.url?d(e.url):"#",o=s.showDate&&e.timestamp!==void 0?`<div class="modal-result-date">${d(z(e.timestamp))}</div>`:"",l=s.showUrl&&e.url||o?`<div class="modal-result-metadata">
|
|
2268
2276
|
${s.showUrl&&e.url?`<span class="modal-result-url">${d(e.url)}</span>`:'<span class="modal-result-url modal-result-url-empty"></span>'}
|
|
2269
|
-
${
|
|
2277
|
+
${o}
|
|
2270
2278
|
</div>`:"";return`
|
|
2271
2279
|
<a
|
|
2272
2280
|
href="${n}"
|
|
@@ -2300,7 +2308,7 @@ ${G}`;const r=e.hideBranding?"":`<div class="powered-by-inline">${x}</div>`,n=do
|
|
|
2300
2308
|
<div class="modal-result-image-container">
|
|
2301
2309
|
<div class="modal-result-image-placeholder">${s}</div>
|
|
2302
2310
|
</div>
|
|
2303
|
-
`}attachResultHandlers(){const e=this.resultsContainer?.querySelectorAll(".modal-result-item");if(!e)return;e.forEach((s,r)=>{s.getAttribute("href")==="#"&&s.addEventListener("click",
|
|
2311
|
+
`}attachResultHandlers(){const e=this.resultsContainer?.querySelectorAll(".modal-result-item");if(!e)return;e.forEach((s,r)=>{s.getAttribute("href")==="#"&&s.addEventListener("click",o=>{o.preventDefault()}),s.addEventListener("mouseenter",()=>{this.activeIndex=r,this.updateActiveResult()})}),this.resultsContainer?.querySelectorAll(".modal-result-image")?.forEach(s=>{s.addEventListener("load",()=>{s.classList.add("loaded"),s.closest(".modal-result-image-container")?.querySelector(".modal-result-image-loading")?.remove()}),s.addEventListener("error",()=>{const r=s.closest(".modal-result-image-container");r?.querySelector(".modal-result-image-loading")?.remove();const n=r?.querySelector(".modal-result-image-placeholder");n&&(n.style.display="flex"),s.style.display="none"})})}renderEmptyState(){return`
|
|
2304
2312
|
<div class="modal-empty">
|
|
2305
2313
|
<svg class="modal-empty-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
2306
2314
|
<circle cx="11" cy="11" r="8"></circle>
|
|
@@ -2326,5 +2334,5 @@ ${G}`;const r=e.hideBranding?"":`<div class="powered-by-inline">${x}</div>`,n=do
|
|
|
2326
2334
|
<div class="error">
|
|
2327
2335
|
<strong>Error:</strong> ${d(e)}
|
|
2328
2336
|
</div>
|
|
2329
|
-
`,this.footerCount&&(this.footerCount.textContent="Error"))}updateTheme(e){const t=e==="light"||e==="dark"||e==="auto"?e:"auto";t==="auto"?this.removeAttribute("theme"):this.setAttribute("theme",t)}lockBodyScroll(){const e=window.scrollY;this.savedBodyStyles={overflow:document.body.style.overflow,position:document.body.style.position,top:document.body.style.top,width:document.body.style.width},this.savedHtmlOverflow=document.documentElement.style.overflow,document.documentElement.style.overflow="hidden",document.body.style.overflow="hidden",document.body.style.position="fixed",document.body.style.top=`-${e}px`,document.body.style.width="100%"}unlockBodyScroll(){if(!this.savedBodyStyles)return;const e=Math.abs(Number.parseInt(document.body.style.top||"0",10));document.documentElement.style.overflow=this.savedHtmlOverflow||"",document.body.style.overflow=this.savedBodyStyles.overflow,document.body.style.position=this.savedBodyStyles.position,document.body.style.top=this.savedBodyStyles.top,document.body.style.width=this.savedBodyStyles.width,window.scrollTo(0,e),this.savedBodyStyles=null,this.savedHtmlOverflow=null}cleanup(){this.clearLoadingInterval(),this.currentSearchController&&(this.currentSearchController.abort(),this.currentSearchController=null),this.handleGlobalKeydown&&(document.removeEventListener("keydown",this.handleGlobalKeydown),this.handleGlobalKeydown=null),this.inputElement&&(this.handleInputChange&&this.inputElement.removeEventListener("input",this.handleInputChange),this.handleInputKeydown&&this.inputElement.removeEventListener("keydown",this.handleInputKeydown)),this.backdrop&&this.handleBackdropClick&&this.backdrop.removeEventListener("click",this.handleBackdropClick),this.handleInputChange=null,this.handleInputKeydown=null,this.handleBackdropClick=null,this.client&&this.client.cancelAllRequests()}open(){this.isOpen||(this.isOpen=!0,this.backdrop?.classList.add("open"),this.modal?.classList.add("open"),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.inputElement?.focus()})}),this.lockBodyScroll(),this.dispatchEvent(v("open",void 0)))}close(){this.isOpen&&(this.isOpen=!1,this.backdrop?.classList.remove("open"),this.modal?.classList.remove("open"),this.inputElement&&(this.inputElement.value=""),this.results=[],this.activeIndex=-1,this.showEmptyState(),this.unlockBodyScroll(),this.dispatchEvent(v("close",void 0)))}toggle(){this.isOpen?this.close():this.open()}async search(e){this.isOpen||this.open(),this.inputElement&&(this.inputElement.value=e),await this.performSearch(e)}getResults(){return[...this.results]}isModalOpen(){return this.isOpen}}customElements.get(
|
|
2337
|
+
`,this.footerCount&&(this.footerCount.textContent="Error"))}showMissingApiUrlError(){this.resultsContainer&&this.showErrorState("The api-url attribute is required. Please provide a valid API URL.")}updateTheme(e){const t=e==="light"||e==="dark"||e==="auto"?e:"auto";t==="auto"?this.removeAttribute("theme"):this.setAttribute("theme",t)}lockBodyScroll(){const e=window.scrollY;this.savedBodyStyles={overflow:document.body.style.overflow,position:document.body.style.position,top:document.body.style.top,width:document.body.style.width},this.savedHtmlOverflow=document.documentElement.style.overflow,document.documentElement.style.overflow="hidden",document.body.style.overflow="hidden",document.body.style.position="fixed",document.body.style.top=`-${e}px`,document.body.style.width="100%"}unlockBodyScroll(){if(!this.savedBodyStyles)return;const e=Math.abs(Number.parseInt(document.body.style.top||"0",10));document.documentElement.style.overflow=this.savedHtmlOverflow||"",document.body.style.overflow=this.savedBodyStyles.overflow,document.body.style.position=this.savedBodyStyles.position,document.body.style.top=this.savedBodyStyles.top,document.body.style.width=this.savedBodyStyles.width,window.scrollTo(0,e),this.savedBodyStyles=null,this.savedHtmlOverflow=null}cleanup(){this.clearLoadingInterval(),this.currentSearchController&&(this.currentSearchController.abort(),this.currentSearchController=null),this.handleGlobalKeydown&&(document.removeEventListener("keydown",this.handleGlobalKeydown),this.handleGlobalKeydown=null),this.inputElement&&(this.handleInputChange&&this.inputElement.removeEventListener("input",this.handleInputChange),this.handleInputKeydown&&this.inputElement.removeEventListener("keydown",this.handleInputKeydown)),this.backdrop&&this.handleBackdropClick&&this.backdrop.removeEventListener("click",this.handleBackdropClick),this.handleInputChange=null,this.handleInputKeydown=null,this.handleBackdropClick=null,this.client&&this.client.cancelAllRequests()}open(){this.isOpen||(this.isOpen=!0,this.backdrop?.classList.add("open"),this.modal?.classList.add("open"),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.inputElement?.focus()})}),this.lockBodyScroll(),this.dispatchEvent(v("open",void 0)))}close(){this.isOpen&&(this.isOpen=!1,this.backdrop?.classList.remove("open"),this.modal?.classList.remove("open"),this.inputElement&&(this.inputElement.value=""),this.results=[],this.activeIndex=-1,this.showEmptyState(),this.unlockBodyScroll(),this.dispatchEvent(v("close",void 0)))}toggle(){this.isOpen?this.close():this.open()}async search(e){this.isOpen||this.open(),this.inputElement&&(this.inputElement.value=e),await this.performSearch(e)}getResults(){return[...this.results]}isModalOpen(){return this.isOpen}}customElements.get(D)||customElements.define(D,U),p.AISearchClient=A,p.ChatBubbleSnippet=R,p.ChatPageSnippet=_,p.SearchBarSnippet=E,p.SearchModalSnippet=U,p.default=E,Object.defineProperties(p,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
|
|
2330
2338
|
//# sourceMappingURL=search-snippet.umd.js.map
|