@cloudflare/ai-search-snippet 0.0.38 → 0.0.39
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 +186 -4
- package/dist/search-snippet.es.js +819 -399
- package/dist/search-snippet.es.js.map +1 -1
- package/dist/search-snippet.umd.js +120 -95
- package/dist/search-snippet.umd.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,9 +1,29 @@
|
|
|
1
|
-
(function(
|
|
1
|
+
(function(g,v){typeof exports=="object"&&typeof module<"u"?v(exports):typeof define=="function"&&define.amd?define(["exports"],v):(g=typeof globalThis<"u"?globalThis:g||self,v(g.SearchSnippet={}))})(this,(function(g){"use strict";var be=Object.defineProperty;var ye=(g,v,u)=>v in g?be(g,v,{enumerable:!0,configurable:!0,writable:!0,value:u}):g[v]=u;var a=(g,v,u)=>ye(g,typeof v!="symbol"?v+"":v,u);const v={loadingAriaLabel:"Loading",errorPrefix:"Error:",missingApiUrlError:"The api-url attribute is required. Please provide a valid API URL.",poweredBy:"Powered by",poweredByLinkLabel:"Cloudflare AI Search",placeholder:"Search...",searchButtonLabel:"Search",searchInputAriaLabel:"Search input",searchResultsAriaLabel:"Search results",emptyStateTitle:"Start Searching",emptyStateDescription:"Enter a query to search for results",modalEmptyStateDescription:"Start typing to search",noResultsTitle:"No Results Found",noResultsDescription:'No results found for "{query}"',modalNoResultsTitle:"No results found",modalNoResultsDescription:'No results for "{query}"',resultsCount:"Found {n} result",resultsCountPlural:"Found {n} results",resultsCountOverflow:"Showing {n} of {total} results",modalResultsCount:"{n} result",modalResultsCountPlural:"{n} results",modalResultsCountZero:"0 results",modalResultsCountError:"Error",seeMoreResults:"See more results",navigateHint:"Navigate",selectHint:"Select",closeHint:"Close",chatTitle:"Chat",chatPlaceholder:"Type a message...",chatInputAriaLabel:"Chat message input",sendButtonLabel:"Send",sendButtonAriaLabel:"Send message",chatEmptyTitle:"Start a Conversation",chatEmptyDescription:"Send a message to begin chatting",userAvatar:"U",assistantAvatar:"AI",unknownError:"Unknown error",openChatAriaLabel:"Open chat",clearHistoryAriaLabel:"Clear history",minimizeAriaLabel:"Minimize",closeAriaLabel:"Close",historyTitle:"History",newChatButton:"New Chat",clearChatButton:"Clear Chat",toggleSidebarTitle:"Toggle sidebar",deleteChatTitle:"Delete chat",noChatsYet:"No chats yet",yesterday:"Yesterday",justNow:"Just now",minuteAgo:"{n} minute ago",minutesAgo:"{n} minutes ago",hourAgo:"{n} hour ago",hoursAgo:"{n} hours ago",loadingMessages:["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 u(l){if(!l||typeof l!="object")return v;const i={...v};for(const e of Object.keys(l)){const t=l[e];if(t!=null){if(e==="loadingMessages"){Array.isArray(t)&&t.length>0&&(i.loadingMessages=t.filter(s=>typeof s=="string"),i.loadingMessages.length===0&&(i.loadingMessages=v.loadingMessages));continue}typeof t=="string"&&(i[e]=t)}}return i}function x(l,i={}){return l.replace(/\{(\w+)\}/g,(e,t)=>Object.hasOwn(i,t)?String(i[t]):e)}function E(l,i){if(!l)return null;try{const e=JSON.parse(l);if(e===null||typeof e!="object"||Array.isArray(e))throw new Error("translations must be a JSON object");return e}catch(e){return console.error(`${i}: invalid translations attribute`,e),null}}const A=2500;function $(l,i){let e;function t(...s){clearTimeout(e),e=setTimeout(()=>{l(...s)},i)}return t.cancel=()=>clearTimeout(e),t}function c(l){const i=document.createElement("div");return i.textContent=l,i.innerHTML}function q(l){try{return decodeURI(l)}catch{return l}}function B(l){return new DOMParser().parseFromString(l,"text/html").documentElement.textContent||""}function se(l,i){const e=u(i),t=new Date(l),r=new Date().getTime()-t.getTime();if(r<6e4)return e.justNow;if(r<36e5){const n=Math.floor(r/6e4),o=n===1?e.minuteAgo:e.minutesAgo;return x(o,{n})}if(r<864e5){const n=Math.floor(r/36e5),o=n===1?e.hourAgo:e.hoursAgo;return x(o,{n})}return t.toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function O(l){return new Date(l).toLocaleDateString(void 0,{month:"short",day:"numeric"})}function H(l="id"){return`${l}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}function f(l,i){return l!==null?l:i}function b(l,i){return l===null?i:l==="true"||l===""}function C(l,i){if(l===null)return i;const e=Number.parseInt(l,10);return Number.isNaN(e)?i:e}function N(l,i){if(!(l===null||l===""))try{const e=JSON.parse(l);if(e===null||typeof e!="object"||Array.isArray(e))throw new Error("chat-query-rewrite must be a JSON object");const t=e,s={};return typeof t.enabled=="boolean"&&(s.enabled=t.enabled),typeof t.model=="string"&&(s.model=t.model),typeof t.rewritePrompt=="string"&&(s.rewritePrompt=t.rewritePrompt),s}catch(e){console.error(`${i}: invalid chat-query-rewrite attribute`,e);return}}function w(l,i){return new CustomEvent(l,{detail:i,bubbles:!0,composed:!0,cancelable:!0})}function M(l){if(!l)throw new Error("API URL is required");return new P(l)}const ie="@cf/meta/llama-3.3-70b-instruct-fp8-fast",re=`You rewrite a multi-turn chat into a single standalone search query for a retrieval system.
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Inputs: the full conversation in \`messages\`. The final user message is the one to answer; earlier messages are context only.
|
|
4
|
+
|
|
5
|
+
Rules:
|
|
6
|
+
- Output ONLY the rewritten query as plain text. No preamble, no quotes, no markdown, no explanation.
|
|
7
|
+
- Resolve pronouns and references (it, that, they, the second one, the previous one, etc.) using prior turns.
|
|
8
|
+
- Inline any entities, names, versions, products, or constraints from earlier turns that the final message depends on.
|
|
9
|
+
- Preserve the user's original language and terminology. Do not translate.
|
|
10
|
+
- Do not invent facts, sources, dates, or details not present in the conversation.
|
|
11
|
+
- If the final user message is already fully self-contained, return it unchanged (modulo trivial cleanup).
|
|
12
|
+
- Drop greetings, thanks, and meta questions about the assistant itself; keep only the information need.
|
|
13
|
+
- Keep it concise — a search query, not a sentence. Aim for under 200 characters when possible.
|
|
14
|
+
|
|
15
|
+
Return only the rewritten query.`;function ae(l){let i="message";const e=[];for(const t of l.split(`
|
|
16
|
+
`)){const s=t.endsWith("\r")?t.slice(0,-1):t;if(s===""||s.startsWith(":"))continue;const r=s.indexOf(":"),n=r===-1?s:s.slice(0,r);let o=r===-1?"":s.slice(r+1);o.startsWith(" ")&&(o=o.slice(1)),n==="event"?i=o:n==="data"&&e.push(o)}return e.length===0?null:{event:i,data:e.join(`
|
|
17
|
+
`)}}function k(l){return l!==null&&typeof l=="object"&&!Array.isArray(l)}function D(...l){const i={};for(const e of l)if(e)for(const[t,s]of Object.entries(e)){const r=i[t];k(r)&&k(s)?i[t]=D(r,s):i[t]=s}return i}function ne(l,i){if(!k(i))return l;const e=new URLSearchParams;for(const[h,d]of Object.entries(i))d!=null&&e.append(h,String(d));const t=e.toString();if(!t)return l;const s=l.indexOf("#"),r=s===-1?l:l.slice(0,s),n=s===-1?"":l.slice(s),o=r.includes("?")?"&":"?";return`${r}${o}${t}${n}`}function oe(l){if(!k(l))return{};const i={};for(const[e,t]of Object.entries(l))t!=null&&(i[e]=String(t));return i}function le(l){return k(l)?l:void 0}class P{constructor(i){a(this,"activeRequests",new Map);a(this,"baseUrl");this.baseUrl=i.replace(/\/$/,"")}request(i,e,t,s){const r=e==="search"?"snippet-search":"snippet-chat-completions",n=ne(`${this.baseUrl}/${e}`,s?.queryParams);return fetch(n,{method:"POST",body:JSON.stringify(D(le(s?.body),i)),headers:{...oe(s?.headers),"Content-Type":"application/json",Accept:i.stream?"text/event-stream":"application/json","cf-ai-search-source":r},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({messages:[{role:"user",content:i}],stream:!1,ai_search_options:{retrieval:{metadata_only:!0,max_num_results:e.maxResults??30}}},"search",r,e.request);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(h=>({type:"result",id:h.id,title:B(h.item.metadata?.title),description:h.item.metadata?.description?B(h.item.metadata?.description):"",timestamp:h.item.timestamp??void 0,url:h.item.key,image:h.item.metadata?.image||void 0,metadata:{...h.item.metadata,instance_id:h.instance_id}}));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({messages:[{role:"user",content:i}],stream:!0,...e.maxResults!==void 0&&{max_num_results:e.maxResults}},"ai-search",r,e.request);if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);if(!n.body)throw new Error("Response body is empty");let o="";const h=n.body.getReader(),d=new TextDecoder;for(;;){const{done:m,value:y}=await h.read();if(m)break;const z=d.decode(y,{stream:!0});o+=z}yield{type:"result",id:"",title:"",description:o.replaceAll("data: ","").trim().split(`
|
|
18
|
+
|
|
19
|
+
`).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=e?.stream??!0,o={messages:[...e?.history??[],{role:"user",content:i}],stream:r};if(e?.queryRewrite){const d=typeof e.queryRewrite=="object"?e.queryRewrite:{};o.ai_search_options={query_rewrite:{enabled:!0,model:d.model??ie,rewrite_prompt:d.rewritePrompt??re}}}const h=await this.request(o,"chat/completions",s);if(!h.ok)throw new Error(`HTTP error! status: ${h.status}`);if(!h.body)throw new Error("Response body is empty");if(!r){yield{type:"text",message:(await h.json()).choices.map(p=>p.message.content).join("")};return}yield*this.parseChatStream(h.body)}async*parseChatStream(i){const e=i.getReader(),t=new TextDecoder;let s="";const r=n=>{const o=ae(n);if(!o||o.event==="chunks")return null;if(o.data==="[DONE]")return"done";try{const d=JSON.parse(o.data).choices?.[0]?.delta?.content;if(typeof d=="string"&&d.length>0)return{type:"text",message:d}}catch(h){console.error("AISearchClient: failed to parse SSE chat chunk",h)}return null};try{for(;;){const{done:n,value:o}=await e.read();if(n)break;s+=t.decode(o,{stream:!0});let h=s.indexOf(`
|
|
20
|
+
|
|
21
|
+
`);for(;h!==-1;){const d=s.slice(0,h);s=s.slice(h+2);const p=r(d);if(p==="done")return;p&&(yield p),h=s.indexOf(`
|
|
22
|
+
|
|
23
|
+
`)}}if(s+=t.decode(),s.trim().length>0){const n=r(s);n&&n!=="done"&&(yield n)}}catch(n){if(n.name==="AbortError")return;throw n}finally{e.releaseLock()}}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 ce="0.0.39",L=`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
24
|
<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
25
|
<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>`,
|
|
26
|
+
</svg></a>`,he=2e4,de=20,pe="/stats";function U(){return typeof document<"u"&&typeof window<"u"}class I{constructor(i,e={}){a(this,"baseUrl");a(this,"endpoint");a(this,"snippetVersion");a(this,"flushIntervalMs");a(this,"maxBufferSize");a(this,"buffer",[]);a(this,"flushTimer",null);a(this,"destroyed",!1);a(this,"boundUnloadHandler");a(this,"boundVisibilityHandler");this.baseUrl=i.replace(/\/$/,""),this.endpoint=e.endpoint??pe,this.snippetVersion=e.snippetVersion??ce,this.flushIntervalMs=e.flushIntervalMs??he,this.maxBufferSize=Math.max(1,e.maxBufferSize??de),this.boundUnloadHandler=()=>this.flushBeacon(),this.boundVisibilityHandler=()=>{typeof document<"u"&&document.visibilityState==="hidden"&&this.flushBeacon()},U()&&(window.addEventListener("pagehide",this.boundUnloadHandler),document.addEventListener("visibilitychange",this.boundVisibilityHandler))}trackSearch(i,e){this.track({inputQuery:i,snippetVersion:this.snippetVersion,totalResult:e})}trackClick(i,e,t,s){this.track({inputQuery:i,snippetVersion:this.snippetVersion,totalResult:e,clickedResultId:t,clickPosition:s,clickViewMore:!1})}trackViewMore(i,e){this.track({inputQuery:i,snippetVersion:this.snippetVersion,totalResult:e,clickViewMore:!0})}track(i){if(!this.destroyed){if(this.buffer.push(i),this.buffer.length>=this.maxBufferSize){this.flush();return}this.scheduleFlush()}}flush(){const i=this.drainBuffer();if(i.length===0)return;const e=JSON.stringify({events:i});fetch(this.buildUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:e,keepalive:!0}).catch(t=>{console.log(t)})}flushBeacon(){const i=this.drainBuffer();if(i.length===0)return;const e=JSON.stringify({events:i}),t=this.buildUrl();if(typeof navigator<"u"&&typeof navigator.sendBeacon=="function")try{const s=new Blob([e],{type:"application/json"});if(navigator.sendBeacon(t,s))return}catch{}typeof fetch<"u"&&fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:e,keepalive:!0}).catch(()=>{})}destroy(){this.destroyed||(this.destroyed=!0,this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null),U()&&(window.removeEventListener("pagehide",this.boundUnloadHandler),document.removeEventListener("visibilitychange",this.boundVisibilityHandler)),this.flushBeacon())}scheduleFlush(){this.flushTimer!==null||this.destroyed||(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush()},this.flushIntervalMs))}drainBuffer(){if(this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.buffer.length===0)return[];const i=this.buffer;return this.buffer=[],i}buildUrl(){const i=this.endpoint.startsWith("/")?this.endpoint:`/${this.endpoint}`;return`${this.baseUrl}${i}`}}const _=`
|
|
7
27
|
/* Chat container */
|
|
8
28
|
.chat-container {
|
|
9
29
|
display: flex;
|
|
@@ -46,6 +66,7 @@
|
|
|
46
66
|
gap: var(--search-snippet-spacing-sm);
|
|
47
67
|
max-width: 85%;
|
|
48
68
|
animation: slideIn var(--search-snippet-animation-duration) ease-out;
|
|
69
|
+
animation-fill-mode: both;
|
|
49
70
|
}
|
|
50
71
|
|
|
51
72
|
@keyframes slideIn {
|
|
@@ -116,6 +137,9 @@
|
|
|
116
137
|
border-radius: var(--search-snippet-border-radius);
|
|
117
138
|
word-wrap: break-word;
|
|
118
139
|
overflow-wrap: break-word;
|
|
140
|
+
/* Isolate layout cost of bubble height changes during streaming so
|
|
141
|
+
siblings don't reflow. */
|
|
142
|
+
contain: layout style;
|
|
119
143
|
}
|
|
120
144
|
|
|
121
145
|
.chat-message-user .chat-message-bubble {
|
|
@@ -754,9 +778,9 @@
|
|
|
754
778
|
padding: var(--search-snippet-spacing-xs) 0;
|
|
755
779
|
text-align: center;
|
|
756
780
|
}
|
|
757
|
-
`;function
|
|
758
|
-
`),t=[];let s=!1,r="";for(let n=0;n<e.length;n++){const
|
|
759
|
-
`)}function S(l){let i=l;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
|
|
781
|
+
`;function ue(l){let i=l;i=ge(i),i=i.replace(/```([\s\S]*?)```/g,(n,o)=>`<pre><code>${o.trim()}</code></pre>`);const e=i.split(`
|
|
782
|
+
`),t=[];let s=!1,r="";for(let n=0;n<e.length;n++){const o=e[n],h=o.match(/^(#{1,6})\s+(.+)$/);if(h){const m=h[1].length,y=h[2];t.push(`<h${m}>${S(y)}</h${m}>`);continue}if(o.match(/^---+$/)){t.push("<hr />");continue}if(o.match(/^>\s+/)){const m=o.replace(/^>\s+/,"");t.push(`<blockquote>${S(m)}</blockquote>`);continue}const d=o.match(/^[-*]\s+(.+)$/);if(d){(!s||r!=="ul")&&(s&&t.push(`</${r}>`),t.push("<ul>"),s=!0,r="ul"),t.push(`<li>${S(d[1])}</li>`);continue}const p=o.match(/^\d+\.\s+(.+)$/);if(p){(!s||r!=="ol")&&(s&&t.push(`</${r}>`),t.push("<ol>"),s=!0,r="ol"),t.push(`<li>${S(p[1])}</li>`);continue}if(s&&(t.push(`</${r}>`),s=!1,r=""),o.trim()===""){t.push("<br />");continue}t.push(`<p>${S(o)}</p>`)}return s&&t.push(`</${r}>`),t.join(`
|
|
783
|
+
`)}function S(l){let i=l;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 ge(l){const i={"&":"&","<":"<",">":">",'"':""","'":"'"};return l.replace(/[&<>"']/g,e=>i[e]||e)}const me=64;class V{constructor(i,e,t){a(this,"container");a(this,"client");a(this,"props");a(this,"translations");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,"pendingScrollFrame",null);a(this,"handleInputResize",null);a(this,"handleInputKeydown",null);a(this,"handleSendClick",null);this.container=i,this.client=e,this.props=t,this.translations=u(t.translations),this.render(),this.attachEventListeners()}render(){const i=this.translations;this.container.innerHTML=`
|
|
760
784
|
<div class="chat-container">
|
|
761
785
|
<div class="chat-messages">
|
|
762
786
|
${this.renderEmptyStateHTML()}
|
|
@@ -765,13 +789,13 @@
|
|
|
765
789
|
<div class="chat-input-wrapper">
|
|
766
790
|
<textarea
|
|
767
791
|
class="chat-input"
|
|
768
|
-
placeholder="${
|
|
769
|
-
aria-label="${
|
|
792
|
+
placeholder="${c(this.props.placeholder||i.chatPlaceholder)}"
|
|
793
|
+
aria-label="${c(i.chatInputAriaLabel)}"
|
|
770
794
|
style="height: 40px;"
|
|
771
795
|
rows="1"
|
|
772
796
|
></textarea>
|
|
773
|
-
<button class="button chat-send-button" aria-label="${
|
|
774
|
-
<span>${
|
|
797
|
+
<button class="button chat-send-button" aria-label="${c(i.sendButtonAriaLabel)}">
|
|
798
|
+
<span>${c(i.sendButtonLabel)}</span>
|
|
775
799
|
</button>
|
|
776
800
|
</div>
|
|
777
801
|
</div>
|
|
@@ -781,26 +805,26 @@
|
|
|
781
805
|
<svg class="chat-empty-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
782
806
|
<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>
|
|
783
807
|
</svg>
|
|
784
|
-
<div class="chat-empty-title">${
|
|
808
|
+
<div class="chat-empty-title">${c(i.chatEmptyTitle)}</div>
|
|
785
809
|
<div class="chat-empty-description">
|
|
786
|
-
${
|
|
810
|
+
${c(i.chatEmptyDescription)}
|
|
787
811
|
</div>
|
|
788
812
|
</div>
|
|
789
|
-
`}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:
|
|
790
|
-
<div class="chat-message ${s}">
|
|
791
|
-
<div class="chat-message-avatar">${
|
|
813
|
+
`}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=this.messages.map(o=>({role:o.role,content:o.content})),t=this.resolveQueryRewriteOption(e),s={id:H("msg"),role:"user",content:i,timestamp:Date.now()};this.addMessage(s),this.renderMessages(!0),this.setStreamingState(!0);const r=H("msg"),n={id:r,role:"assistant",content:"",timestamp:Date.now()};this.addMessage(n),this.currentStreamingMessageId=r,this.renderMessages(!0);try{const o=this.client.chat(i,{history:e,queryRewrite:t});let h="";for await(const p of o)if(p.type==="text"&&p.message)h+=p.message,this.updateStreamingMessage(r,h);else if(p.type==="error"){this.showErrorInMessage(r,p.message||this.translations.unknownError);break}const d=this.messages.findIndex(p=>p.id===r);d!==-1&&(this.messages[d].content=h),this.container.dispatchEvent(w("message",{message:n}))}catch(o){this.showErrorInMessage(r,o.message),this.container.dispatchEvent(w("error",{error:{message:o.message,code:"CHAT_ERROR"}}))}finally{this.setStreamingState(!1),this.renderMessages(),this.currentStreamingMessageId=null}}resolveQueryRewriteOption(i){const e=this.props.chatQueryRewrite;return e?.enabled===!1||i.length===0?!1:e&&(e.model!==void 0||e.rewritePrompt!==void 0)?{model:e.model,rewritePrompt:e.rewritePrompt}:!0}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.updateStreamingMessageDOM(i,e)||this.renderMessages(!0))}updateStreamingMessageDOM(i,e){if(!this.messagesContainer)return!1;const t=this.messagesContainer.querySelector(`[data-message-id="${CSS.escape(i)}"]`);if(!t)return!1;const s=t.querySelector(".chat-message-bubble");if(!s)return!1;const r=this.isNearBottom();let n=s.querySelector(".chat-message-text");if(!n){const o=document.createElement("div");o.className="chat-message-text";const h=s.querySelector(".chat-streaming");h?s.insertBefore(o,h):s.appendChild(o),n=o}return n.textContent=e,r&&this.scheduleScrollToBottom(),!0}showErrorInMessage(i,e){const t=this.messages.findIndex(s=>s.id===i);t!==-1&&(this.messages[t].content=`${this.translations.errorPrefix} ${e}`,this.renderMessages())}renderMessages(i=!1){if(!this.messagesContainer)return;if(this.messages.length===0){this.messagesContainer.innerHTML=this.renderEmptyStateHTML();return}const e=this.messages.map(t=>this.renderMessage(t,i&&t.id===this.currentStreamingMessageId)).join("");this.messagesContainer.innerHTML=e,this.scheduleScrollToBottom()}renderMessage(i,e=!1){const t=this.translations,s=`chat-message-${i.role}`,r=i.role==="user"?t.userAvatar:t.assistantAvatar,n=t.loadingMessages[this.loadingMessageIndex]??"",o=i.content?e?c(i.content):ue(i.content):"";return`
|
|
814
|
+
<div class="chat-message ${s}" data-message-id="${c(i.id)}">
|
|
815
|
+
<div class="chat-message-avatar">${c(r)}</div>
|
|
792
816
|
<div class="chat-message-content">
|
|
793
817
|
<div class="chat-message-bubble">
|
|
794
|
-
${
|
|
795
|
-
${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">${
|
|
818
|
+
${o?`<div class="chat-message-text">${o}</div>`:""}
|
|
819
|
+
${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">${c(n)}</span></div>`:""}
|
|
796
820
|
</div>
|
|
797
821
|
<div class="chat-message-metadata">
|
|
798
|
-
<span class="chat-message-time">${
|
|
822
|
+
<span class="chat-message-time">${c(se(i.timestamp,this.translations))}</span>
|
|
799
823
|
</div>
|
|
800
824
|
</div>
|
|
801
825
|
</div>
|
|
802
|
-
`}
|
|
803
|
-
${
|
|
826
|
+
`}isNearBottom(){const i=this.messagesContainer;return i?i.scrollHeight-i.scrollTop-i.clientHeight<me:!0}scheduleScrollToBottom(){this.messagesContainer&&this.pendingScrollFrame===null&&(this.pendingScrollFrame=requestAnimationFrame(()=>{this.pendingScrollFrame=null;const i=this.messagesContainer;i&&(i.scrollTop=i.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>${c(this.translations.sendButtonLabel)}</span>`),i?this.startLoadingMessages():this.clearLoadingMessages()}startLoadingMessages(){this.clearLoadingMessages();const i=this.translations.loadingMessages;this.loadingMessageIndex=Math.floor(Math.random()*i.length),this.loadingMessageInterval=setInterval(()=>{const e=this.translations.loadingMessages;if(this.loadingMessageIndex=(this.loadingMessageIndex+1)%e.length,!this.isStreaming)return;this.updateLoadingTextDOM(e[this.loadingMessageIndex]??"")||this.renderMessages(!0)},A)}updateLoadingTextDOM(i){if(!this.messagesContainer||!this.currentStreamingMessageId)return!1;const e=this.messagesContainer.querySelector(`[data-message-id="${CSS.escape(this.currentStreamingMessageId)}"]`);if(!e)return!1;const t=e.querySelector(".chat-streaming .loading-text");return t?(t.textContent=i,!0):!1}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()}setProps(i){this.props=i,this.translations=u(i.translations),this.detachEventListeners(),this.render(),this.attachEventListeners(),this.renderMessages(this.isStreaming),this.isStreaming&&this.setStreamingState(!0)}detachEventListeners(){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}destroy(){this.clearLoadingMessages(),this.pendingScrollFrame!==null&&(cancelAnimationFrame(this.pendingScrollFrame),this.pendingScrollFrame=null),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 j="chat-bubble-snippet";class F 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,"translationsOverride",null);a(this,"resolvedTranslations",u(null));a(this,"chatQueryRewriteOverride",null);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","translations","chat-query-rewrite"]}connectedCallback(){this.syncTranslationsFromAttribute(),this.render(),this.initializeClient(),this.dispatchEvent(w("ready",void 0))}disconnectedCallback(){this.cleanup()}attributeChangedCallback(e,t,s){t!==s&&(e==="api-url"?this.initializeClient():e==="theme"?this.updateTheme(s):e==="translations"&&(this.syncTranslationsFromAttribute(),this.isConnected&&this.rerenderAfterTranslationsChange()))}get translations(){return this.translationsOverride}get chatQueryRewrite(){return this.chatQueryRewriteOverride}set chatQueryRewrite(e){this.chatQueryRewriteOverride=e??null,this.chatView&&this.chatView.setProps(this.getProps())}set translations(e){this.translationsOverride=e??null,this.resolvedTranslations=u(this.translationsOverride),this.isConnected&&this.rerenderAfterTranslationsChange()}syncTranslationsFromAttribute(){if(this.translationsOverride){this.resolvedTranslations=u(this.translationsOverride);return}const e=E(this.getAttribute("translations"),"ChatBubbleSnippet");this.resolvedTranslations=u(e)}rerenderAfterTranslationsChange(){const e=this.isExpanded,t=this.isMinimized;this.removeEventListeners();const s=this.chatView?this.shadow.querySelector(".chat-content"):null;s?.parentNode&&s.parentNode.removeChild(s),this.render(),e&&(this.shadow.querySelector(".bubble-button")?.classList.add("hidden"),this.shadow.querySelector(".chat-window")?.classList.add("expanded"),t&&this.shadow.querySelector(".chat-window")?.classList.add("minimized"));const r=this.shadow.querySelector(".chat-window");if(this.chatView&&s&&r){const n=r.querySelector(".chat-content");n?r.replaceChild(s,n):r.appendChild(s),this.chatView.setProps(this.getProps())}else e&&this.initializeChatView()}getProps(){const e=this.resolvedTranslations;return{apiUrl:f(this.getAttribute("api-url"),""),placeholder:f(this.getAttribute("placeholder"),e.chatPlaceholder),theme:f(this.getAttribute("theme"),"auto"),hideBranding:b(this.getAttribute("hide-branding"),!1),translations:this.translationsOverride??void 0,chatQueryRewrite:this.resolveChatQueryRewrite()}}resolveChatQueryRewrite(){return this.chatQueryRewriteOverride!==null?this.chatQueryRewriteOverride:N(this.getAttribute("chat-query-rewrite"),"ChatBubbleSnippet")}initializeClient(){const e=this.getProps();if(!e.apiUrl){console.error("ChatBubbleSnippet: api-url attribute is required"),this.client=null;return}try{this.client=M(e.apiUrl)}catch(t){console.error("ChatBubbleSnippet:",t)}}render(){const e=document.createElement("style");e.textContent=`${T}
|
|
827
|
+
${_}
|
|
804
828
|
${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`
|
|
805
829
|
.chat-bubble-widget {
|
|
806
830
|
position: var(--chat-bubble-position);
|
|
@@ -940,7 +964,7 @@ ${this.getBubbleStyles()}`,this.container=document.createElement("div"),this.con
|
|
|
940
964
|
}
|
|
941
965
|
}
|
|
942
966
|
`}getBaseHTML(){const e=this.getProps(),t=this.resolvedTranslations,s=e.hideBranding?"":`<div class="powered-by">${L}</div>`;return`
|
|
943
|
-
<button class="bubble-button" aria-label="${
|
|
967
|
+
<button class="bubble-button" aria-label="${c(t.openChatAriaLabel)}">
|
|
944
968
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
945
969
|
<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>
|
|
946
970
|
</svg>
|
|
@@ -951,21 +975,21 @@ ${this.getBubbleStyles()}`,this.container=document.createElement("div"),this.con
|
|
|
951
975
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
952
976
|
<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>
|
|
953
977
|
</svg>
|
|
954
|
-
<span>${
|
|
978
|
+
<span>${c(t.chatTitle)}</span>
|
|
955
979
|
</div>
|
|
956
980
|
<div class="chat-header-actions">
|
|
957
|
-
<button class="icon-button clear-button" aria-label="${
|
|
981
|
+
<button class="icon-button clear-button" aria-label="${c(t.clearHistoryAriaLabel)}">
|
|
958
982
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
959
983
|
<polyline points="3 6 5 6 21 6"></polyline>
|
|
960
984
|
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
|
|
961
985
|
</svg>
|
|
962
986
|
</button>
|
|
963
|
-
<button class="icon-button minimize-button" aria-label="${
|
|
987
|
+
<button class="icon-button minimize-button" aria-label="${c(t.minimizeAriaLabel)}">
|
|
964
988
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
965
989
|
<line x1="5" y1="12" x2="19" y2="12"></line>
|
|
966
990
|
</svg>
|
|
967
991
|
</button>
|
|
968
|
-
<button class="icon-button close-button" aria-label="${
|
|
992
|
+
<button class="icon-button close-button" aria-label="${c(t.closeAriaLabel)}">
|
|
969
993
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
970
994
|
<line x1="18" y1="6" x2="6" y2="18"></line>
|
|
971
995
|
<line x1="6" y1="6" x2="18" y2="18"></line>
|
|
@@ -978,10 +1002,10 @@ ${this.getBubbleStyles()}`,this.container=document.createElement("div"),this.con
|
|
|
978
1002
|
</div>
|
|
979
1003
|
`}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){const s=this.resolvedTranslations;e.innerHTML=`
|
|
980
1004
|
<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);">
|
|
981
|
-
<strong>${
|
|
1005
|
+
<strong>${c(s.errorPrefix)}</strong> ${c(s.missingApiUrlError)}
|
|
982
1006
|
</div>
|
|
983
|
-
`;return}const t=this.getProps();this.chatView=new
|
|
984
|
-
${
|
|
1007
|
+
`;return}const t=this.getProps();this.chatView=new V(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(j)||customElements.define(j,F);const K="chat-page-snippet",Q="chat-page-sessions";class G 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,"translationsOverride",null);a(this,"resolvedTranslations",u(null));a(this,"chatQueryRewriteOverride",null);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","translations","chat-query-rewrite"]}connectedCallback(){this.syncTranslationsFromAttribute(),this.render(),this.initializeClient(),this.setupView(),this.dispatchEvent(w("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):e==="translations"&&(this.syncTranslationsFromAttribute(),this.isConnected&&this.rerenderAfterTranslationsChange()))}get translations(){return this.translationsOverride}get chatQueryRewrite(){return this.chatQueryRewriteOverride}set chatQueryRewrite(e){this.chatQueryRewriteOverride=e??null,this.chatView&&this.chatView.setProps(this.getProps())}set translations(e){this.translationsOverride=e??null,this.resolvedTranslations=u(this.translationsOverride),this.refreshDefaultSessionTitles(),this.isConnected&&this.rerenderAfterTranslationsChange()}syncTranslationsFromAttribute(){if(this.translationsOverride){this.resolvedTranslations=u(this.translationsOverride),this.refreshDefaultSessionTitles();return}const e=E(this.getAttribute("translations"),"ChatPageSnippet");this.resolvedTranslations=u(e),this.refreshDefaultSessionTitles()}refreshDefaultSessionTitles(){if(this.sessions.length===0)return;const e=this.resolvedTranslations.newChatButton;let t=!1;for(const s of this.sessions)s.titleIsDefault&&s.title!==e&&(s.title=e,t=!0);t&&this.saveSessions()}rerenderAfterTranslationsChange(){this.removeEventListeners();const e=this.chatView?this.shadow.querySelector(".container"):null;e?.parentNode&&e.parentNode.removeChild(e),this.render(),this.attachEventListeners(),this.renderChatList();const t=this.shadow.querySelector(".chat-page-content");if(this.chatView&&e&&t){const s=t.querySelector(".container");s?t.replaceChild(e,s):t.appendChild(e),this.chatView.setProps(this.getProps()),this.handleMessageEvent=()=>{this.saveCurrentSession(),this.updateSessionTitle(),this.renderChatList()},e.addEventListener("message",this.handleMessageEvent)}}getProps(){const e=this.resolvedTranslations;return{apiUrl:f(this.getAttribute("api-url"),""),placeholder:f(this.getAttribute("placeholder"),e.chatPlaceholder),theme:f(this.getAttribute("theme"),"auto"),hideBranding:b(this.getAttribute("hide-branding"),!1),translations:this.translationsOverride??void 0,chatQueryRewrite:this.resolveChatQueryRewrite()}}resolveChatQueryRewrite(){return this.chatQueryRewriteOverride!==null?this.chatQueryRewriteOverride:N(this.getAttribute("chat-query-rewrite"),"ChatPageSnippet")}initializeClient(){const e=this.getProps();if(!e.apiUrl){console.error("ChatPageSnippet: api-url attribute is required"),this.client=null;return}try{this.client=M(e.apiUrl)}catch(t){console.error("ChatPageSnippet:",t)}}render(){const e=document.createElement("style");e.textContent=`${T}
|
|
1008
|
+
${_}
|
|
985
1009
|
${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`
|
|
986
1010
|
:host {
|
|
987
1011
|
display: block;
|
|
@@ -1258,13 +1282,13 @@ ${this.getPageStyles()}`,this.container=document.createElement("div"),this.conta
|
|
|
1258
1282
|
`}getBaseHTML(){const e=this.getProps(),t=this.resolvedTranslations,s=e.hideBranding?"":`<div class="powered-by">${L}</div>`;return`
|
|
1259
1283
|
<div class="chat-sidebar">
|
|
1260
1284
|
<div class="sidebar-header">
|
|
1261
|
-
<span class="sidebar-title">${
|
|
1285
|
+
<span class="sidebar-title">${c(t.historyTitle)}</span>
|
|
1262
1286
|
</div>
|
|
1263
1287
|
<button class="new-chat-button">
|
|
1264
1288
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
1265
1289
|
<path d="M12 5v14M5 12h14"></path>
|
|
1266
1290
|
</svg>
|
|
1267
|
-
${
|
|
1291
|
+
${c(t.newChatButton)}
|
|
1268
1292
|
</button>
|
|
1269
1293
|
<div class="chat-list"></div>
|
|
1270
1294
|
${s}
|
|
@@ -1272,7 +1296,7 @@ ${this.getPageStyles()}`,this.container=document.createElement("div"),this.conta
|
|
|
1272
1296
|
<div class="chat-main">
|
|
1273
1297
|
<div class="chat-page-header">
|
|
1274
1298
|
<div class="chat-page-header-left">
|
|
1275
|
-
<button class="toggle-sidebar-button" title="${
|
|
1299
|
+
<button class="toggle-sidebar-button" title="${c(t.toggleSidebarTitle)}">
|
|
1276
1300
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
1277
1301
|
<path d="M3 12h18M3 6h18M3 18h18"></path>
|
|
1278
1302
|
</svg>
|
|
@@ -1281,7 +1305,7 @@ ${this.getPageStyles()}`,this.container=document.createElement("div"),this.conta
|
|
|
1281
1305
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
1282
1306
|
<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>
|
|
1283
1307
|
</svg>
|
|
1284
|
-
<span>${
|
|
1308
|
+
<span>${c(t.chatTitle)}</span>
|
|
1285
1309
|
</div>
|
|
1286
1310
|
</div>
|
|
1287
1311
|
<div class="chat-page-header-actions">
|
|
@@ -1289,7 +1313,7 @@ ${this.getPageStyles()}`,this.container=document.createElement("div"),this.conta
|
|
|
1289
1313
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
1290
1314
|
<path d="M3 6h18M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
|
|
1291
1315
|
</svg>
|
|
1292
|
-
${
|
|
1316
|
+
${c(t.clearChatButton)}
|
|
1293
1317
|
</button>
|
|
1294
1318
|
</div>
|
|
1295
1319
|
</div>
|
|
@@ -1299,9 +1323,9 @@ ${this.getPageStyles()}`,this.container=document.createElement("div"),this.conta
|
|
|
1299
1323
|
</div>
|
|
1300
1324
|
`}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){if(e){const s=this.resolvedTranslations;e.innerHTML=`
|
|
1301
1325
|
<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);">
|
|
1302
|
-
<strong>${
|
|
1326
|
+
<strong>${c(s.errorPrefix)}</strong> ${c(s.missingApiUrlError)}
|
|
1303
1327
|
</div>
|
|
1304
|
-
`}return}if(!e)return;const t=this.getProps();if(this.chatView=new
|
|
1328
|
+
`}return}if(!e)return;const t=this.getProps();if(this.chatView=new V(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(Q);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(Q,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(r=>r.id===this.currentSessionId);if(!e||e.messages.length===0||!(e.titleIsDefault??e.title===this.resolvedTranslations.newChatButton))return;const s=e.messages.find(r=>r.role==="user");s&&(e.title=s.content.slice(0,50)+(s.content.length>50?"...":""),e.titleIsDefault=!1,this.saveSessions())}createNewChat(){this.saveCurrentSession();const e={id:this.generateSessionId(),title:this.resolvedTranslations.newChatButton,messages:[],createdAt:Date.now(),updatedAt:Date.now(),titleIsDefault:!0};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=this.resolvedTranslations.newChatButton,e.titleIsDefault=!0,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)return;const t=this.resolvedTranslations;if(this.sessions.length===0){e.innerHTML=`<div class="chat-list-empty">${this.escapeHTML(t.noChatsYet)}</div>`;return}e.innerHTML=this.sessions.map(s=>this.renderChatListItem(s)).join("")}renderChatListItem(e){const t=e.id===this.currentSessionId,s=this.formatDate(e.updatedAt),r=this.resolvedTranslations.deleteChatTitle;return`
|
|
1305
1329
|
<div class="chat-list-item ${t?"active":""}" data-session-id="${e.id}">
|
|
1306
1330
|
<div class="chat-list-item-content">
|
|
1307
1331
|
<div class="chat-list-item-title">${this.escapeHTML(e.title)}</div>
|
|
@@ -1313,7 +1337,7 @@ ${this.getPageStyles()}`,this.container=document.createElement("div"),this.conta
|
|
|
1313
1337
|
</svg>
|
|
1314
1338
|
</button>
|
|
1315
1339
|
</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?this.resolvedTranslations.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(
|
|
1340
|
+
`}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?this.resolvedTranslations.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(K)||customElements.define(K,G);const ve=`
|
|
1317
1341
|
/* Search view states */
|
|
1318
1342
|
.search-view {
|
|
1319
1343
|
transition: var(--search-snippet-transition-slow);
|
|
@@ -1683,8 +1707,8 @@ a.search-result-item:focus-visible {
|
|
|
1683
1707
|
border-radius: 2px;
|
|
1684
1708
|
font-weight: var(--search-snippet-font-weight-medium);
|
|
1685
1709
|
}
|
|
1686
|
-
`,
|
|
1687
|
-
${
|
|
1710
|
+
`,Y="search-bar-snippet",W=10,J=50;class R extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"client",null);a(this,"stats",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,"translationsOverride",null);a(this,"resolvedTranslations",u(null));a(this,"lastSearchQuery","");a(this,"lastSearchTotal",0);a(this,"handleInputChange",null);a(this,"handleInputKeydownEnter",null);a(this,"handleInputKeydownEscape",null);a(this,"handleSearchButtonClick",null);a(this,"handleResultClick",null);a(this,"handleSeeMoreClick",null);this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["api-url","placeholder","max-results","max-render-results","debounce-ms","theme","hide-branding","show-url","show-date","hide-thumbnails","see-more","disable-analytics","request-options","translations"]}connectedCallback(){this.syncTranslationsFromAttribute(),this.initializeClient(),this.render(),this.dispatchEvent(w("ready",void 0))}disconnectedCallback(){this.cleanup()}attributeChangedCallback(e,t,s){t!==s&&(e==="api-url"||e==="disable-analytics"?this.initializeClient():e==="theme"?this.updateTheme(s):e==="translations"&&(this.syncTranslationsFromAttribute(),this.isConnected&&this.rerender()))}get translations(){return this.translationsOverride}set translations(e){this.translationsOverride=e??null,this.resolvedTranslations=u(this.translationsOverride),this.isConnected&&this.rerender()}rerender(){const e=this.inputElement?.value??"";this.render(),e&&this.inputElement&&(this.inputElement.value=e,e.trim().length>0&&this.performSearch(e.trim()))}syncTranslationsFromAttribute(){if(this.translationsOverride){this.resolvedTranslations=u(this.translationsOverride);return}const e=E(this.getAttribute("translations"),"SearchBarSnippet");this.resolvedTranslations=u(e)}getProps(){const e=this.resolvedTranslations;return{apiUrl:f(this.getAttribute("api-url"),""),placeholder:f(this.getAttribute("placeholder"),e.placeholder),maxResults:C(this.getAttribute("max-results"),J),maxRenderResults:C(this.getAttribute("max-render-results"),W),debounceMs:C(this.getAttribute("debounce-ms"),300),theme:f(this.getAttribute("theme"),"auto"),hideBranding:b(this.getAttribute("hide-branding"),!1),showUrl:b(this.getAttribute("show-url"),!1),showDate:b(this.getAttribute("show-date"),!1),hideThumbnails:b(this.getAttribute("hide-thumbnails"),!1),seeMore:f(this.getAttribute("see-more"),""),disableAnalytics:b(this.getAttribute("disable-analytics"),!1),translations:this.translationsOverride??void 0}}getRequestOptions(){const e=this.getAttribute("request-options");if(e)try{const t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))throw new Error("request-options must be a JSON object");return t}catch(t){console.error("SearchBarSnippet: invalid request-options attribute",t);return}}initializeClient(){const e=this.getProps();if(!e.apiUrl){console.error("SearchBarSnippet: api-url attribute is required"),this.client=null,this.destroyStatsClient(),this.showMissingApiUrlError();return}try{this.client=M(e.apiUrl),this.destroyStatsClient(),e.disableAnalytics||(this.stats=new I(e.apiUrl))}catch(t){console.error("SearchBarSnippet:",t)}}destroyStatsClient(){this.stats&&(this.stats.destroy(),this.stats=null)}render(){const e=this.getProps(),t=this.resolvedTranslations,s=n=>this.performSearch(n);this.debouncedSearch=$(s,e.debounceMs||400);const r=document.createElement("style");r.textContent=`${T}
|
|
1711
|
+
${ve}`,this.container=document.createElement("div"),this.container.className="container",this.container.innerHTML=`
|
|
1688
1712
|
<div class="search-view">
|
|
1689
1713
|
<div class="search-input-wrapper">
|
|
1690
1714
|
<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>
|
|
@@ -1692,12 +1716,12 @@ ${re}`,this.container=document.createElement("div"),this.container.className="co
|
|
|
1692
1716
|
type="text"
|
|
1693
1717
|
name="search-input"
|
|
1694
1718
|
class="search-input"
|
|
1695
|
-
placeholder="${
|
|
1696
|
-
aria-label="${
|
|
1719
|
+
placeholder="${c(e.placeholder||t.placeholder)}"
|
|
1720
|
+
aria-label="${c(t.searchInputAriaLabel)}"
|
|
1697
1721
|
autocomplete="off"
|
|
1698
1722
|
/>
|
|
1699
|
-
<button class="button search-submit-button" aria-label="${
|
|
1700
|
-
<span>${
|
|
1723
|
+
<button class="button search-submit-button" aria-label="${c(t.searchButtonLabel)}">
|
|
1724
|
+
<span>${c(t.searchButtonLabel)}</span>
|
|
1701
1725
|
</button>
|
|
1702
1726
|
</div>
|
|
1703
1727
|
<div class="search-content">
|
|
@@ -1706,32 +1730,32 @@ ${re}`,this.container=document.createElement("div"),this.container.className="co
|
|
|
1706
1730
|
</div>
|
|
1707
1731
|
</div>
|
|
1708
1732
|
</div>
|
|
1709
|
-
`,this.shadow.innerHTML="",this.shadow.appendChild(r),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=this.getProps(),s=await this.client.search(e,{signal:this.currentSearchController.signal,maxResults:t.maxResults||
|
|
1710
|
-
<a href="${
|
|
1711
|
-
<span>${
|
|
1733
|
+
`,this.shadow.innerHTML="",this.shadow.appendChild(r),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=this.getProps(),s=await this.client.search(e,{signal:this.currentSearchController.signal,maxResults:t.maxResults||J,request:this.getRequestOptions()}),r=s.slice(0,t.maxRenderResults||W);this.lastSearchQuery=e,this.lastSearchTotal=s.length,this.stats?.trackSearch(e,s.length),this.displayResults(r,e,s.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=this.resolvedTranslations,o=r.hideBranding?"":`<div class="powered-by-inline">${L}</div>`,h=s>e.length,d=h?x(n.resultsCountOverflow,{n:e.length,total:s}):x(s===1?n.resultsCount:n.resultsCountPlural,{n:s}),p=r.seeMore&&h?`<div class="search-footer">
|
|
1734
|
+
<a href="${c(r.seeMore+encodeURIComponent(t))}" class="search-see-more">
|
|
1735
|
+
<span>${c(n.seeMoreResults)}</span>
|
|
1712
1736
|
<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
1737
|
</a>
|
|
1714
|
-
</div>`:"",
|
|
1738
|
+
</div>`:"",m=`
|
|
1715
1739
|
<div class="search-header">
|
|
1716
1740
|
<div class="search-count">
|
|
1717
|
-
${
|
|
1741
|
+
${c(d)}
|
|
1718
1742
|
</div>
|
|
1719
|
-
${
|
|
1743
|
+
${o}
|
|
1720
1744
|
</div>
|
|
1721
1745
|
<div class="search-results">
|
|
1722
|
-
${e.map(
|
|
1746
|
+
${e.map((y,z)=>this.renderResult(y,z)).join("")}
|
|
1723
1747
|
</div>
|
|
1724
|
-
${
|
|
1725
|
-
`;this.resultsContainer.innerHTML=
|
|
1726
|
-
${
|
|
1727
|
-
${
|
|
1748
|
+
${p}
|
|
1749
|
+
`;this.resultsContainer.innerHTML=m,this.attachResultHandlers()}renderResult(e,t){const s=this.getProps(),r=s.hideThumbnails?"":this.renderResultImage(e.image,e.title),n=e.url?c(e.url):"#",o=e.url?c(q(e.url)):"",h=s.showDate&&e.timestamp!==void 0?`<div class="search-result-date">${c(O(e.timestamp))}</div>`:"",d=s.showUrl&&e.url||h?`<div class="search-result-metadata">
|
|
1750
|
+
${s.showUrl&&e.url?`<span class="search-result-url">${o}</span>`:'<span class="search-result-url search-result-url-empty"></span>'}
|
|
1751
|
+
${h}
|
|
1728
1752
|
</div>`:"";return`
|
|
1729
|
-
<a href="${
|
|
1730
|
-
${
|
|
1753
|
+
<a href="${n}" class="search-result-item" data-index="${t}" data-result-id="${c(e.id||"")}">
|
|
1754
|
+
${r}
|
|
1731
1755
|
<div class="search-result-content">
|
|
1732
|
-
<div class="search-result-title">${
|
|
1733
|
-
<div class="search-result-snippet">${
|
|
1734
|
-
${
|
|
1756
|
+
<div class="search-result-title">${c(e.title||"")}</div>
|
|
1757
|
+
<div class="search-result-snippet">${c(e.description||"")}</div>
|
|
1758
|
+
${d}
|
|
1735
1759
|
</div>
|
|
1736
1760
|
</a>
|
|
1737
1761
|
`}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?`
|
|
@@ -1740,8 +1764,8 @@ ${re}`,this.container=document.createElement("div"),this.container.className="co
|
|
|
1740
1764
|
<div class="search-result-image-placeholder" style="display: none;">${s}</div>
|
|
1741
1765
|
<img
|
|
1742
1766
|
class="search-result-image"
|
|
1743
|
-
src="${
|
|
1744
|
-
alt="${
|
|
1767
|
+
src="${c(e)}"
|
|
1768
|
+
alt="${c(t)}"
|
|
1745
1769
|
loading="lazy"
|
|
1746
1770
|
/>
|
|
1747
1771
|
</div>
|
|
@@ -1749,10 +1773,10 @@ ${re}`,this.container=document.createElement("div"),this.container.className="co
|
|
|
1749
1773
|
<div class="search-result-image-container">
|
|
1750
1774
|
<div class="search-result-image-placeholder">${s}</div>
|
|
1751
1775
|
</div>
|
|
1752
|
-
`}attachResultHandlers(){const e=this.
|
|
1776
|
+
`}attachResultHandlers(){this.detachResultTrackingHandlers();const e=this.resultsContainer;if(!e)return;this.handleResultClick=r=>{const o=r.target?.closest(".search-result-item");if(!o)return;o.getAttribute("href")==="#"&&r.preventDefault();const d=o.getAttribute("data-index"),p=o.getAttribute("data-result-id")??"",m=d!==null?Number.parseInt(d,10):Number.NaN;!Number.isNaN(m)&&p&&this.stats?.trackClick(this.lastSearchQuery,this.lastSearchTotal,p,m)},e.addEventListener("click",this.handleResultClick);const t=e.querySelector(".search-see-more");t&&(this.handleSeeMoreClick=()=>{this.stats?.trackViewMore(this.lastSearchQuery,this.lastSearchTotal)},t.addEventListener("click",this.handleSeeMoreClick)),this.container?.querySelectorAll(".search-result-image")?.forEach(r=>{r.addEventListener("load",()=>{r.classList.add("loaded"),r.closest(".search-result-image-container")?.querySelector(".search-result-image-loading")?.remove()}),r.addEventListener("error",()=>{const n=r.closest(".search-result-image-container");n?.querySelector(".search-result-image-loading")?.remove();const o=n?.querySelector(".search-result-image-placeholder");o&&(o.style.display="flex"),r.style.display="none"})})}detachResultTrackingHandlers(){const e=this.resultsContainer;e&&this.handleResultClick&&e.removeEventListener("click",this.handleResultClick),this.handleResultClick=null,this.handleSeeMoreClick=null}showLoadingState(){if(!this.resultsContainer)return;this.clearLoadingInterval();const e=this.resolvedTranslations.loadingMessages;this.loadingMessageIndex=Math.floor(Math.random()*e.length);const t=this.resolvedTranslations;this.resultsContainer.innerHTML=`
|
|
1753
1777
|
<div class="search-loading">
|
|
1754
|
-
<div class="loading" aria-label="${
|
|
1755
|
-
<div class="loading-text loading-text-animate">${
|
|
1778
|
+
<div class="loading" aria-label="${c(t.loadingAriaLabel)}"></div>
|
|
1779
|
+
<div class="loading-text loading-text-animate">${c(e[this.loadingMessageIndex])}</div>
|
|
1756
1780
|
</div>
|
|
1757
1781
|
`,this.startLoadingInterval()}startLoadingInterval(){this.loadingMessageInterval=setInterval(()=>{const e=this.resolvedTranslations.loadingMessages;this.loadingMessageIndex=(this.loadingMessageIndex+1)%e.length;const t=this.resultsContainer?.querySelector(".loading-text");t&&(t.classList.remove("loading-text-animate"),t.offsetWidth,t.textContent=e[this.loadingMessageIndex],t.classList.add("loading-text-animate"))},A)}clearLoadingInterval(){this.loadingMessageInterval&&(clearInterval(this.loadingMessageInterval),this.loadingMessageInterval=null)}showEmptyState(){if(this.clearLoadingInterval(),!this.resultsContainer)return;const e=this.resolvedTranslations;this.resultsContainer.innerHTML=`
|
|
1758
1782
|
<div class="search-empty">
|
|
@@ -1760,9 +1784,9 @@ ${re}`,this.container=document.createElement("div"),this.container.className="co
|
|
|
1760
1784
|
<circle cx="11" cy="11" r="8"></circle>
|
|
1761
1785
|
<path d="m21 21-4.35-4.35"></path>
|
|
1762
1786
|
</svg>
|
|
1763
|
-
<div class="search-empty-title">${
|
|
1787
|
+
<div class="search-empty-title">${c(e.emptyStateTitle)}</div>
|
|
1764
1788
|
<div class="search-empty-description">
|
|
1765
|
-
${
|
|
1789
|
+
${c(e.emptyStateDescription)}
|
|
1766
1790
|
</div>
|
|
1767
1791
|
</div>
|
|
1768
1792
|
`}showNoResultsState(e){if(this.clearLoadingInterval(),!this.resultsContainer)return;const t=this.resolvedTranslations;this.resultsContainer.innerHTML=`
|
|
@@ -1771,16 +1795,16 @@ ${re}`,this.container=document.createElement("div"),this.container.className="co
|
|
|
1771
1795
|
<circle cx="11" cy="11" r="8"></circle>
|
|
1772
1796
|
<line x1="21" y1="21" x2="16.65" y2="16.65"></line>
|
|
1773
1797
|
</svg>
|
|
1774
|
-
<div class="search-empty-title">${
|
|
1798
|
+
<div class="search-empty-title">${c(t.noResultsTitle)}</div>
|
|
1775
1799
|
<div class="search-empty-description">
|
|
1776
|
-
${
|
|
1800
|
+
${c(x(t.noResultsDescription,{query:e}))}
|
|
1777
1801
|
</div>
|
|
1778
1802
|
</div>
|
|
1779
1803
|
`}showErrorState(e){if(this.clearLoadingInterval(),!this.resultsContainer)return;const t=this.resolvedTranslations;this.resultsContainer.innerHTML=`
|
|
1780
1804
|
<div class="error">
|
|
1781
|
-
<strong>${
|
|
1805
|
+
<strong>${c(t.errorPrefix)}</strong> ${c(e)}
|
|
1782
1806
|
</div>
|
|
1783
|
-
`}showMissingApiUrlError(){this.resultsContainer&&this.showErrorState(this.resolvedTranslations.missingApiUrlError)}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(
|
|
1807
|
+
`}showMissingApiUrlError(){this.resultsContainer&&this.showErrorState(this.resolvedTranslations.missingApiUrlError)}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.destroyStatsClient(),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.detachResultTrackingHandlers(),this.handleInputChange=null,this.handleInputKeydownEnter=null,this.handleInputKeydownEscape=null,this.handleSearchButtonClick=null}async search(e){await this.performSearch(e)}}customElements.get(Y)||customElements.define(Y,R);const fe=`
|
|
1784
1808
|
/* Modal backdrop */
|
|
1785
1809
|
.modal-backdrop {
|
|
1786
1810
|
position: fixed;
|
|
@@ -2217,8 +2241,8 @@ a.modal-result-item:focus-visible {
|
|
|
2217
2241
|
.modal-container.open {
|
|
2218
2242
|
animation: modal-slide-in var(--search-snippet-transition) ease-out;
|
|
2219
2243
|
}
|
|
2220
|
-
`,
|
|
2221
|
-
${
|
|
2244
|
+
`,X="search-modal-snippet",Z=10,ee=50;class te extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"client",null);a(this,"stats",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,"translationsOverride",null);a(this,"resolvedTranslations",u(null));a(this,"lastSearchQuery","");a(this,"lastSearchTotal",0);a(this,"handleGlobalKeydown",null);a(this,"handleInputChange",null);a(this,"handleInputKeydown",null);a(this,"handleBackdropClick",null);a(this,"handleResultsContainerClick",null);a(this,"savedBodyStyles",null);a(this,"savedHtmlOverflow",null);this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["api-url","placeholder","max-results","max-render-results","theme","shortcut","use-meta-key","debounce-ms","hide-branding","show-url","show-date","hide-thumbnails","see-more","disable-analytics","request-options","translations"]}connectedCallback(){this.syncTranslationsFromAttribute(),this.initializeClient(),this.render(),this.attachGlobalKeyboardShortcut(),this.dispatchEvent(w("ready",void 0))}disconnectedCallback(){this.cleanup()}attributeChangedCallback(e,t,s){t!==s&&(e==="api-url"||e==="disable-analytics"?this.initializeClient():e==="theme"?this.updateTheme(s):e==="translations"&&(this.syncTranslationsFromAttribute(),this.isConnected&&this.rerender()))}get translations(){return this.translationsOverride}set translations(e){this.translationsOverride=e??null,this.resolvedTranslations=u(this.translationsOverride),this.isConnected&&this.rerender()}rerender(){const e=this.isOpen,t=this.inputElement?.value??"";this.isOpen=!1,this.render(),e&&(this.isOpen=!0,this.backdrop?.classList.add("open"),this.modal?.classList.add("open"),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.inputElement?.focus()})})),t&&this.inputElement&&(this.inputElement.value=t,t.trim().length>0&&this.performSearch(t.trim()))}syncTranslationsFromAttribute(){if(this.translationsOverride){this.resolvedTranslations=u(this.translationsOverride);return}const e=E(this.getAttribute("translations"),"SearchModalSnippet");this.resolvedTranslations=u(e)}getProps(){const e=this.resolvedTranslations;return{apiUrl:f(this.getAttribute("api-url"),""),placeholder:f(this.getAttribute("placeholder"),e.placeholder),maxResults:C(this.getAttribute("max-results"),ee),maxRenderResults:C(this.getAttribute("max-render-results"),Z),debounceMs:C(this.getAttribute("debounce-ms"),300),theme:f(this.getAttribute("theme"),"auto"),shortcut:f(this.getAttribute("shortcut"),"k"),useMetaKey:this.getAttribute("use-meta-key")!=="false",hideBranding:b(this.getAttribute("hide-branding"),!1),showUrl:b(this.getAttribute("show-url"),!1),showDate:b(this.getAttribute("show-date"),!1),hideThumbnails:b(this.getAttribute("hide-thumbnails"),!1),seeMore:f(this.getAttribute("see-more"),""),disableAnalytics:b(this.getAttribute("disable-analytics"),!1),translations:this.translationsOverride??void 0}}getRequestOptions(){const e=this.getAttribute("request-options");if(e)try{const t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))throw new Error("request-options must be a JSON object");return t}catch(t){console.error("SearchModalSnippet: invalid request-options attribute",t);return}}initializeClient(){const e=this.getProps();if(!e.apiUrl){console.error("SearchModalSnippet: api-url attribute is required"),this.client=null,this.destroyStatsClient(),this.showMissingApiUrlError();return}try{this.client=M(e.apiUrl),this.destroyStatsClient(),e.disableAnalytics||(this.stats=new I(e.apiUrl))}catch(t){console.error("SearchModalSnippet:",t)}}destroyStatsClient(){this.stats&&(this.stats.destroy(),this.stats=null)}render(){const e=this.getProps(),t=this.resolvedTranslations,s=h=>this.performSearch(h);this.debouncedSearch=$(s,e.debounceMs||300);const r=document.createElement("style");r.textContent=`${T}
|
|
2245
|
+
${fe}`;const n=e.hideBranding?"":`<div class="powered-by-inline">${L}</div>`,o=document.createElement("div");o.innerHTML=`
|
|
2222
2246
|
<div class="modal-backdrop" role="presentation"></div>
|
|
2223
2247
|
<div class="modal-container" role="dialog" aria-modal="true" aria-labelledby="modal-title">
|
|
2224
2248
|
<div class="modal-header">
|
|
@@ -2228,8 +2252,8 @@ ${ae}`;const n=e.hideBranding?"":`<div class="powered-by-inline">${L}</div>`,c=d
|
|
|
2228
2252
|
<input
|
|
2229
2253
|
type="text"
|
|
2230
2254
|
class="modal-search-input"
|
|
2231
|
-
placeholder="${
|
|
2232
|
-
aria-label="${
|
|
2255
|
+
placeholder="${c(e.placeholder||t.placeholder)}"
|
|
2256
|
+
aria-label="${c(t.searchButtonLabel)}"
|
|
2233
2257
|
aria-autocomplete="list"
|
|
2234
2258
|
aria-controls="modal-results-list"
|
|
2235
2259
|
aria-expanded="false"
|
|
@@ -2238,7 +2262,7 @@ ${ae}`;const n=e.hideBranding?"":`<div class="powered-by-inline">${L}</div>`,c=d
|
|
|
2238
2262
|
/>
|
|
2239
2263
|
</div>
|
|
2240
2264
|
<div class="modal-content">
|
|
2241
|
-
<div class="modal-results" id="modal-results-list" role="listbox" aria-label="${
|
|
2265
|
+
<div class="modal-results" id="modal-results-list" role="listbox" aria-label="${c(t.searchResultsAriaLabel)}">
|
|
2242
2266
|
${this.renderEmptyState()}
|
|
2243
2267
|
</div>
|
|
2244
2268
|
</div>
|
|
@@ -2247,25 +2271,25 @@ ${ae}`;const n=e.hideBranding?"":`<div class="powered-by-inline">${L}</div>`,c=d
|
|
|
2247
2271
|
<div class="modal-footer-hint">
|
|
2248
2272
|
<kbd class="modal-kbd">↑</kbd>
|
|
2249
2273
|
<kbd class="modal-kbd">↓</kbd>
|
|
2250
|
-
<span>${
|
|
2274
|
+
<span>${c(t.navigateHint)}</span>
|
|
2251
2275
|
</div>
|
|
2252
2276
|
<div class="modal-footer-hint">
|
|
2253
2277
|
<kbd class="modal-kbd">↵</kbd>
|
|
2254
|
-
<span>${
|
|
2278
|
+
<span>${c(t.selectHint)}</span>
|
|
2255
2279
|
</div>
|
|
2256
2280
|
<div class="modal-footer-hint">
|
|
2257
2281
|
<kbd class="modal-kbd">Esc</kbd>
|
|
2258
|
-
<span>${
|
|
2282
|
+
<span>${c(t.closeHint)}</span>
|
|
2259
2283
|
</div>
|
|
2260
2284
|
</div>
|
|
2261
2285
|
${n}
|
|
2262
2286
|
</div>
|
|
2263
2287
|
</div>
|
|
2264
|
-
`,this.shadow.innerHTML="",this.shadow.appendChild(r),this.shadow.appendChild(
|
|
2265
|
-
<span>${
|
|
2288
|
+
`,this.shadow.innerHTML="",this.shadow.appendChild(r),this.shadow.appendChild(o),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.debouncedSearch?.cancel(),this.currentSearchController?.abort(),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(w("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=this.getProps(),s=await this.client.search(e,{signal:this.currentSearchController.signal,maxResults:t.maxResults||ee,request:this.getRequestOptions()});this.results=s.slice(0,t.maxRenderResults||Z),this.activeIndex=this.results.length>0?0:-1,this.lastSearchQuery=e,this.lastSearchTotal=s.length,this.stats?.trackSearch(e,s.length),this.displayResults(this.results,e,s.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=this.resolvedTranslations,o=e.map((m,y)=>this.renderResult(m,y)).join(""),h=s>e.length,d=h?x(n.resultsCountOverflow,{n:e.length,total:s}):x(s===1?n.modalResultsCount:n.modalResultsCountPlural,{n:s}),p=r.seeMore&&h?`<a href="${c(r.seeMore+encodeURIComponent(t))}" class="modal-see-more">
|
|
2289
|
+
<span>${c(n.seeMoreResults)}</span>
|
|
2266
2290
|
<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=
|
|
2268
|
-
${s.showUrl&&e.url?`<span class="modal-result-url">${
|
|
2291
|
+
</a>`:"";this.resultsContainer.innerHTML=o+p,this.footerCount&&(this.footerCount.textContent=d),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?c(e.url):"#",o=e.url?c(q(e.url)):"",h=s.showDate&&e.timestamp!==void 0?`<div class="modal-result-date">${c(O(e.timestamp))}</div>`:"",d=s.showUrl&&e.url||h?`<div class="modal-result-metadata">
|
|
2292
|
+
${s.showUrl&&e.url?`<span class="modal-result-url">${o}</span>`:'<span class="modal-result-url modal-result-url-empty"></span>'}
|
|
2269
2293
|
${h}
|
|
2270
2294
|
</div>`:"";return`
|
|
2271
2295
|
<a
|
|
@@ -2276,13 +2300,14 @@ ${ae}`;const n=e.hideBranding?"":`<div class="powered-by-inline">${L}</div>`,c=d
|
|
|
2276
2300
|
aria-selected="${t===this.activeIndex}"
|
|
2277
2301
|
tabindex="-1"
|
|
2278
2302
|
data-index="${t}"
|
|
2279
|
-
data-
|
|
2303
|
+
data-result-id="${c(e.id||"")}"
|
|
2304
|
+
data-url="${c(e.url||"")}"
|
|
2280
2305
|
>
|
|
2281
2306
|
${r}
|
|
2282
2307
|
<div class="modal-result-content">
|
|
2283
|
-
<div class="modal-result-title">${
|
|
2284
|
-
${e.description?`<div class="modal-result-description">${
|
|
2285
|
-
${
|
|
2308
|
+
<div class="modal-result-title">${c(e.title||"")}</div>
|
|
2309
|
+
${e.description?`<div class="modal-result-description">${c(e.description)}</div>`:""}
|
|
2310
|
+
${d}
|
|
2286
2311
|
</div>
|
|
2287
2312
|
</a>
|
|
2288
2313
|
`}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?`
|
|
@@ -2291,8 +2316,8 @@ ${ae}`;const n=e.hideBranding?"":`<div class="powered-by-inline">${L}</div>`,c=d
|
|
|
2291
2316
|
<div class="modal-result-image-placeholder" style="display: none;">${s}</div>
|
|
2292
2317
|
<img
|
|
2293
2318
|
class="modal-result-image"
|
|
2294
|
-
src="${
|
|
2295
|
-
alt="${
|
|
2319
|
+
src="${c(e)}"
|
|
2320
|
+
alt="${c(t)}"
|
|
2296
2321
|
loading="lazy"
|
|
2297
2322
|
/>
|
|
2298
2323
|
</div>
|
|
@@ -2300,18 +2325,18 @@ ${ae}`;const n=e.hideBranding?"":`<div class="powered-by-inline">${L}</div>`,c=d
|
|
|
2300
2325
|
<div class="modal-result-image-container">
|
|
2301
2326
|
<div class="modal-result-image-placeholder">${s}</div>
|
|
2302
2327
|
</div>
|
|
2303
|
-
`}attachResultHandlers(){const e=this.resultsContainer
|
|
2328
|
+
`}attachResultHandlers(){this.detachResultsContainerClick();const e=this.resultsContainer;if(!e)return;this.handleResultsContainerClick=r=>{const n=r.target;if(!n)return;const o=n.closest(".modal-result-item");if(o){o.getAttribute("href")==="#"&&r.preventDefault();const p=o.getAttribute("data-index"),m=o.getAttribute("data-result-id")??"",y=p!==null?Number.parseInt(p,10):Number.NaN;!Number.isNaN(y)&&m&&this.stats?.trackClick(this.lastSearchQuery,this.lastSearchTotal,m,y);return}n.closest(".modal-see-more")&&this.stats?.trackViewMore(this.lastSearchQuery,this.lastSearchTotal)},e.addEventListener("click",this.handleResultsContainerClick),e.querySelectorAll(".modal-result-item").forEach((r,n)=>{r.addEventListener("mouseenter",()=>{this.activeIndex=n,this.updateActiveResult()})}),e.querySelectorAll(".modal-result-image").forEach(r=>{r.addEventListener("load",()=>{r.classList.add("loaded"),r.closest(".modal-result-image-container")?.querySelector(".modal-result-image-loading")?.remove()}),r.addEventListener("error",()=>{const n=r.closest(".modal-result-image-container");n?.querySelector(".modal-result-image-loading")?.remove();const o=n?.querySelector(".modal-result-image-placeholder");o&&(o.style.display="flex"),r.style.display="none"})})}detachResultsContainerClick(){this.resultsContainer&&this.handleResultsContainerClick&&this.resultsContainer.removeEventListener("click",this.handleResultsContainerClick),this.handleResultsContainerClick=null}renderEmptyState(){const e=this.resolvedTranslations;return`
|
|
2304
2329
|
<div class="modal-empty">
|
|
2305
2330
|
<svg class="modal-empty-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
2306
2331
|
<circle cx="11" cy="11" r="8"></circle>
|
|
2307
2332
|
<path d="m21 21-4.35-4.35"></path>
|
|
2308
2333
|
</svg>
|
|
2309
|
-
<div class="modal-empty-description">${
|
|
2334
|
+
<div class="modal-empty-description">${c(e.modalEmptyStateDescription)}</div>
|
|
2310
2335
|
</div>
|
|
2311
2336
|
`}showEmptyState(){this.clearLoadingInterval(),this.resultsContainer&&(this.resultsContainer.innerHTML=this.renderEmptyState(),this.footerCount&&(this.footerCount.textContent=""),this.inputElement&&this.inputElement.setAttribute("aria-expanded","false"))}showLoadingState(){if(!this.resultsContainer)return;this.clearLoadingInterval();const e=this.resolvedTranslations.loadingMessages,t=this.resolvedTranslations;this.loadingMessageIndex=Math.floor(Math.random()*e.length),this.resultsContainer.innerHTML=`
|
|
2312
2337
|
<div class="modal-loading">
|
|
2313
|
-
<div class="loading" aria-label="${
|
|
2314
|
-
<div class="loading-text loading-text-animate">${
|
|
2338
|
+
<div class="loading" aria-label="${c(t.loadingAriaLabel)}"></div>
|
|
2339
|
+
<div class="loading-text loading-text-animate">${c(e[this.loadingMessageIndex])}</div>
|
|
2315
2340
|
</div>
|
|
2316
2341
|
`,this.footerCount&&(this.footerCount.textContent=e[this.loadingMessageIndex]),this.startLoadingInterval()}startLoadingInterval(){this.loadingMessageInterval=setInterval(()=>{const e=this.resolvedTranslations.loadingMessages;this.loadingMessageIndex=(this.loadingMessageIndex+1)%e.length;const t=this.resultsContainer?.querySelector(".loading-text");t&&(t.classList.remove("loading-text-animate"),t.offsetWidth,t.textContent=e[this.loadingMessageIndex],t.classList.add("loading-text-animate")),this.footerCount&&(this.footerCount.textContent=e[this.loadingMessageIndex])},A)}clearLoadingInterval(){this.loadingMessageInterval&&(clearInterval(this.loadingMessageInterval),this.loadingMessageInterval=null)}showNoResultsState(e){if(this.clearLoadingInterval(),!this.resultsContainer)return;const t=this.resolvedTranslations;this.resultsContainer.innerHTML=`
|
|
2317
2342
|
<div class="modal-empty">
|
|
@@ -2319,12 +2344,12 @@ ${ae}`;const n=e.hideBranding?"":`<div class="powered-by-inline">${L}</div>`,c=d
|
|
|
2319
2344
|
<circle cx="11" cy="11" r="8"></circle>
|
|
2320
2345
|
<line x1="21" y1="21" x2="16.65" y2="16.65"></line>
|
|
2321
2346
|
</svg>
|
|
2322
|
-
<div class="modal-empty-title">${
|
|
2323
|
-
<div class="modal-empty-description">${
|
|
2347
|
+
<div class="modal-empty-title">${c(t.modalNoResultsTitle)}</div>
|
|
2348
|
+
<div class="modal-empty-description">${c(x(t.modalNoResultsDescription,{query:e}))}</div>
|
|
2324
2349
|
</div>
|
|
2325
2350
|
`,this.footerCount&&(this.footerCount.textContent=t.modalResultsCountZero),this.inputElement&&this.inputElement.setAttribute("aria-expanded","false")}showErrorState(e){if(this.clearLoadingInterval(),!this.resultsContainer)return;const t=this.resolvedTranslations;this.resultsContainer.innerHTML=`
|
|
2326
2351
|
<div class="error">
|
|
2327
|
-
<strong>${
|
|
2352
|
+
<strong>${c(t.errorPrefix)}</strong> ${c(e)}
|
|
2328
2353
|
</div>
|
|
2329
|
-
`,this.footerCount&&(this.footerCount.textContent=t.modalResultsCountError)}showMissingApiUrlError(){this.resultsContainer&&this.showErrorState(this.resolvedTranslations.missingApiUrlError)}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,scrollbarGutter:document.body.style.scrollbarGutter},this.savedHtmlOverflow=document.documentElement.style.overflow,document.body.style.scrollbarGutter="stable",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,document.body.style.scrollbarGutter=this.savedBodyStyles.scrollbarGutter||"",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(
|
|
2354
|
+
`,this.footerCount&&(this.footerCount.textContent=t.modalResultsCountError)}showMissingApiUrlError(){this.resultsContainer&&this.showErrorState(this.resolvedTranslations.missingApiUrlError)}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,scrollbarGutter:document.body.style.scrollbarGutter},this.savedHtmlOverflow=document.documentElement.style.overflow,document.body.style.scrollbarGutter="stable",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,document.body.style.scrollbarGutter=this.savedBodyStyles.scrollbarGutter||"",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.detachResultsContainerClick(),this.handleInputChange=null,this.handleInputKeydown=null,this.handleBackdropClick=null,this.destroyStatsClient(),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(w("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(w("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(X)||customElements.define(X,te),g.AISearchClient=P,g.ChatBubbleSnippet=F,g.ChatPageSnippet=G,g.DEFAULT_TRANSLATIONS=v,g.SearchBarSnippet=R,g.SearchModalSnippet=te,g.StatsClient=I,g.default=R,g.mergeTranslations=u,Object.defineProperties(g,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
|
|
2330
2355
|
//# sourceMappingURL=search-snippet.umd.js.map
|