Spaces:
Running
Running
File size: 22,712 Bytes
7bc796e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 |
document.addEventListener('DOMContentLoaded', function() {
// DOM Elements
const chatWindow = document.getElementById('chatWindow');
const userInput = document.getElementById('userInput');
const sendButton = document.getElementById('sendButton');
const clearButton = document.getElementById('clearButton');
const clearButtonNav = document.getElementById('clearButtonNav');
const imageInput = document.getElementById('imageInput');
const uploadImageButton = document.getElementById('uploadImageButton');
const imagePreviewArea = document.getElementById('imagePreviewArea');
const imagePreviewContainer = document.getElementById('imagePreviewContainer');
const chatHistoryList = document.getElementById('chatHistoryList');
const saveCurrentChatButton = document.getElementById('saveCurrentChatButton');
const settingsButton = document.getElementById('settingsButtonNav');
const toggleNavButton = document.getElementById('toggleNavButton');
const closeSideNavButton = document.getElementById('closeSideNavButton');
const sideNav = document.getElementById('sideNav');
const mainContent = document.querySelector('.main-content');
const welcomeContainer = document.querySelector('.welcome-container');
const suggestionBubbles = document.querySelectorAll('.suggestion-bubble');
// Templates
const loadingTemplate = document.getElementById('loadingTemplate');
const userMessageTemplate = document.getElementById('userMessageTemplate');
const userImageMessageTemplate = document.getElementById('userImageMessageTemplate');
const botMessageTemplate = document.getElementById('botMessageTemplate');
const errorMessageTemplate = document.getElementById('errorMessageTemplate');
// State variables
let chatHistory = [];
let selectedImagesData = []; // Pour stocker plusieurs images
let conversationStarted = false;
// --- IMAGE HANDLING ---
// Upload image button click
uploadImageButton.addEventListener('click', function() {
imageInput.click();
});
// Image input change - support for multiple images
imageInput.addEventListener('change', function(e) {
const files = Array.from(e.target.files);
if (!files.length) return;
// Clear previous image container
imagePreviewContainer.innerHTML = '';
selectedImagesData = [];
// Process each file
files.forEach(file => {
// Check file type
if (!file.type.startsWith('image/')) {
alert('Veuillez sélectionner uniquement des fichiers image valides.');
return;
}
// Check file size (max 5MB)
if (file.size > 5 * 1024 * 1024) {
alert('La taille de chaque image ne doit pas dépasser 5 Mo.');
return;
}
const reader = new FileReader();
reader.onload = function(event) {
// Create preview container
const previewContainer = document.createElement('div');
previewContainer.className = 'image-preview-container';
// Create image preview
const imgPreview = document.createElement('img');
imgPreview.src = event.target.result;
imgPreview.alt = 'Image preview';
previewContainer.appendChild(imgPreview);
// Create remove button
const removeBtn = document.createElement('button');
removeBtn.className = 'remove-image-button';
removeBtn.innerHTML = '<i class="bi bi-x-circle-fill"></i>';
previewContainer.appendChild(removeBtn);
// Add preview to container
imagePreviewContainer.appendChild(previewContainer);
// Store image data
const imageData = event.target.result;
selectedImagesData.push(imageData);
// Add event listener to remove button
removeBtn.addEventListener('click', () => {
// Remove this specific image
const index = selectedImagesData.indexOf(imageData);
if (index > -1) {
selectedImagesData.splice(index, 1);
}
previewContainer.remove();
// Hide preview area if no images left
if (selectedImagesData.length === 0) {
imagePreviewArea.classList.add('hidden');
imageInput.value = '';
}
});
};
reader.readAsDataURL(file);
});
// Show preview area
imagePreviewArea.classList.remove('hidden');
// Focus on input for caption
userInput.focus();
});
// --- SIDE NAVIGATION HANDLING ---
// Toggle side navigation
toggleNavButton.addEventListener('click', function() {
sideNav.classList.add('active');
document.body.insertAdjacentHTML('beforeend', '<div class="overlay" id="navOverlay"></div>');
const overlay = document.getElementById('navOverlay');
overlay.classList.add('active');
loadChatHistoryList();
// Close side nav when clicking overlay
overlay.addEventListener('click', closeSideNav);
});
// Close side navigation
closeSideNavButton.addEventListener('click', closeSideNav);
function closeSideNav() {
sideNav.classList.remove('active');
const overlay = document.getElementById('navOverlay');
if (overlay) {
overlay.remove();
}
}
// Clear chat from nav button
if (clearButtonNav) {
clearButtonNav.addEventListener('click', function() {
clearChat(true); // With confirmation
closeSideNav();
});
}
// Settings button in side nav
if (settingsButtonNav) {
settingsButtonNav.addEventListener('click', function() {
alert('Fonctionnalité en cours de développement');
closeSideNav();
});
}
// Load chat history list
function loadChatHistoryList() {
fetch('/api/load-chats')
.then(response => response.json())
.then(data => {
if (data.error) {
chatHistoryList.innerHTML = `<div class="empty-state">${data.error}</div>`;
return;
}
if (!data.chats || data.chats.length === 0) {
chatHistoryList.innerHTML = '<div class="empty-state">Aucune conversation sauvegardée</div>';
return;
}
// Create history items
let historyHTML = '';
data.chats.forEach(chat => {
// Format timestamp (YYYYMMDD_HHMMSS to readable format)
const timestamp = chat.timestamp;
const year = timestamp.substring(0, 4);
const month = timestamp.substring(4, 6);
const day = timestamp.substring(6, 8);
const hour = timestamp.substring(9, 11);
const minute = timestamp.substring(11, 13);
const formattedDate = `${day}/${month}/${year} ${hour}:${minute}`;
historyHTML += `
<div class="chat-history-item" data-filename="${chat.filename}">
<div class="icon"><i class="bi bi-chat-dots"></i></div>
<div class="details">
<div>Conversation</div>
<div class="timestamp">${formattedDate}</div>
</div>
</div>
`;
});
chatHistoryList.innerHTML = historyHTML;
// Add click event to history items
const historyItems = chatHistoryList.querySelectorAll('.chat-history-item');
historyItems.forEach(item => {
item.addEventListener('click', function() {
const filename = this.getAttribute('data-filename');
loadChatHistory(filename);
toggleHistoryDropdown();
});
});
})
.catch(error => {
console.error('Error loading chat history:', error);
chatHistoryList.innerHTML = '<div class="empty-state">Erreur lors du chargement de l\'historique</div>';
});
}
// Load specific chat history
function loadChatHistory(filename) {
fetch(`/api/load-chat/${filename}`)
.then(response => response.json())
.then(data => {
if (data.error) {
alert(data.error);
return;
}
if (data.history) {
// Clear current chat
clearChat(false); // No confirmation needed
// Load history
chatHistory = data.history;
// Display messages
data.history.forEach(msg => {
if (msg.sender === 'user') {
const messageElement = userMessageTemplate.content.cloneNode(true);
messageElement.querySelector('p').textContent = msg.text;
chatWindow.appendChild(messageElement);
} else {
const messageElement = botMessageTemplate.content.cloneNode(true);
const messageParagraph = messageElement.querySelector('p');
if (window.marked) {
messageParagraph.innerHTML = marked.parse(msg.text);
} else {
messageParagraph.textContent = msg.text;
}
chatWindow.appendChild(messageElement);
if (window.Prism) {
const codeBlocks = messageParagraph.querySelectorAll('pre code');
codeBlocks.forEach(block => {
Prism.highlightElement(block);
});
}
}
});
// Scroll to bottom
scrollToBottom();
}
})
.catch(error => {
console.error('Error loading chat:', error);
alert('Erreur lors du chargement de la conversation.');
});
}
// Save current chat
saveCurrentChatButton.addEventListener('click', function() {
if (chatHistory.length <= 1) {
alert('Aucune conversation à sauvegarder. Veuillez d\'abord discuter avec le chatbot.');
return;
}
fetch('/api/save-chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
history: chatHistory
})
})
.then(response => response.json())
.then(data => {
if (data.error) {
alert(data.error);
} else {
alert('Conversation sauvegardée avec succès !');
loadChatHistoryList();
}
})
.catch(error => {
console.error('Error saving chat:', error);
alert('Erreur lors de la sauvegarde de la conversation.');
});
});
// --- TEXT INPUT HANDLING ---
// Auto-resize textarea based on content
userInput.addEventListener('input', function() {
this.style.height = 'auto';
this.style.height = (this.scrollHeight) + 'px';
// Reset height if empty
if (this.value === '') {
this.style.height = '';
}
});
// Send message when Enter key is pressed (without shift)
userInput.addEventListener('keydown', function(e) {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
sendMessage();
}
});
// Send message when send button is clicked
sendButton.addEventListener('click', sendMessage);
// Clear chat history when clear button is clicked
if (clearButton) {
clearButton.addEventListener('click', function() {
clearChat(true); // With confirmation
});
}
// --- CHAT FUNCTIONS ---
// Function to clear the chat history
function clearChat(withConfirmation = true) {
if (!withConfirmation || (chatHistory.length > 0 && confirm('Êtes-vous sûr de vouloir effacer toute la conversation ?'))) {
// Clear the chat window except for the welcome message
while (chatWindow.childElementCount > 1) {
chatWindow.removeChild(chatWindow.lastChild);
}
// Reset chat history but keep the welcome message
const welcomeMsg = chatHistory[0];
chatHistory = welcomeMsg ? [welcomeMsg] : [];
// Focus on input field
userInput.focus();
}
}
// Function to send message
function sendMessage() {
const message = userInput.value.trim();
// Require either text or images
if (message === '' && selectedImagesData.length === 0) return;
if (selectedImagesData.length > 0) {
// Add user message with images to UI
addUserImageMessage(message, selectedImagesData[0]); // Pour l'instant afficher seulement la première image dans l'UI
} else {
// Add user text message to UI
addUserMessage(message);
}
// Clear input field and reset height
userInput.value = '';
userInput.style.height = '';
// Show loading indicator
const loadingElement = addLoadingIndicator();
// Send message to API
sendToAPI(message, loadingElement, selectedImagesData.length > 0 ? selectedImagesData[0] : null);
// Clear image previews if any
if (selectedImagesData.length > 0) {
imagePreviewContainer.innerHTML = '';
imagePreviewArea.classList.add('hidden');
selectedImagesData = [];
imageInput.value = '';
}
}
// Add user message to chat window
function addUserMessage(message) {
// Hide welcome container if visible (first message)
if (!conversationStarted && welcomeContainer) {
welcomeContainer.style.display = 'none';
conversationStarted = true;
}
const messageElement = userMessageTemplate.content.cloneNode(true);
messageElement.querySelector('p').textContent = message;
chatWindow.appendChild(messageElement);
// Add to chat history
chatHistory.push({
sender: 'user',
text: message
});
// Scroll to bottom
scrollToBottom();
}
// Add user message with image to chat window
function addUserImageMessage(message, imageData) {
// Hide welcome container if visible (first message)
if (!conversationStarted && welcomeContainer) {
welcomeContainer.style.display = 'none';
conversationStarted = true;
}
const messageElement = userImageMessageTemplate.content.cloneNode(true);
// Set image source
const imageElement = messageElement.querySelector('.chat-image');
imageElement.src = imageData;
// Set message text if any
const textElement = messageElement.querySelector('p');
if (message) {
textElement.textContent = message;
} else {
textElement.style.display = 'none'; // Hide text element if no message
}
chatWindow.appendChild(messageElement);
// Add to chat history (we don't add the image to history, just the text)
chatHistory.push({
sender: 'user',
text: message || 'Image envoyée' // Default text if no message provided
});
// Scroll to bottom
scrollToBottom();
}
// Add bot message to chat window with markdown support
function addBotMessage(message) {
// Hide welcome container if visible (first message)
if (!conversationStarted && welcomeContainer) {
welcomeContainer.style.display = 'none';
conversationStarted = true;
}
const messageElement = botMessageTemplate.content.cloneNode(true);
const messageParagraph = messageElement.querySelector('p');
// Use the marked library to parse Markdown if available
if (window.marked) {
messageParagraph.innerHTML = marked.parse(message);
} else {
messageParagraph.textContent = message;
}
chatWindow.appendChild(messageElement);
// Add syntax highlighting to code blocks if Prism is available
if (window.Prism) {
const codeBlocks = messageParagraph.querySelectorAll('pre code');
codeBlocks.forEach(block => {
Prism.highlightElement(block);
});
}
// Add to chat history
chatHistory.push({
sender: 'bot',
text: message
});
// Scroll to bottom
scrollToBottom();
}
// Add loading indicator to chat window
function addLoadingIndicator() {
const loadingElement = loadingTemplate.content.cloneNode(true);
chatWindow.appendChild(loadingElement);
// Scroll to bottom
scrollToBottom();
// Return the loading element so it can be removed later
return chatWindow.lastElementChild;
}
// Add error message to chat window
function addErrorMessage(error, retryMessage, retryImage) {
const errorElement = errorMessageTemplate.content.cloneNode(true);
errorElement.querySelector('p').textContent = error;
// Add retry functionality if a message to retry is provided
if (retryMessage || retryImage) {
const retryButton = errorElement.querySelector('.retry-button');
retryButton.addEventListener('click', function() {
// Remove the error message
this.closest('.message-container').remove();
// Show loading indicator
const loadingElement = addLoadingIndicator();
// Retry sending the message
sendToAPI(retryMessage, loadingElement, retryImage);
});
} else {
// Hide retry button if no retry message
errorElement.querySelector('.retry-button').style.display = 'none';
}
chatWindow.appendChild(errorElement);
// Scroll to bottom
scrollToBottom();
}
// Send message to API
function sendToAPI(message, loadingElement, imageData = null) {
// Disable input while processing
userInput.disabled = true;
sendButton.disabled = true;
uploadImageButton.disabled = true;
if (clearButton) clearButton.disabled = true;
// Prepare request data
const requestData = {
message: message,
history: chatHistory
};
// Add image data if provided
if (imageData) {
requestData.image = imageData;
}
fetch('/api/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(requestData)
})
.then(response => {
if (!response.ok) {
throw new Error(`Server responded with status: ${response.status}`);
}
return response.json();
})
.then(data => {
// Remove loading indicator
if (loadingElement) {
loadingElement.remove();
}
// Check for error
if (data.error) {
addErrorMessage(data.error, message, imageData);
} else {
// Add bot response
addBotMessage(data.response);
}
})
.catch(error => {
console.error('Error:', error);
// Remove loading indicator
if (loadingElement) {
loadingElement.remove();
}
// Add error message
addErrorMessage('Désolé, il y a eu un problème de connexion avec le serveur. Veuillez réessayer.', message, imageData);
})
.finally(() => {
// Re-enable input
userInput.disabled = false;
sendButton.disabled = false;
uploadImageButton.disabled = false;
if (clearButton) clearButton.disabled = false;
userInput.focus();
});
}
// Scroll chat window to bottom
function scrollToBottom() {
chatWindow.scrollTop = chatWindow.scrollHeight;
}
// Setup suggestion bubbles click handlers
if (suggestionBubbles) {
suggestionBubbles.forEach(bubble => {
bubble.addEventListener('click', function() {
const prompt = this.getAttribute('data-prompt');
if (prompt) {
userInput.value = prompt;
sendMessage();
}
});
});
}
// Initial focus on input field
userInput.focus();
});
|