Files
minne/html-router/templates/chat/streaming_response.html
2025-04-15 12:41:45 +02:00

50 lines
2.0 KiB
HTML

<div class="chat chat-end">
<div class="chat-bubble markdown-content">
{{ user_message.content }}
</div>
</div>
<div class="chat chat-start">
<div hx-ext="sse" sse-connect="/chat/response-stream?message_id={{user_message.id}}" sse-close="close_stream"
hx-swap="beforeend">
<div class="chat-bubble">
<span class="loading loading-dots loading-sm loading-id-{{user_message.id}}"></span>
<div class="markdown-content" id="ai-message-content-{{user_message.id}}" sse-swap="chat_message"></div>
</div>
<div sse-swap="references"></div>
</div>
</div>
<script>
marked.setOptions({
breaks: true, gfm: true, headerIds: false, mangle: false
});
// Buffer store for markdown, keyed by message id
window.markdownBuffer = window.markdownBuffer || {};
document.body.addEventListener('htmx:sseBeforeMessage', function (e) {
const spinner = document.querySelector('.loading-id-{{user_message.id}}');
if (spinner) spinner.style.display = 'none';
if (e.detail.event === 'chat_message') {
const el = document.getElementById('ai-message-content-{{user_message.id}}');
if (e.detail.elt !== el) return;
e.preventDefault(); // Prevent htmx from swapping
// Use message id as buffer key
const msgId = '{{user_message.id}}';
window.markdownBuffer[msgId] = (window.markdownBuffer[msgId] || '') + (e.detail.data || '');
// Render buffer (with newline fix) on *every* chunk
el.innerHTML = marked.parse(
window.markdownBuffer[msgId].replace(/\\n/g, '\n')
);
scrollChatToBottom();
}
});
document.body.addEventListener('htmx:sseClose', function () {
const el = document.getElementById('ai-message-content-{{user_message.id}}');
const msgId = '{{user_message.id}}';
if (el && window.markdownBuffer[msgId]) {
el.innerHTML = marked.parse(
window.markdownBuffer[msgId].replace(/\\n/g, '\n')
);
delete window.markdownBuffer[msgId]; // Clean up in multichat
}
});
</script>