@cloudflare/ai-search-snippet 0.0.23 → 0.0.24
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 +8 -0
- package/dist/search-snippet.es.js +305 -234
- package/dist/search-snippet.es.js.map +1 -1
- package/dist/search-snippet.umd.js +85 -60
- package/dist/search-snippet.umd.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
(function(
|
|
1
|
+
(function(u,l){typeof exports=="object"&&typeof module<"u"?l(exports):typeof define=="function"&&define.amd?define(["exports"],l):(u=typeof globalThis<"u"?globalThis:u||self,l(u.SearchSnippet={}))})(this,(function(u){"use strict";var Y=Object.defineProperty;var W=(u,l,w)=>l in u?Y(u,l,{enumerable:!0,configurable:!0,writable:!0,value:w}):u[l]=w;var a=(u,l,w)=>W(u,typeof l!="symbol"?l+"":l,w);const l=["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(o,i){let e;return function(...s){const r=()=>{clearTimeout(e),o(...s)};clearTimeout(e),e=setTimeout(r,i)}}function h(o){const i=document.createElement("div");return i.textContent=o,i.innerHTML}function I(o){return new DOMParser().parseFromString(o,"text/html").documentElement.textContent||""}function V(o){const i=new Date(o),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(o="id"){return`${o}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}function g(o,i){return o!==null?o:i}function f(o,i){return o===null?i:o==="true"||o===""}function x(o,i){if(o===null)return i;const e=Number.parseInt(o,10);return Number.isNaN(e)?i:e}function v(o,i){return new CustomEvent(o,{detail:i,bubbles:!0,composed:!0,cancelable:!0})}function k(o){if(!o)throw new Error("API URL is required");return new A(o)}class D{constructor(i){a(this,"activeRequests",new Map);a(this,"baseUrl");this.baseUrl=i.replace(/\/$/,"")}search(i,e){throw new Error("Not implemented")}searchStream(i,e){throw new Error("Not implemented")}chat(i,e){throw new Error("Not implemented")}cancelRequest(i){throw new Error("Not implemented")}cancelAllRequests(){throw new Error("Not implemented")}}class A extends D{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: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 c=await n.json();if(c.success&&c.result){const d=new Map;for(const p of c.result.chunks){const b=p.item.key,m=p.scoring_details.vector_score;(!d.has(b)||(d.get(b)?.score??0)<m)&&d.set(b,{chunk:p,score:m})}return Array.from(d.values()).sort((p,b)=>b.score-p.score).slice(0,10).map(({chunk:p})=>({type:"result",id:p.id,title:I(p.item.metadata.title),description:p.item.metadata.description?I(p.item.metadata.description):"",url:p.item.key,image:p.item.metadata.image||void 0,metadata:p.item.metadata}))}throw c.success===!1?new Error(c.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 c="";const d=n.body.getReader(),p=new TextDecoder;for(;;){const{done:m,value:M}=await d.read();if(m)break;const F=p.decode(M,{stream:!0});c+=F}yield{type:"result",id:"",title:"",description:c.replaceAll("data: ","").trim().split(`
|
|
2
2
|
|
|
3
|
-
`).map(m=>JSON.parse(m)).map(m=>m.response).join(""),url:"",metadata:{}}}async*chat(i,e){const t=new AbortController,s=e?.signal||t.signal,
|
|
3
|
+
`).map(m=>JSON.parse(m)).map(m=>m.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(c=>c.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://search.ai.cloudflare.com" 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
|
-
</svg></a>`,
|
|
6
|
+
</svg></a>`,T=`
|
|
7
7
|
/* Chat container */
|
|
8
8
|
.chat-container {
|
|
9
9
|
display: flex;
|
|
@@ -198,6 +198,10 @@
|
|
|
198
198
|
}
|
|
199
199
|
}
|
|
200
200
|
|
|
201
|
+
.chat-streaming .loading-text {
|
|
202
|
+
margin-left: var(--search-snippet-spacing-xs);
|
|
203
|
+
}
|
|
204
|
+
|
|
201
205
|
/* Input area */
|
|
202
206
|
.chat-input-area {
|
|
203
207
|
padding: var(--search-snippet-spacing-md);
|
|
@@ -316,7 +320,7 @@
|
|
|
316
320
|
.chat-message-bubble a:hover {
|
|
317
321
|
text-decoration: none;
|
|
318
322
|
}
|
|
319
|
-
`,
|
|
323
|
+
`,S=`
|
|
320
324
|
:host {
|
|
321
325
|
/* Colors - Light Mode */
|
|
322
326
|
--search-snippet-primary-color: #2563eb;
|
|
@@ -651,6 +655,27 @@
|
|
|
651
655
|
to { transform: rotate(360deg); }
|
|
652
656
|
}
|
|
653
657
|
|
|
658
|
+
/* Loading message animation */
|
|
659
|
+
@keyframes loading-message-in {
|
|
660
|
+
from {
|
|
661
|
+
opacity: 0;
|
|
662
|
+
transform: translateY(8px);
|
|
663
|
+
}
|
|
664
|
+
to {
|
|
665
|
+
opacity: 1;
|
|
666
|
+
transform: translateY(0);
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
.loading-text {
|
|
671
|
+
font-size: var(--search-snippet-font-size-sm);
|
|
672
|
+
color: var(--search-snippet-text-secondary);
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
.loading-text-animate {
|
|
676
|
+
animation: loading-message-in 0.3s ease-out;
|
|
677
|
+
}
|
|
678
|
+
|
|
654
679
|
/* Error message */
|
|
655
680
|
.error {
|
|
656
681
|
padding: var(--search-snippet-spacing-md);
|
|
@@ -729,9 +754,9 @@
|
|
|
729
754
|
padding: var(--search-snippet-spacing-xs) 0;
|
|
730
755
|
text-align: center;
|
|
731
756
|
}
|
|
732
|
-
`;function
|
|
733
|
-
`),t=[];let s=!1,
|
|
734
|
-
`)}function
|
|
757
|
+
`;function j(o){let i=o;i=K(i),i=i.replace(/```([\s\S]*?)```/g,(n,c)=>`<pre><code>${c.trim()}</code></pre>`);const e=i.split(`
|
|
758
|
+
`),t=[];let s=!1,r="";for(let n=0;n<e.length;n++){const c=e[n],d=c.match(/^(#{1,6})\s+(.+)$/);if(d){const m=d[1].length,M=d[2];t.push(`<h${m}>${y(M)}</h${m}>`);continue}if(c.match(/^---+$/)){t.push("<hr />");continue}if(c.match(/^>\s+/)){const m=c.replace(/^>\s+/,"");t.push(`<blockquote>${y(m)}</blockquote>`);continue}const p=c.match(/^[-*]\s+(.+)$/);if(p){(!s||r!=="ul")&&(s&&t.push(`</${r}>`),t.push("<ul>"),s=!0,r="ul"),t.push(`<li>${y(p[1])}</li>`);continue}const b=c.match(/^\d+\.\s+(.+)$/);if(b){(!s||r!=="ol")&&(s&&t.push(`</${r}>`),t.push("<ol>"),s=!0,r="ol"),t.push(`<li>${y(b[1])}</li>`);continue}if(s&&(t.push(`</${r}>`),s=!1,r=""),c.trim()===""){t.push("<br />");continue}t.push(`<p>${y(c)}</p>`)}return s&&t.push(`</${r}>`),t.join(`
|
|
759
|
+
`)}function y(o){let i=o;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 K(o){const i={"&":"&","<":"<",">":">",'"':""","'":"'"};return o.replace(/[&<>"']/g,e=>i[e]||e)}class ${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=`
|
|
735
760
|
<div class="chat-container">
|
|
736
761
|
<div class="chat-messages">
|
|
737
762
|
<div class="chat-empty">
|
|
@@ -748,7 +773,7 @@
|
|
|
748
773
|
<div class="chat-input-wrapper">
|
|
749
774
|
<textarea
|
|
750
775
|
class="chat-input"
|
|
751
|
-
placeholder="${
|
|
776
|
+
placeholder="${h(this.props.placeholder||"Type a message...")}"
|
|
752
777
|
aria-label="Chat message input"
|
|
753
778
|
style="height: 40px;"
|
|
754
779
|
rows="1"
|
|
@@ -759,7 +784,7 @@
|
|
|
759
784
|
</div>
|
|
760
785
|
</div>
|
|
761
786
|
</div>
|
|
762
|
-
`,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:
|
|
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:z("msg"),role:"user",content:i,timestamp:Date.now()};this.addMessage(e),this.renderMessages(!0),this.setStreamingState(!0);const t=z("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 d of r)if(d.type==="text"&&d.message)n+=d.message,this.updateStreamingMessage(t,n);else if(d.type==="error"){this.showErrorInMessage(t,d.message||"Unknown error");break}const c=this.messages.findIndex(d=>d.id===t);c!==-1&&(this.messages[c].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=`
|
|
763
788
|
<div class="chat-empty">
|
|
764
789
|
<svg class="chat-empty-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
765
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>
|
|
@@ -774,16 +799,16 @@
|
|
|
774
799
|
<div class="chat-message-avatar">${s}</div>
|
|
775
800
|
<div class="chat-message-content">
|
|
776
801
|
<div class="chat-message-bubble">
|
|
777
|
-
${i.content?`<div class="chat-message-text">${
|
|
778
|
-
${e
|
|
802
|
+
${i.content?`<div class="chat-message-text">${j(i.content)}</div>`:""}
|
|
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">${l[this.loadingMessageIndex]}</span></div>`:""}
|
|
779
804
|
</div>
|
|
780
805
|
<div class="chat-message-metadata">
|
|
781
|
-
<span class="chat-message-time">${
|
|
806
|
+
<span class="chat-message-time">${V(i.timestamp)}</span>
|
|
782
807
|
</div>
|
|
783
808
|
</div>
|
|
784
809
|
</div>
|
|
785
|
-
`}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>")}getMessages(){return[...this.messages]}clearMessages(){this.messages=[],this.renderMessages()}setMessages(i){this.messages=[...i],this.renderMessages()}destroy(){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
|
|
786
|
-
${
|
|
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()*l.length),this.loadingMessageInterval=setInterval(()=>{this.loadingMessageIndex=(this.loadingMessageIndex+1)%l.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 B 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:g(this.getAttribute("api-url"),"http://localhost:3000"),placeholder:g(this.getAttribute("placeholder"),"Type a message..."),theme:g(this.getAttribute("theme"),"auto"),hideBranding:f(this.getAttribute("hide-branding"),!1)}}initializeClient(){const e=this.getProps();if(!e.apiUrl){console.error("ChatBubbleSnippet: api-url attribute is required");return}try{this.client=k(e.apiUrl)}catch(t){console.error("ChatBubbleSnippet:",t)}}render(){const e=document.createElement("style");e.textContent=`${S}
|
|
811
|
+
${T}
|
|
787
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`
|
|
788
813
|
.chat-bubble-widget {
|
|
789
814
|
position: var(--chat-bubble-position);
|
|
@@ -957,10 +982,10 @@ ${this.getBubbleStyles()}`,this.container=document.createElement("div"),this.con
|
|
|
957
982
|
</div>
|
|
958
983
|
</div>
|
|
959
984
|
<div class="chat-content"></div>
|
|
960
|
-
${this.getProps().hideBranding?"":`<div class="powered-by">${
|
|
985
|
+
${this.getProps().hideBranding?"":`<div class="powered-by">${C}</div>`}
|
|
961
986
|
</div>
|
|
962
|
-
`}attachEventListeners(){const e=this.shadow.querySelector(".bubble-button"),t=this.shadow.querySelector(".close-button"),s=this.shadow.querySelector(".minimize-button"),
|
|
963
|
-
${
|
|
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||!this.client)return;const e=this.shadow.querySelector(".chat-content");if(!e)return;const t=this.getProps();this.chatView=new $(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,B);const R="chat-page-snippet",H="chat-page-sessions";class N 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:g(this.getAttribute("api-url"),"http://localhost:3000"),placeholder:g(this.getAttribute("placeholder"),"Type a message..."),theme:g(this.getAttribute("theme"),"auto"),hideBranding:f(this.getAttribute("hide-branding"),!1)}}initializeClient(){const e=this.getProps();if(!e.apiUrl){console.error("ChatPageSnippet: api-url attribute is required");return}try{this.client=k(e.apiUrl)}catch(t){console.error("ChatPageSnippet:",t)}}render(){const e=document.createElement("style");e.textContent=`${S}
|
|
988
|
+
${T}
|
|
964
989
|
${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`
|
|
965
990
|
:host {
|
|
966
991
|
display: block;
|
|
@@ -1246,7 +1271,7 @@ ${this.getPageStyles()}`,this.container=document.createElement("div"),this.conta
|
|
|
1246
1271
|
New Chat
|
|
1247
1272
|
</button>
|
|
1248
1273
|
<div class="chat-list"></div>
|
|
1249
|
-
${this.getProps().hideBranding?"":`<div class="powered-by">${
|
|
1274
|
+
${this.getProps().hideBranding?"":`<div class="powered-by">${C}</div>`}
|
|
1250
1275
|
</div>
|
|
1251
1276
|
<div class="chat-main">
|
|
1252
1277
|
<div class="chat-page-header">
|
|
@@ -1276,7 +1301,7 @@ ${this.getPageStyles()}`,this.container=document.createElement("div"),this.conta
|
|
|
1276
1301
|
<div class="container"></div>
|
|
1277
1302
|
</div>
|
|
1278
1303
|
</div>
|
|
1279
|
-
`}attachEventListeners(){const e=this.shadow.querySelector(".clear-button"),t=this.shadow.querySelector(".new-chat-button"),s=this.shadow.querySelector(".toggle-sidebar-button"),
|
|
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(){if(!this.client)return;const e=this.shadow.querySelector(".container");if(!e)return;const t=this.getProps();if(this.chatView=new $(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(H);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(H,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`
|
|
1280
1305
|
<div class="chat-list-item ${t?"active":""}" data-session-id="${e.id}">
|
|
1281
1306
|
<div class="chat-list-item-content">
|
|
1282
1307
|
<div class="chat-list-item-title">${this.escapeHTML(e.title)}</div>
|
|
@@ -1288,7 +1313,7 @@ ${this.getPageStyles()}`,this.container=document.createElement("div"),this.conta
|
|
|
1288
1313
|
</svg>
|
|
1289
1314
|
</button>
|
|
1290
1315
|
</div>
|
|
1291
|
-
`}formatDate(e){const t=new Date(e),
|
|
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(R)||customElements.define(R,N);const U=`
|
|
1292
1317
|
/* Search view states */
|
|
1293
1318
|
.search-view {
|
|
1294
1319
|
transition: var(--search-snippet-transition-slow);
|
|
@@ -1620,8 +1645,8 @@ a.search-result-item:focus-visible {
|
|
|
1620
1645
|
border-radius: 2px;
|
|
1621
1646
|
font-weight: var(--search-snippet-font-weight-medium);
|
|
1622
1647
|
}
|
|
1623
|
-
`,
|
|
1624
|
-
${
|
|
1648
|
+
`,_="search-bar-snippet";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"]}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:g(this.getAttribute("api-url"),"http://localhost:3000"),placeholder:g(this.getAttribute("placeholder"),"Search..."),maxResults:x(this.getAttribute("max-results"),10),debounceMs:x(this.getAttribute("debounce-ms"),300),theme:g(this.getAttribute("theme"),"auto"),hideBranding:f(this.getAttribute("hide-branding"),!1),showUrl:f(this.getAttribute("show-url"),!1)}}initializeClient(){const e=this.getProps();if(!e.apiUrl){console.error("SearchBarSnippet: api-url attribute is required");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}
|
|
1649
|
+
${U}`,this.container=document.createElement("div"),this.container.className="container",this.container.innerHTML=`
|
|
1625
1650
|
<div class="search-view">
|
|
1626
1651
|
<div class="search-input-wrapper">
|
|
1627
1652
|
<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>
|
|
@@ -1629,7 +1654,7 @@ ${K}`,this.container=document.createElement("div"),this.container.className="con
|
|
|
1629
1654
|
type="text"
|
|
1630
1655
|
name="search-input"
|
|
1631
1656
|
class="search-input"
|
|
1632
|
-
placeholder="${
|
|
1657
|
+
placeholder="${h(e.placeholder||"Search...")}"
|
|
1633
1658
|
aria-label="Search input"
|
|
1634
1659
|
autocomplete="off"
|
|
1635
1660
|
/>
|
|
@@ -1643,23 +1668,23 @@ ${K}`,this.container=document.createElement("div"),this.container.className="con
|
|
|
1643
1668
|
</div>
|
|
1644
1669
|
</div>
|
|
1645
1670
|
</div>
|
|
1646
|
-
`,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(t,e)}catch(t){if(t.name==="AbortError")return;this.showErrorState(t.message)}finally{this.currentSearchController=null}}}displayResults(e,t){if(
|
|
1671
|
+
`,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(t,e)}catch(t){if(t.name==="AbortError")return;this.showErrorState(t.message)}finally{this.currentSearchController=null}}}displayResults(e,t){if(this.clearLoadingInterval(),!this.resultsContainer)return;if(e.length===0){this.showNoResultsState(t);return}const r=this.getProps().hideBranding?"":`<div class="powered-by-inline">${C}</div>`,n=`
|
|
1647
1672
|
<div class="search-header">
|
|
1648
1673
|
<div class="search-count">
|
|
1649
1674
|
Found ${e.length} result${e.length===1?"":"s"}
|
|
1650
1675
|
</div>
|
|
1651
|
-
${
|
|
1676
|
+
${r}
|
|
1652
1677
|
</div>
|
|
1653
1678
|
<div class="search-results">
|
|
1654
1679
|
${e.map(c=>this.renderResult(c)).join("")}
|
|
1655
1680
|
</div>
|
|
1656
1681
|
`;this.resultsContainer.innerHTML=n,this.attachResultHandlers()}renderResult(e){const t=this.getProps(),s=this.renderResultImage(e.image,e.title);return`
|
|
1657
|
-
<a href="${e.url?
|
|
1682
|
+
<a href="${e.url?h(e.url):"#"}" class="search-result-item" data-result-id="${h(e.url||"")}">
|
|
1658
1683
|
${s}
|
|
1659
1684
|
<div class="search-result-content">
|
|
1660
|
-
<div class="search-result-title">${
|
|
1661
|
-
<div class="search-result-snippet">${
|
|
1662
|
-
${t.showUrl&&e.url?`<span class="search-result-url">${
|
|
1685
|
+
<div class="search-result-title">${h(e.title||"")}</div>
|
|
1686
|
+
<div class="search-result-snippet">${h(e.description||"")}</div>
|
|
1687
|
+
${t.showUrl&&e.url?`<span class="search-result-url">${h(e.url)}</span>`:""}
|
|
1663
1688
|
</div>
|
|
1664
1689
|
</a>
|
|
1665
1690
|
`}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?`
|
|
@@ -1668,8 +1693,8 @@ ${K}`,this.container=document.createElement("div"),this.container.className="con
|
|
|
1668
1693
|
<div class="search-result-image-placeholder" style="display: none;">${s}</div>
|
|
1669
1694
|
<img
|
|
1670
1695
|
class="search-result-image"
|
|
1671
|
-
src="${
|
|
1672
|
-
alt="${
|
|
1696
|
+
src="${h(e)}"
|
|
1697
|
+
alt="${h(t)}"
|
|
1673
1698
|
loading="lazy"
|
|
1674
1699
|
/>
|
|
1675
1700
|
</div>
|
|
@@ -1677,12 +1702,12 @@ ${K}`,this.container=document.createElement("div"),this.container.className="con
|
|
|
1677
1702
|
<div class="search-result-image-container">
|
|
1678
1703
|
<div class="search-result-image-placeholder">${s}</div>
|
|
1679
1704
|
</div>
|
|
1680
|
-
`}attachResultHandlers(){const e=this.container?.querySelectorAll(".search-result-item");if(!e)return;for(const s of e)s.getAttribute("href")==="#"&&s.addEventListener("click",n=>{n.preventDefault()});this.container?.querySelectorAll(".search-result-image")?.forEach(s=>{s.addEventListener("load",()=>{s.classList.add("loaded"),s.closest(".search-result-image-container")?.querySelector(".search-result-image-loading")?.remove()}),s.addEventListener("error",()=>{const
|
|
1705
|
+
`}attachResultHandlers(){const e=this.container?.querySelectorAll(".search-result-item");if(!e)return;for(const s of e)s.getAttribute("href")==="#"&&s.addEventListener("click",n=>{n.preventDefault()});this.container?.querySelectorAll(".search-result-image")?.forEach(s=>{s.addEventListener("load",()=>{s.classList.add("loaded"),s.closest(".search-result-image-container")?.querySelector(".search-result-image-loading")?.remove()}),s.addEventListener("error",()=>{const r=s.closest(".search-result-image-container");r?.querySelector(".search-result-image-loading")?.remove();const n=r?.querySelector(".search-result-image-placeholder");n&&(n.style.display="flex"),s.style.display="none"})})}showLoadingState(){this.resultsContainer&&(this.clearLoadingInterval(),this.loadingMessageIndex=Math.floor(Math.random()*l.length),this.resultsContainer.innerHTML=`
|
|
1681
1706
|
<div class="search-loading">
|
|
1682
1707
|
<div class="loading" aria-label="Loading"></div>
|
|
1683
|
-
<div
|
|
1708
|
+
<div class="loading-text loading-text-animate">${l[this.loadingMessageIndex]}</div>
|
|
1684
1709
|
</div>
|
|
1685
|
-
|
|
1710
|
+
`,this.startLoadingInterval())}startLoadingInterval(){this.loadingMessageInterval=setInterval(()=>{this.loadingMessageIndex=(this.loadingMessageIndex+1)%l.length;const e=this.resultsContainer?.querySelector(".loading-text");e&&(e.classList.remove("loading-text-animate"),e.offsetWidth,e.textContent=l[this.loadingMessageIndex],e.classList.add("loading-text-animate"))},2500)}clearLoadingInterval(){this.loadingMessageInterval&&(clearInterval(this.loadingMessageInterval),this.loadingMessageInterval=null)}showEmptyState(){this.clearLoadingInterval(),this.resultsContainer&&(this.resultsContainer.innerHTML=`
|
|
1686
1711
|
<div class="search-empty">
|
|
1687
1712
|
<svg class="search-empty-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
1688
1713
|
<circle cx="11" cy="11" r="8"></circle>
|
|
@@ -1693,7 +1718,7 @@ ${K}`,this.container=document.createElement("div"),this.container.className="con
|
|
|
1693
1718
|
Enter a query to search for results
|
|
1694
1719
|
</div>
|
|
1695
1720
|
</div>
|
|
1696
|
-
`)}showNoResultsState(e){this.resultsContainer&&(this.resultsContainer.innerHTML=`
|
|
1721
|
+
`)}showNoResultsState(e){this.clearLoadingInterval(),this.resultsContainer&&(this.resultsContainer.innerHTML=`
|
|
1697
1722
|
<div class="search-empty">
|
|
1698
1723
|
<svg class="search-empty-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
1699
1724
|
<circle cx="11" cy="11" r="8"></circle>
|
|
@@ -1701,14 +1726,14 @@ ${K}`,this.container=document.createElement("div"),this.container.className="con
|
|
|
1701
1726
|
</svg>
|
|
1702
1727
|
<div class="search-empty-title">No Results Found</div>
|
|
1703
1728
|
<div class="search-empty-description">
|
|
1704
|
-
No results found for "${
|
|
1729
|
+
No results found for "${h(e)}"
|
|
1705
1730
|
</div>
|
|
1706
1731
|
</div>
|
|
1707
|
-
`)}showErrorState(e){this.resultsContainer&&(this.resultsContainer.innerHTML=`
|
|
1732
|
+
`)}showErrorState(e){this.clearLoadingInterval(),this.resultsContainer&&(this.resultsContainer.innerHTML=`
|
|
1708
1733
|
<div class="error">
|
|
1709
|
-
<strong>Error:</strong> ${
|
|
1734
|
+
<strong>Error:</strong> ${h(e)}
|
|
1710
1735
|
</div>
|
|
1711
|
-
`)}updateTheme(e){const t=e==="light"||e==="dark"||e==="auto"?e:"auto";t==="auto"?this.removeAttribute("theme"):this.setAttribute("theme",t)}cleanup(){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(
|
|
1736
|
+
`)}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(_)||customElements.define(_,E);const G=`
|
|
1712
1737
|
/* Modal backdrop */
|
|
1713
1738
|
.modal-backdrop {
|
|
1714
1739
|
position: fixed;
|
|
@@ -2107,8 +2132,8 @@ a.modal-result-item:focus-visible {
|
|
|
2107
2132
|
.modal-container.open {
|
|
2108
2133
|
animation: modal-slide-in var(--search-snippet-transition) ease-out;
|
|
2109
2134
|
}
|
|
2110
|
-
`,
|
|
2111
|
-
${
|
|
2135
|
+
`,O="search-modal-snippet";class P 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"]}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:g(this.getAttribute("api-url"),"http://localhost:3000"),placeholder:g(this.getAttribute("placeholder"),"Search..."),maxResults:x(this.getAttribute("max-results"),10),debounceMs:x(this.getAttribute("debounce-ms"),300),theme:g(this.getAttribute("theme"),"auto"),shortcut:g(this.getAttribute("shortcut"),"k"),useMetaKey:this.getAttribute("use-meta-key")!=="false",hideBranding:f(this.getAttribute("hide-branding"),!1),showUrl:f(this.getAttribute("show-url"),!1)}}initializeClient(){const e=this.getProps();if(!e.apiUrl){console.error("SearchModalSnippet: api-url attribute is required");return}try{this.client=k(e.apiUrl)}catch(t){console.error("SearchModalSnippet:",t)}}render(){const e=this.getProps(),t=c=>this.performSearch(c);this.debouncedSearch=L(t,e.debounceMs||300);const s=document.createElement("style");s.textContent=`${S}
|
|
2136
|
+
${G}`;const r=e.hideBranding?"":`<div class="powered-by-inline">${C}</div>`,n=document.createElement("div");n.innerHTML=`
|
|
2112
2137
|
<div class="modal-backdrop" role="presentation"></div>
|
|
2113
2138
|
<div class="modal-container" role="dialog" aria-modal="true" aria-labelledby="modal-title">
|
|
2114
2139
|
<div class="modal-header">
|
|
@@ -2118,7 +2143,7 @@ ${D}`;const a=e.hideBranding?"":`<div class="powered-by-inline">${k}</div>`,n=do
|
|
|
2118
2143
|
<input
|
|
2119
2144
|
type="text"
|
|
2120
2145
|
class="modal-search-input"
|
|
2121
|
-
placeholder="${
|
|
2146
|
+
placeholder="${h(e.placeholder||"Search...")}"
|
|
2122
2147
|
aria-label="Search"
|
|
2123
2148
|
aria-autocomplete="list"
|
|
2124
2149
|
aria-controls="modal-results-list"
|
|
@@ -2148,25 +2173,25 @@ ${D}`;const a=e.hideBranding?"":`<div class="powered-by-inline">${k}</div>`,n=do
|
|
|
2148
2173
|
<span>Close</span>
|
|
2149
2174
|
</div>
|
|
2150
2175
|
</div>
|
|
2151
|
-
${
|
|
2176
|
+
${r}
|
|
2152
2177
|
</div>
|
|
2153
2178
|
</div>
|
|
2154
|
-
`,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||10),this.activeIndex=this.results.length>0?0:-1,this.displayResults(this.results,e)}catch(t){if(t.name==="AbortError")return;this.showErrorState(t.message)}finally{this.currentSearchController=null}}}displayResults(e,t){if(
|
|
2179
|
+
`,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||10),this.activeIndex=this.results.length>0?0:-1,this.displayResults(this.results,e)}catch(t){if(t.name==="AbortError")return;this.showErrorState(t.message)}finally{this.currentSearchController=null}}}displayResults(e,t){if(this.clearLoadingInterval(),!this.resultsContainer)return;if(e.length===0){this.showNoResultsState(t);return}const s=e.map((r,n)=>this.renderResult(r,n)).join("");this.resultsContainer.innerHTML=s,this.footerCount&&(this.footerCount.textContent=`${e.length} result${e.length===1?"":"s"}`),this.inputElement&&this.inputElement.setAttribute("aria-expanded","true"),this.attachResultHandlers(),this.updateActiveResult()}renderResult(e,t){const s=this.getProps(),r=this.renderResultImage(e.image,e.title);return`
|
|
2155
2180
|
<a
|
|
2156
|
-
href="${e.url?
|
|
2181
|
+
href="${e.url?h(e.url):"#"}"
|
|
2157
2182
|
class="modal-result-item${t===this.activeIndex?" active":""}"
|
|
2158
2183
|
role="option"
|
|
2159
2184
|
id="result-${t}"
|
|
2160
2185
|
aria-selected="${t===this.activeIndex}"
|
|
2161
2186
|
tabindex="-1"
|
|
2162
2187
|
data-index="${t}"
|
|
2163
|
-
data-url="${
|
|
2188
|
+
data-url="${h(e.url||"")}"
|
|
2164
2189
|
>
|
|
2165
|
-
${
|
|
2190
|
+
${r}
|
|
2166
2191
|
<div class="modal-result-content">
|
|
2167
|
-
<div class="modal-result-title">${
|
|
2168
|
-
${e.description?`<div class="modal-result-description">${
|
|
2169
|
-
${s.showUrl&&e.url?`<span class="modal-result-url">${
|
|
2192
|
+
<div class="modal-result-title">${h(e.title||"")}</div>
|
|
2193
|
+
${e.description?`<div class="modal-result-description">${h(e.description)}</div>`:""}
|
|
2194
|
+
${s.showUrl&&e.url?`<span class="modal-result-url">${h(e.url)}</span>`:""}
|
|
2170
2195
|
</div>
|
|
2171
2196
|
</a>
|
|
2172
2197
|
`}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?`
|
|
@@ -2175,8 +2200,8 @@ ${D}`;const a=e.hideBranding?"":`<div class="powered-by-inline">${k}</div>`,n=do
|
|
|
2175
2200
|
<div class="modal-result-image-placeholder" style="display: none;">${s}</div>
|
|
2176
2201
|
<img
|
|
2177
2202
|
class="modal-result-image"
|
|
2178
|
-
src="${
|
|
2179
|
-
alt="${
|
|
2203
|
+
src="${h(e)}"
|
|
2204
|
+
alt="${h(t)}"
|
|
2180
2205
|
loading="lazy"
|
|
2181
2206
|
/>
|
|
2182
2207
|
</div>
|
|
@@ -2184,7 +2209,7 @@ ${D}`;const a=e.hideBranding?"":`<div class="powered-by-inline">${k}</div>`,n=do
|
|
|
2184
2209
|
<div class="modal-result-image-container">
|
|
2185
2210
|
<div class="modal-result-image-placeholder">${s}</div>
|
|
2186
2211
|
</div>
|
|
2187
|
-
`}attachResultHandlers(){const e=this.resultsContainer?.querySelectorAll(".modal-result-item");if(!e)return;e.forEach((s,
|
|
2212
|
+
`}attachResultHandlers(){const e=this.resultsContainer?.querySelectorAll(".modal-result-item");if(!e)return;e.forEach((s,r)=>{s.getAttribute("href")==="#"&&s.addEventListener("click",c=>{c.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`
|
|
2188
2213
|
<div class="modal-empty">
|
|
2189
2214
|
<svg class="modal-empty-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
2190
2215
|
<circle cx="11" cy="11" r="8"></circle>
|
|
@@ -2192,23 +2217,23 @@ ${D}`;const a=e.hideBranding?"":`<div class="powered-by-inline">${k}</div>`,n=do
|
|
|
2192
2217
|
</svg>
|
|
2193
2218
|
<div class="modal-empty-description">Start typing to search</div>
|
|
2194
2219
|
</div>
|
|
2195
|
-
`}showEmptyState(){this.resultsContainer&&(this.resultsContainer.innerHTML=this.renderEmptyState(),this.footerCount&&(this.footerCount.textContent=""),this.inputElement&&this.inputElement.setAttribute("aria-expanded","false"))}showLoadingState(){this.resultsContainer&&(this.resultsContainer.innerHTML=`
|
|
2220
|
+
`}showEmptyState(){this.clearLoadingInterval(),this.resultsContainer&&(this.resultsContainer.innerHTML=this.renderEmptyState(),this.footerCount&&(this.footerCount.textContent=""),this.inputElement&&this.inputElement.setAttribute("aria-expanded","false"))}showLoadingState(){this.resultsContainer&&(this.clearLoadingInterval(),this.loadingMessageIndex=Math.floor(Math.random()*l.length),this.resultsContainer.innerHTML=`
|
|
2196
2221
|
<div class="modal-loading">
|
|
2197
2222
|
<div class="loading" aria-label="Loading"></div>
|
|
2198
|
-
<div
|
|
2223
|
+
<div class="loading-text loading-text-animate">${l[this.loadingMessageIndex]}</div>
|
|
2199
2224
|
</div>
|
|
2200
|
-
`,this.footerCount&&(this.footerCount.textContent="
|
|
2225
|
+
`,this.footerCount&&(this.footerCount.textContent=l[this.loadingMessageIndex]),this.startLoadingInterval())}startLoadingInterval(){this.loadingMessageInterval=setInterval(()=>{this.loadingMessageIndex=(this.loadingMessageIndex+1)%l.length;const e=this.resultsContainer?.querySelector(".loading-text");e&&(e.classList.remove("loading-text-animate"),e.offsetWidth,e.textContent=l[this.loadingMessageIndex],e.classList.add("loading-text-animate")),this.footerCount&&(this.footerCount.textContent=l[this.loadingMessageIndex])},2500)}clearLoadingInterval(){this.loadingMessageInterval&&(clearInterval(this.loadingMessageInterval),this.loadingMessageInterval=null)}showNoResultsState(e){this.clearLoadingInterval(),this.resultsContainer&&(this.resultsContainer.innerHTML=`
|
|
2201
2226
|
<div class="modal-empty">
|
|
2202
2227
|
<svg class="modal-empty-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
2203
2228
|
<circle cx="11" cy="11" r="8"></circle>
|
|
2204
2229
|
<line x1="21" y1="21" x2="16.65" y2="16.65"></line>
|
|
2205
2230
|
</svg>
|
|
2206
2231
|
<div class="modal-empty-title">No results found</div>
|
|
2207
|
-
<div class="modal-empty-description">No results for "${
|
|
2232
|
+
<div class="modal-empty-description">No results for "${h(e)}"</div>
|
|
2208
2233
|
</div>
|
|
2209
|
-
`,this.footerCount&&(this.footerCount.textContent="0 results"),this.inputElement&&this.inputElement.setAttribute("aria-expanded","false"))}showErrorState(e){this.resultsContainer&&(this.resultsContainer.innerHTML=`
|
|
2234
|
+
`,this.footerCount&&(this.footerCount.textContent="0 results"),this.inputElement&&this.inputElement.setAttribute("aria-expanded","false"))}showErrorState(e){this.clearLoadingInterval(),this.resultsContainer&&(this.resultsContainer.innerHTML=`
|
|
2210
2235
|
<div class="error">
|
|
2211
|
-
<strong>Error:</strong> ${
|
|
2236
|
+
<strong>Error:</strong> ${h(e)}
|
|
2212
2237
|
</div>
|
|
2213
|
-
`,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.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(
|
|
2238
|
+
`,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(O)||customElements.define(O,P),u.AISearchClient=A,u.ChatBubbleSnippet=B,u.ChatPageSnippet=N,u.SearchBarSnippet=E,u.SearchModalSnippet=P,u.default=E,Object.defineProperties(u,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
|
|
2214
2239
|
//# sourceMappingURL=search-snippet.umd.js.map
|