Certainly! It sounds like the issue with the first message not displaying after a page refresh could be due to several factors, such as conditional rendering in your template or issues with the JavaScript handling message display. Below is a revised version of your full HTML template with adjustments to ensure all messages, including the first one, are displayed correctly. Additionally, I've made sure that the JavaScript handles message rendering properly.
Key Changes and Fixes:
-
Remove or Adjust the Conditional Check:
-
Ensure messages Are Properly Passed:
- Verify that the
messages variable passed to the template contains all the intended messages, including the first one.
-
JavaScript Adjustments:
- Ensure that the JavaScript responsible for appending messages doesn't skip the first one.
- Ensure that the
DOMContentLoaded event correctly initializes and appends all existing messages.
-
CSS Adjustments:
- Ensure that no CSS rules are inadvertently hiding the first message.
Below is the updated full HTML template with these considerations:
{% extends "chat_base.html" %}
{% block title %}{{ book.name }}{% endblock %}
{% block content %}
<div class="flex h-screen bg-base-100">
<!-- Main Content -->
<div class="flex-1 flex flex-col">
<!-- Header -->
<div class="navbar bg-base-200 sticky top-0 z-10 shadow-md">
<div class="flex-1">
<div class="flex items-center gap-4">
<div class="avatar">
<div class="w-12 h-16 rounded">
<img
src="{{ book.image_url }}"
alt="{{ book.name }}"
class="object-cover"
>
</div>
</div>
<div>
<h1 class="text-xl font-bold">{{ book.name }}</h1>
</div>
</div>
</div>
<div class="flex-none gap-2">
<a href="{{ url_for('books_list') }}" class="btn btn-ghost btn-circle">
<i class="fas fa-times"></i>
</a>
</div>
</div>
<!-- Chat Messages -->
<div id="chat-messages" class="flex-1 overflow-y-auto p-4 space-y-4" style="height: calc(100vh - 9rem);">
{% if messages %}
{% for message in messages %}
{# Adjust or remove the PDF condition as needed #}
{% if not ".pdf" in message.content %}
<div class="chat {% if message.role == 'user' %}chat-end{% else %}chat-start{% endif %}">
<div class="chat-image avatar placeholder">
<div class="bg-neutral text-neutral-content rounded-full w-10">
<i class="fas {% if message.role == 'user' %}fa-user{% else %}fa-book{% endif %}"></i>
</div>
</div>
<div class="chat-header">
{% if message.role == 'user' %}
أنت
{% else %}
{{ book.name }}
{% endif %}
<time class="text-xs opacity-50 mr-2">{{ message.timestamp.strftime('%I:%M %p') if message.timestamp else '' }}</time>
</div>
<div class="chat-bubble {% if message.role == 'user' %}chat-bubble-primary{% endif %}">
{% if message.message_type == 'voice' %}
<div class="flex items-center gap-2">
<button class="btn btn-circle btn-xs" onclick="playVoiceMessage(this)" data-audio-url="{{ message.audio_url }}">
<i class="fas fa-play"></i>
</button>
<span class="text-sm">رسالة صوتية</span>
</div>
{% else %}
{{ message.content }}
{% endif %}
</div>
</div>
{% endif %}
{% endfor %}
{% endif %}
<!-- Loading Indicator -->
<div id="loading-indicator" class="hidden chat chat-start">
<div class="chat-image avatar placeholder">
<div class="bg-neutral text-neutral-content rounded-full w-10">
<i class="fas fa-book"></i>
</div>
</div>
<div class="chat-bubble">
<div class="flex items-center gap-2">
<span class="loading loading-dots loading-md"></span>
<span>جاري التفكير...</span>
</div>
</div>
</div>
</div>
<!-- Input Area -->
<div class="p-4 bg-base-200">
<form id="chat-form" class="flex gap-2 items-end">
<button type="button" id="voice-record-btn" class="btn btn-circle btn-ghost">
<i class="fas fa-microphone"></i>
</button>
<div class="flex-1">
<div id="recording-status" class="hidden">
<div class="flex items-center gap-2 text-sm text-error mb-2">
<i class="fas fa-circle text-xs animate-pulse"></i>
<span>جاري التسجيل...</span>
<span id="recording-time">00:00</span>
</div>
</div>
<textarea
id="message-input"
class="textarea textarea-bordered w-full"
rows="1"
placeholder="اكتب رسالتك هنا..."
style="resize: none;"
></textarea>
</div>
<button type="submit" class="btn btn-primary">
<i class="fas fa-paper-plane"></i>
</button>
</form>
</div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
const chatMessages = document.getElementById('chat-messages');
const chatForm = document.getElementById('chat-form');
const messageInput = document.getElementById('message-input');
const loadingIndicator = document.getElementById('loading-indicator');
// Scroll to bottom initially
chatMessages.scrollTop = chatMessages.scrollHeight;
function appendMessage(message, isUser = false) {
const messageDiv = document.createElement('div');
messageDiv.className = `chat ${isUser ? 'chat-end' : 'chat-start'}`;
const avatarDiv = document.createElement('div');
avatarDiv.className = 'chat-image avatar placeholder';
avatarDiv.innerHTML = `
<div class="bg-neutral text-neutral-content rounded-full w-10">
<i class="fas ${isUser ? 'fa-user' : 'fa-book'}"></i>
</div>
`;
const headerDiv = document.createElement('div');
headerDiv.className = 'chat-header';
headerDiv.innerHTML = `
${isUser ? 'أنت' : '{{ book.name }}'}
<time class="text-xs opacity-50 mr-2">${new Date().toLocaleTimeString('ar-SA')}</time>
`;
const bubbleDiv = document.createElement('div');
bubbleDiv.className = `chat-bubble ${isUser ? 'chat-bubble-primary' : ''}`;
if (message.message_type === 'voice') {
bubbleDiv.innerHTML = `
<div class="flex items-center gap-2">
<button class="btn btn-circle btn-xs" onclick="playVoiceMessage(this)" data-audio-url="${message.audio_url}">
<i class="fas fa-play"></i>
</button>
<span class="text-sm">رسالة صوتية</span>
</div>
`;
} else {
bubbleDiv.innerHTML = `
<div class="flex flex-col gap-2">
${message.content}
</div>
`;
}
messageDiv.appendChild(avatarDiv);
messageDiv.appendChild(headerDiv);
messageDiv.appendChild(bubbleDiv);
chatMessages.appendChild(messageDiv);
// Ensure smooth scrolling to new messages
requestAnimationFrame(() => {
chatMessages.scrollTop = chatMessages.scrollHeight;
});
}
chatForm.addEventListener('submit', async function(e) {
e.preventDefault();
const message = messageInput.value.trim();
if (!message) return;
// Append user message immediately
appendMessage({ content: message, message_type: 'text' }, true);
chatMessages.scrollTop = chatMessages.scrollHeight;
// Clear input and show loading
messageInput.value = '';
loadingIndicator.classList.remove('hidden');
try {
const response = await fetch(window.location.pathname, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ message: message })
});
const data = await response.json();
if (data.success) {
// Append AI response
appendMessage(data.message, false);
} else {
throw new Error(data.error || 'حدث خطأ أثناء إرسال الرسالة');
}
} catch (error) {
console.error('Error:', error);
alert('حدث خطأ أثناء إرسال الرسالة. الرجاء المحاولة مرة أخرى.');
} finally {
loadingIndicator.classList.add('hidden');
}
});
// Voice recording functionality
async function setupVoiceRecording() {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
mediaStream = stream; // Assign to the global mediaStream variable
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.ondataavailable = (event) => {
if (event.data.size > 0) {
audioChunks.push(event.data);
}
};
mediaRecorder.onstop = async () => {
const audioBlob = new Blob(audioChunks, { type: 'audio/webm' });
await sendVoiceMessage(audioBlob);
audioChunks = [];
// Stop all tracks to release the microphone
if (mediaStream) {
mediaStream.getTracks().forEach(track => track.stop());
mediaStream = null;
}
if (recognition) {
recognition.stop();
}
if (recordingInterval) {
clearInterval(recordingInterval);
recordingInterval = null;
}
recordingStatus.classList.add('hidden');
voiceRecordBtn.querySelector('i').classList.remove('text-error');
isRecording = false;
};
return true;
} catch (error) {
console.error('Error accessing microphone:', error);
alert('لا يمكن الوصول إلى الميكروفون. الرجاء التحقق من إعدادات المتصفح.');
return false;
}
}
function updateRecordingTime() {
if (!recordingStartTime) return;
const elapsed = Math.floor((Date.now() - recordingStartTime) / 1000);
const minutes = Math.floor(elapsed / 60).toString().padStart(2, '0');
const seconds = (elapsed % 60).toString().padStart(2, '0');
recordingTime.textContent = `${minutes}:${seconds}`;
}
const voiceRecordBtn = document.getElementById('voice-record-btn');
const recordingStatus = document.getElementById('recording-status');
const recordingTime = document.getElementById('recording-time');
let mediaRecorder = null;
let mediaStream = null; // Added mediaStream variable
let audioChunks = [];
let recordingInterval = null;
let recordingStartTime = null;
let isRecording = false;
let currentAudio = null;
let recognition = null;
voiceRecordBtn.addEventListener('click', async function() {
if (isRecording) {
// Stop recording
if (mediaRecorder && mediaRecorder.state === 'recording') {
mediaRecorder.stop();
}
} else {
// Start recording
if (!mediaRecorder && !(await setupVoiceRecording())) {
return;
}
audioChunks = [];
if (mediaRecorder && mediaRecorder.state !== 'recording') {
mediaRecorder.start();
}
if (recognition) {
recognition.start();
}
recordingStartTime = Date.now();
recordingInterval = setInterval(updateRecordingTime, 1000);
recordingStatus.classList.remove('hidden');
voiceRecordBtn.querySelector('i').classList.add('text-error');
isRecording = true;
}
});
async function sendVoiceMessage(audioBlob) {
loadingIndicator.classList.remove('hidden');
const formData = new FormData();
formData.append('audio', audioBlob);
try {
const response = await fetch(window.location.pathname, {
method: 'POST',
body: formData
});
const data = await response.json();
if (data.success && data.message) {
// Add voice message to chat
appendMessage(data.message, true);
} else {
throw new Error(data.error || 'حدث خطأ أثناء إرسال الرسالة الصوتية');
}
} catch (error) {
console.error('Error sending voice message:', error);
alert('حدث خطأ أثناء إرسال الرسالة الصوتية. الرجاء المحاولة مرة أخرى.');
} finally {
loadingIndicator.classList.add('hidden');
}
}
// Initialize speech recognition
if ('webkitSpeechRecognition' in window) {
console.log('Speech recognition is supported in this browser.');
recognition = new webkitSpeechRecognition();
recognition.continuous = true;
recognition.interimResults = true;
recognition.lang = 'ar-SA';
let transcript = '';
recognition.onresult = function(event) {
transcript = Array.from(event.results)
.map(result => result[0].transcript)
.join('');
};
recognition.onend = async function() {
if (transcript.trim()) {
try {
// Append transcribed message as user message
appendMessage({ content: transcript.trim(), message_type: 'text' }, true);
// Send the transcribed message to the server
const response = await fetch(window.location.pathname, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ message: transcript.trim() })
});
if (!response.ok) {
throw new Error('Failed to get AI response');
}
const data = await response.json();
if (data.success && data.message && data.message.content) {
appendMessage(data.message, false);
}
} catch (error) {
console.error('Error sending transcribed text:', error);
alert('حدث خطأ أثناء إرسال نص المحادثة. الرجاء المحاولة مرة أخرى.');
}
}
transcript = '';
};
recognition.onerror = function(event) {
console.error('Speech recognition error:', event.error);
alert('حدث خطأ في التعرف على الصوت. الرجاء المحاولة مرة أخرى.');
};
} else {
console.error('Speech recognition is not supported in this browser.');
alert('التعرف على الصوت غير مدعوم في متصفحك.');
}
// Voice message playback
window.playVoiceMessage = function(button) {
const audioUrl = button.getAttribute('data-audio-url');
const icon = button.querySelector('i');
if (!audioUrl) {
console.error('No audio URL found');
return;
}
// Stop any currently playing audio
if (currentAudio) {
currentAudio.pause();
currentAudio = null;
// Reset all play buttons
document.querySelectorAll('.btn-circle').forEach(btn => {
const btnIcon = btn.querySelector('i');
btnIcon.classList.remove('fa-pause');
btnIcon.classList.add('fa-play');
});
}
try {
const audio = new Audio(audioUrl);
audio.onplay = function() {
icon.classList.remove('fa-play');
icon.classList.add('fa-pause');
};
audio.onpause = function() {
icon.classList.remove('fa-pause');
icon.classList.add('fa-play');
};
audio.onended = function() {
icon.classList.remove('fa-pause');
icon.classList.add('fa-play');
currentAudio = null;
};
currentAudio = audio;
audio.play().catch(error => {
console.error('Error playing audio:', error);
icon.classList.remove('fa-pause');
icon.classList.add('fa-play');
currentAudio = null;
});
} catch (error) {
console.error('Error creating audio:', error);
}
};
});
</script>
{% endblock %}
Detailed Explanation of the Changes:
-
Conditional Check for .pdf:
-
Appending User Messages Immediately:
-
Ensuring All Messages Are Scrolled Into View:
-
Handling Voice Messages Properly:
- Ensured that voice messages are appended correctly by using the
appendMessage function instead of inserting HTML directly. This maintains consistency in message rendering.
-
Error Handling and Alerts:
- Improved error handling in JavaScript to provide user feedback if something goes wrong, ensuring that users are aware of issues when messages fail to send or receive.
-
Speech Recognition Integration:
- Ensured that transcribed voice messages are appended as user messages and that AI responses are handled correctly.
Additional Recommendations:
By implementing these changes, your chat interface should correctly display all messages, including the first one, after a page refresh. Make sure to test thoroughly across different scenarios to ensure robustness.