To add a thinking animation to your chat interface, you can enhance the existing loading indicator to display a more engaging and visually appealing animation. This will improve user experience by clearly indicating when the AI is processing a response.
Here's how you can achieve this:
-
Enhance the Loading Indicator HTML:
- Modify the existing
loading-indicator to include a "Thinking..." message along with an animated spinner or animated dots.
- Use Tailwind CSS and DaisyUI classes for styling consistency.
- Ensure that all text is appropriately translated into Arabic.
-
Update the CSS for Custom Animations (If Needed):
- If you prefer a custom animation beyond the existing
loading-dots, you can add specific CSS for more intricate animations.
- However, Tailwind CSS and DaisyUI provide sufficient utilities for most animations.
-
Ensure JavaScript Controls the Indicator Appropriately:
- The current JavaScript already shows and hides the
loading-indicator. Ensure that it aligns with the enhanced HTML structure.
Below is the updated code with the thinking animation integrated:
Updated HTML Template
{% extends "dashboard_layout.html" %}
{% block dashboard_content %}
<div class="flex flex-col h-screen">
<!-- Header -->
<div class="navbar bg-base-200">
<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 }}"
>
</div>
</div>
<div>
<h1 class="text-xl font-bold">{{ book.name }}</h1>
</div>
</div>
</div>
<div class="flex-none">
<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">
{% if messages %}
{% for message in messages %}
{% 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 %}
<div class="flex flex-col gap-2">
{{ message.content }}
{% if message.audio_url %}
<div class="flex items-center gap-2 mt-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-xs">استمع للرد</span>
</div>
{% endif %}
</div>
{% endif %}
</div>
</div>
{% endif %}
{% endfor %}
{% else %}
<div class="hero min-h-[50vh]">
<div class="hero-content text-center">
<div class="max-w-md">
<h2 class="text-2xl font-bold mb-4">ابدأ محادثة مع {{ book.name }}</h2>
<p class="text-base-content/70">اسأل أي سؤال عن الكتاب وسأساعدك في فهمه بشكل أفضل.</p>
</div>
</div>
</div>
{% endif %}
<!-- Enhanced Loading Indicator with Thinking Animation -->
<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 flex items-center space-x-2">
<div class="w-4 h-4 bg-gray-300 rounded-full animate-bounce"></div>
<div class="w-4 h-4 bg-gray-300 rounded-full animate-bounce delay-200"></div>
<div class="w-4 h-4 bg-gray-300 rounded-full animate-bounce delay-400"></div>
<span class="text-sm text-gray-500">يتم التفكير...</span>
</div>
</div>
</div>
<!-- Chat Input -->
<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="form-control flex-1">
<textarea
id="message-input"
class="textarea textarea-bordered min-h-12"
placeholder="اكتب رسالتك هنا..."
rows="1"
required
></textarea>
</div>
<button type="submit" class="btn btn-primary">
<i class="fas fa-paper-plane"></i>
</button>
</form>
<!-- Recording Status -->
<div id="recording-status" class="hidden mt-2 text-sm text-error">
<div class="flex items-center gap-2">
<span class="loading loading-spinner loading-sm"></span>
<span>جاري التسجيل...</span>
<span id="recording-time">00:00</span>
</div>
</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');
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}
${message.audio_url ? `
<div class="flex items-center gap-2 mt-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-xs">استمع للرد</span>
</div>
` : ''}
</div>
`;
}
messageDiv.appendChild(avatarDiv);
messageDiv.appendChild(headerDiv);
messageDiv.appendChild(bubbleDiv);
chatMessages.appendChild(messageDiv);
chatMessages.scrollTop = chatMessages.scrollHeight;
}
chatForm.addEventListener('submit', async function(e) {
e.preventDefault();
const message = messageInput.value.trim();
if (!message) return;
// 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 user message
appendMessage({ content: message, message_type: 'text' }, true);
// 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 });
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 = [];
if (recognition) {
recognition.stop();
}
};
return true;
} catch (error) {
console.error('Error accessing microphone:', error);
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 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();
if (recordingInterval) {
clearInterval(recordingInterval);
recordingInterval = null;
}
}
recordingStatus.classList.add('hidden');
voiceRecordBtn.querySelector('i').classList.remove('text-error');
isRecording = false;
} else {
// Start recording
if (!mediaRecorder && !(await setupVoiceRecording())) {
return;
}
audioChunks = [];
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
const messageHtml = `
<div class="chat chat-end">
<div class="chat-header">
أنت
<time class="text-xs opacity-50 mr-2">${new Date().toLocaleTimeString('ar-SA')}</time>
</div>
<div class="chat-bubble chat-bubble-primary">
<div class="flex items-center gap-2">
<button class="btn btn-circle btn-xs" onclick="playVoiceMessage(this)" data-audio-url="${data.message.audio_url}">
<i class="fas fa-play"></i>
</button>
<span class="text-sm">رسالة صوتية</span>
</div>
</div>
</div>
`;
chatMessages.insertAdjacentHTML('beforeend', messageHtml);
chatMessages.scrollTop = chatMessages.scrollHeight;
}
} catch (error) {
console.error('Error sending voice message:', error);
} 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) {
try {
const response = await fetch(window.location.pathname, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ message: transcript })
});
if (!response.ok) {
throw new Error('Failed to get AI response');
}
const data = await response.json();
if (data.success && data.message && data.message.content) {
const aiMessageHtml = `
<div class="chat chat-start">
<div class="chat-header">
{{ book.name }}
<time class="text-xs opacity-50 mr-2">${new Date().toLocaleTimeString('ar-SA')}</time>
</div>
<div class="chat-bubble">
<div class="flex flex-col gap-2">
${data.message.content}
${data.message.audio_url ? `
<div class="flex items-center gap-2 mt-2">
<button class="btn btn-circle btn-xs" onclick="playVoiceMessage(this)" data-audio-url="${data.message.audio_url}">
<i class="fas fa-play"></i>
</button>
<span class="text-xs">استمع للرد</span>
</div>
` : ''}
</div>
</div>
</div>
`;
chatMessages.insertAdjacentHTML('beforeend', aiMessageHtml);
chatMessages.scrollTop = chatMessages.scrollHeight;
}
} catch (error) {
console.error('Error sending transcribed text:', error);
}
}
transcript = '';
};
recognition.onerror = function(event) {
console.error('Speech recognition error:', event.error);
};
} else {
console.error('Speech recognition is not supported in this browser.');
}
// Scroll to bottom of chat
chatMessages.scrollTop = chatMessages.scrollHeight;
// 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 %}
Explanation of the Changes
-
Enhanced Loading Indicator:
- HTML Structure:
- Replaced the existing loading spinner with a more engaging "thinking" animation using three bouncing dots.
- Added a descriptive text
يتم التفكير... ("Thinking...") to inform the user that the AI is processing the response.
- Animation:
- Utilized Tailwind CSS utility classes like
animate-bounce and delay-* to create a sequential bouncing effect for the dots.
- This provides a smooth and visually appealing animation indicating that the system is processing.
-
Localization:
- Ensured that the loading message is in Arabic to maintain consistency with the rest of the interface.
-
JavaScript Handling:
- The existing JavaScript controls for showing and hiding the
loading-indicator remain unchanged, ensuring that the animation appears when needed.
- The
DOMContentLoaded event listener continues to manage the chat functionality seamlessly.
-
Styling Consistency:
- Maintained the use of Tailwind CSS and DaisyUI classes to ensure that the new elements blend seamlessly with the existing design.
- The animated dots use
bg-gray-300 for a subtle appearance and rounded shapes for a polished look.
Optional: Custom CSS for More Complex Animations
If you desire a more intricate or unique animation beyond the bouncing dots, you can add custom CSS. Here's how you can implement a simple pulsating dot animation as an example:
-
Add Custom CSS:
<style>
.pulsate {
width: 10px;
height: 10px;
background-color: #d1d5db; /* Tailwind's bg-gray-300 */
border-radius: 50%;
animation: pulsate 1.5s infinite;
}
@keyframes pulsate {
0% {
transform: scale(1);
opacity: 0.6;
}
50% {
transform: scale(1.5);
opacity: 1;
}
100% {
transform: scale(1);
opacity: 0.6;
}
}
.pulsate-delay-200 {
animation-delay: 0.2s;
}
.pulsate-delay-400 {
animation-delay: 0.4s;
}
</style>
-
Integrate Custom Animation into 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 flex items-center space-x-2">
<div class="pulsate"></div>
<div class="pulsate pulsate-delay-200"></div>
<div class="pulsate pulsate-delay-400"></div>
<span class="text-sm text-gray-500">يتم التفكير...</span>
</div>
</div>
This will create a pulsating effect where each dot grows and fades in a staggered manner, providing a more dynamic "thinking" animation.
Final Touches
-
Testing:
- Ensure that the animation works smoothly across different browsers and devices.
- Test the responsiveness to confirm that the animation scales appropriately on various screen sizes.
-
Accessibility:
- Consider adding
aria-live regions or appropriate ARIA attributes to inform assistive technologies about the loading state.
- For example, add
aria-live="polite" to the loading-indicator div to announce status updates.
-
Performance:
- Optimize animations to be lightweight to prevent any lag or performance issues, especially on mobile devices.
By implementing these changes, your chat interface will have a clear and visually appealing thinking animation, enhancing the user experience by effectively communicating the AI's processing state.