EVOLUTION-NINJA
Edit File: index.js
document.addEventListener('DOMContentLoaded', function () { /// Fetch messages from the backend API (GET) async function fetchMessagesFromAPI() { try { const response = await fetch('https://jayblues.in/taskpage/messages'); if (response.ok) { const data = await response.json(); console.log(data) return data || []; // Always return the array of messages } else { console.error('Failed to fetch messages'); return []; } } catch (error) { console.error('Error fetching messages:', error); return []; } } // Function to send new messages to the backend API (POST) async function sendMessagesToAPI(message) { try { const response = await fetch('https://jayblues.in/taskpage/messages', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(message), // Send a single message object }); if (response.ok) { console.log('Message sent successfully'); await fetchAndRenderMessages(); // Fetch and render messages after sending } else { console.error('Failed to send message'); } } catch (error) { console.error('Error sending message:', error); } } let chatMessages = []; // This will store the messages fetched from the API // Fetch and render messages async function fetchAndRenderMessages() { chatMessages = await fetchMessagesFromAPI(); // Fetch messages from the API renderMessages(); // Render messages } // Render messages on page load async function init() { await fetchAndRenderMessages(); // Fetch and render messages initially } // Call init on page load init(); // Function to render chat messages function renderMessages() { const messagesContainer = document.getElementById('messagesContainer'); messagesContainer.innerHTML = ''; // Clear the container before rendering new messages // Loop through the messages and render each one chatMessages.forEach((message) => { const messageDiv = document.createElement('div'); messageDiv.classList.add('chat-message'); // Render message content based on type if (message.type === 'text') { messageDiv.innerHTML = ` <p class="your-name me-2">You</p> <p class="messages-from-you me-2">${message.content}</p> `; } else if (message.type === 'image') { messageDiv.innerHTML = ` <p class="your-name me-2">You</p> <p class="messages-from-you me-2"> <img src="${message.content}" alt="Uploaded Image" style="max-width: 200px;" /> </p> `; } else if (message.type === 'audio') { messageDiv.innerHTML = ` <p class="your-name me-2">You</p> <p class="messages-from-you me-2"> <audio controls src="${message.content}"></audio> </p> `; } else if (message.type === 'document') { messageDiv.innerHTML = ` <p class="your-name me-2">You</p> <p class="messages-from-you me-2"> <a href="${message.content}" target="_blank">${message.fileName}</a> </p> `; } else if (message.type === 'video') { messageDiv.innerHTML = ` <p class="your-name me-2">You</p> <p class="messages-from-you me-2"> <video controls src="${message.content}" style="max-width: 200px;"></video> </p> `; } messagesContainer.appendChild(messageDiv); }); scrollToBottom(); // Scroll to the latest message } // Scroll to the latest message in the chat function scrollToBottom() { const div = document.getElementById('messagesContainer'); div.scrollTop = div.scrollHeight; // Scroll to the bottom of the container } // Scroll to the latest message in the chat function scrollToBottom() { const div = document.getElementById('messagesContainer'); div.scrollTop = div.scrollHeight; } // // Add text message to chat // document.getElementById('send-text').addEventListener('click', function () { // const message = document.getElementById('text-message').value; // if (message) { // chatMessages.push({ content: message, type: 'text' }); // saveMessages(); // Save messages to localStorage // renderMessages(); // Re-render chat // document.getElementById('text-message').value = ''; // Clear input // toggleSendButton(); // Hide send button after sending // } // }); // -------------------------------------------------------------------------------------------- // changed text message js document.getElementById('send-text').addEventListener('click', function (event) { event.preventDefault(); // Prevent the page reload const message = document.getElementById('text-message').value; if (message) { const newMessage = { content: message, type: 'text' }; // Create a new message object chatMessages.push(newMessage); // Add to the local array sendMessagesToAPI(newMessage); // Send to backend immediately // Re-render chat document.getElementById('text-message').value = ''; // Clear input // Reset the height of the textarea to the initial height document.getElementById('text-message').style.height = '40px'; toggleSendButton(); // Hide send button after sending } }); // -------------------------------------------------------------------------------------------- // Toggle send button visibility based on input field const messageInput = document.querySelector('.message-input'); const inputBar = document.querySelector('.input-bar'); messageInput.addEventListener('input', () => { toggleSendButton(); }); // Function to toggle send button visibility function toggleSendButton() { const sendButton = document.getElementById('send-text'); if (messageInput.value.trim() !== '') { inputBar.classList.add('show-send-button'); // Show send button sendButton.style.display = 'inline'; // Ensure send button is visible } else { inputBar.classList.remove('show-send-button'); // Hide send button sendButton.style.display = 'none'; // Hide send button } } // Initially hide send button toggleSendButton(); const raiseHandButton = document.getElementById('raise-hand'); raiseHandButton.addEventListener('click', function () { const raisehand = { content: '✋', type: 'text' }; chatMessages.push(raisehand); sendMessagesToAPI(raisehand); // Send to backend immediately }); // Camera functionality const cameraLink = document.getElementById('cameraLink'); const cameraContainer = document.getElementById('cameraContainer'); const video = document.getElementById('cameraStream'); const captureButton = document.getElementById('captureButton'); const cancelButton = document.getElementById('cancelButton'); // Cancel button const canvas = document.getElementById('cameraCanvas'); cameraLink.addEventListener('click', function (event) { event.preventDefault(); openCamera(); }); function openCamera() { cameraContainer.style.display = 'block'; navigator.mediaDevices.getUserMedia({ video: true }) .then((stream) => { video.srcObject = stream; }) .catch((error) => { console.error('Camera access error:', error); }); } captureButton.addEventListener('click', function () { const context = canvas.getContext('2d'); canvas.width = video.videoWidth; canvas.height = video.videoHeight; context.drawImage(video, 0, 0, canvas.width, canvas.height); const imageDataUrl = canvas.toDataURL('image/png'); stopCameraStream(); // Stop camera after capture cameraContainer.style.display = 'none'; tempMedia = { type: 'image', content: imageDataUrl }; // Store in temp until confirmation showImagePreview(imageDataUrl); // Show image preview before adding to chat }); // Stop the camera stream function stopCameraStream() { const stream = video.srcObject; const tracks = stream.getTracks(); tracks.forEach(track => track.stop()); // Stop all camera tracks } // Cancel camera capture cancelButton.addEventListener('click', function () { stopCameraStream(); // Stop the camera stream cameraContainer.style.display = 'none'; // Hide camera container tempMedia = { type: null, content: null }; // Clear temp data }); // Show image preview function showImagePreview(imageUrl) { const imagePreviewContainer = document.getElementById('imagePreviewContainer'); const imagePreview = document.getElementById('imagePreview'); imagePreview.src = imageUrl; imagePreviewContainer.style.display = 'block'; resetImagePreviewListeners(); // Reset listeners for confirm and cancel buttons } // // Plus Icon Upload Options // const plusIcon = document.getElementById('plus-icon'); // const uploadOptions = document.getElementById('upload-options'); // const imageUploadInput = document.getElementById('image-upload'); // const fileUploadInput = document.getElementById('file-upload'); // // Handle plus icon click to show upload options // plusIcon.addEventListener('click', function () { // uploadOptions.style.display = uploadOptions.style.display === 'block' ? 'none' : 'block'; // }); // // Handle image upload preview and convert to Base64 // document.getElementById('select-image').addEventListener('click', function () { // imageUploadInput.click(); // }); // imageUploadInput.addEventListener('change', function (event) { // const file = event.target.files[0]; // if (file) { // const reader = new FileReader(); // reader.onload = function (e) { // showImagePreview(e.target.result); // Base64 format // }; // reader.readAsDataURL(file); // Convert to Base64 // } // }); // // Show image preview // function showImagePreview(imageUrl) { // const imagePreviewContainer = document.getElementById('imagePreviewContainer'); // const imagePreview = document.getElementById('imagePreview'); // imagePreview.src = imageUrl; // imagePreviewContainer.style.display = 'block'; // resetImagePreviewListeners(); // Reset the listeners for confirm and cancel buttons // } // // Handle file upload preview and convert to Base64 // document.getElementById('select-file').addEventListener('click', function () { // fileUploadInput.click(); // }); // fileUploadInput.addEventListener('change', function (event) { // const file = event.target.files[0]; // if (file) { // const reader = new FileReader(); // reader.onload = function (e) { // showFilePreview(file.name, e.target.result); // Base64 format // }; // reader.readAsDataURL(file); // Convert to Base64 // } // }); // // Show file preview // function showFilePreview(fileName, fileContentBase64) { // const filePreviewContainer = document.getElementById('filePreviewContainer'); // const filePreviewName = document.getElementById('filePreviewName'); // filePreviewName.textContent = `Selected File: ${fileName}`; // filePreviewContainer.style.display = 'block'; // resetFilePreviewListeners(fileContentBase64); // Reset the listeners for confirm and cancel buttons // } // // Reset listeners for image preview // function resetImagePreviewListeners() { // const confirmImageButton = document.getElementById('confirmImageButton'); // const cancelImagePreview = document.getElementById('cancelImagePreview'); // // Remove existing event listeners // confirmImageButton.replaceWith(confirmImageButton.cloneNode(true)); // cancelImagePreview.replaceWith(cancelImagePreview.cloneNode(true)); // document.getElementById('confirmImageButton').addEventListener('click', function () { // chatMessages.push({ content: document.getElementById('imagePreview').src, type: 'image' }); // saveMessages(); // renderMessages(); // document.getElementById('imagePreviewContainer').style.display = 'none'; // resetFileInput(imageUploadInput); // Reset the input after confirming // }); // document.getElementById('cancelImagePreview').addEventListener('click', function () { // document.getElementById('imagePreviewContainer').style.display = 'none'; // resetFileInput(imageUploadInput); // Reset the input after canceling // }); // } // // Reset listeners for file preview // function resetFilePreviewListeners(fileContentBase64) { // const confirmFileButton = document.getElementById('confirmFileButton'); // const cancelFilePreview = document.getElementById('cancelFilePreview'); // // Remove existing event listeners // confirmFileButton.replaceWith(confirmFileButton.cloneNode(true)); // cancelFilePreview.replaceWith(cancelFilePreview.cloneNode(true)); // document.getElementById('confirmFileButton').addEventListener('click', function () { // chatMessages.push({ content: fileContentBase64, type: 'document' }); // saveMessages(); // renderMessages(); // document.getElementById('filePreviewContainer').style.display = 'none'; // resetFileInput(fileUploadInput); // Reset the input after confirming // }); // document.getElementById('cancelFilePreview').addEventListener('click', function () { // document.getElementById('filePreviewContainer').style.display = 'none'; // resetFileInput(fileUploadInput); // Reset the input after canceling // }); // } // // Function to reset file input to allow re-upload of the same file in Chrome // function resetFileInput(inputElement) { // inputElement.value = ''; // Reset the file input element to ensure the same file can be selected again // } // -------------------------------------------------- // const plusIcon = document.getElementById('plus-icon'); // const uploadOptions = document.getElementById('upload-options'); // const imageUploadInput = document.getElementById('image-upload'); // const fileUploadInput = document.getElementById('file-upload'); // // Mapping of file extensions to icons // const fileIcons = { // '.doc': 'assets/google-docs (1).png', // Replace with the path to your Word icon // '.docx': 'assets/google-docs (1).png', // Replace with the path to your Word icon // '.xls': 'assets/xls.png', // Replace with the path to your Excel icon // '.xlsx': 'assets/sheets.png', // Replace with the path to your Excel icon // '.pdf': 'assets/pdfimg.png', // Replace with the path to your PDF icon // '.ppt': 'assets/ppt.png', // Replace with the path to your PowerPoint icon // '.pptx': 'assets/pptx-file.png', // Replace with the path to your PowerPoint icon // // Add more mappings as needed // }; // // Handle plus icon click to show upload options // plusIcon.addEventListener('click', function () { // uploadOptions.style.display = uploadOptions.style.display === 'block' ? 'none' : 'block'; // }); // // Handle image upload preview and convert to Base64 // document.getElementById('select-image').addEventListener('click', function () { // imageUploadInput.click(); // }); // imageUploadInput.addEventListener('change', function (event) { // const file = event.target.files[0]; // if (file) { // const reader = new FileReader(); // reader.onload = function (e) { // showImagePreview(e.target.result); // Base64 format // }; // reader.readAsDataURL(file); // Convert to Base64 // } // }); // // Show image preview // function showImagePreview(imageUrl) { // const imagePreviewContainer = document.getElementById('imagePreviewContainer'); // const imagePreview = document.getElementById('imagePreview'); // imagePreview.src = imageUrl; // imagePreviewContainer.style.display = 'block'; // resetImagePreviewListeners(); // Reset the listeners for confirm and cancel buttons // } // // Handle file upload preview and convert to Base64 // document.getElementById('select-file').addEventListener('click', function () { // fileUploadInput.click(); // }); // fileUploadInput.addEventListener('change', function (event) { // const file = event.target.files[0]; // if (file) { // const reader = new FileReader(); // reader.onload = function (e) { // showFilePreview(file.name, e.target.result, file.type); // Pass the file type // }; // reader.readAsDataURL(file); // Convert to Base64 // } // }); // // Show file preview in the same container // function showFilePreview(fileName, fileContentBase64, fileType) { // const filePreviewContainer = document.getElementById('filePreviewContainer'); // const filePreviewName = document.getElementById('filePreviewName'); // const previewContent = document.getElementById('previewContent'); // filePreviewName.textContent = `Selected File: ${fileName}`; // filePreviewContainer.style.display = 'block'; // // Clear previous preview content // previewContent.innerHTML = ''; // // Get the file extension // const fileExtension = fileName.split('.').pop().toLowerCase(); // const iconSrc = fileIcons['.' + fileExtension] || 'path/to/default-icon.png'; // Default icon if extension not found // // Display different types of previews // if (fileType.startsWith('image/')) { // const img = document.createElement('img'); // img.src = fileContentBase64; // img.style.width = '100%'; // Make the image responsive // previewContent.appendChild(img); // } else if (fileType.startsWith('application/pdf')) { // const pdfCanvas = document.createElement('canvas'); // pdfCanvas.style.width = '100%'; // previewContent.appendChild(pdfCanvas); // renderPDF(fileContentBase64, pdfCanvas); // Render PDF to canvas // } else { // // Create an image element for the corresponding file type // const fileIcon = document.createElement('img'); // fileIcon.src = iconSrc; // Set the image source based on the file extension // fileIcon.alt = 'File icon'; // fileIcon.style.width = '100px'; // Set a fixed width for the icon // fileIcon.style.display = 'block'; // Center the image // fileIcon.style.margin = '0 auto'; // Center the icon horizontally // previewContent.appendChild(fileIcon); // Add the icon to the preview content // } // resetFilePreviewListeners(fileContentBase64); // Reset the listeners for confirm and cancel buttons // } // // Function to render PDF using PDF.js // async function renderPDF(pdfBase64, canvas) { // const pdfData = atob(pdfBase64.split(',')[1]); // Decode Base64 to binary // const loadingTask = pdfjsLib.getDocument({ data: pdfData }); // loadingTask.promise.then(pdf => { // pdf.getPage(1).then(page => { // const viewport = page.getViewport({ scale: 1.5 }); // Scale for better readability // canvas.width = viewport.width; // canvas.height = viewport.height; // const renderContext = { // canvasContext: canvas.getContext('2d'), // viewport: viewport // }; // page.render(renderContext); // }); // }).catch(error => { // console.error('Error rendering PDF:', error); // const errorMsg = document.createElement('p'); // errorMsg.textContent = 'Failed to render PDF.'; // canvas.parentNode.appendChild(errorMsg); // }); // } // // Reset listeners for image preview // function resetImagePreviewListeners() { // const confirmImageButton = document.getElementById('confirmImageButton'); // const cancelImagePreview = document.getElementById('cancelImagePreview'); // // Remove existing event listeners // confirmImageButton.replaceWith(confirmImageButton.cloneNode(true)); // cancelImagePreview.replaceWith(cancelImagePreview.cloneNode(true)); // document.getElementById('confirmImageButton').addEventListener('click', function () { // chatMessages.push({ content: document.getElementById('imagePreview').src, type: 'image' }); // saveMessages(); // renderMessages(); // document.getElementById('imagePreviewContainer').style.display = 'none'; // resetFileInput(imageUploadInput); // Reset the input after confirming // }); // document.getElementById('cancelImagePreview').addEventListener('click', function () { // document.getElementById('imagePreviewContainer').style.display = 'none'; // resetFileInput(imageUploadInput); // Reset the input after canceling // }); // } // // Reset listeners for file preview // function resetFilePreviewListeners(fileContentBase64) { // const confirmFileButton = document.getElementById('confirmFileButton'); // const cancelFilePreview = document.getElementById('cancelFilePreview'); // // Remove existing event listeners // confirmFileButton.replaceWith(confirmFileButton.cloneNode(true)); // cancelFilePreview.replaceWith(cancelFilePreview.cloneNode(true)); // document.getElementById('confirmFileButton').addEventListener('click', function () { // chatMessages.push({ content: fileContentBase64, type: 'document' }); // saveMessages(); // renderMessages(); // document.getElementById('filePreviewContainer').style.display = 'none'; // resetFileInput(fileUploadInput); // Reset the input after confirming // }); // document.getElementById('cancelFilePreview').addEventListener('click', function () { // document.getElementById('filePreviewContainer').style.display = 'none'; // resetFileInput(fileUploadInput); // Reset the input after canceling // }); // } // // Function to reset file input to allow re-upload of the same file in Chrome // function resetFileInput(inputElement) { // inputElement.value = ''; // Reset the file input element to ensure the same file can be selected again // } // -------------------------------------------------- // plus icon updates const plusIcon = document.getElementById('plus-icon'); const uploadOptions = document.getElementById('upload-options'); const imageUploadInput = document.getElementById('image-upload'); const fileUploadInput = document.getElementById('file-upload'); // Mapping of file extensions to icons const fileIcons = { '.doc': 'assets/google-docs (1).png', // Replace with the path to your Word icon '.docx': 'assets/google-docs (1).png', // Replace with the path to your Word icon '.xls': 'assets/xls.png', // Replace with the path to your Excel icon '.xlsx': 'assets/sheets.png', // Replace with the path to your Excel icon '.pdf': 'assets/pdfimg.png', // Replace with the path to your PDF icon '.ppt': 'assets/ppt.png', // Replace with the path to your PowerPoint icon '.pptx': 'assets/pptx-file.png', // Replace with the path to your PowerPoint icon // Add more mappings as needed }; // Handle plus icon click to show upload options plusIcon.addEventListener('click', function () { uploadOptions.style.display = uploadOptions.style.display === 'block' ? 'none' : 'block'; }); // Handle image upload preview and convert to Base64 document.getElementById('select-image').addEventListener('click', function () { imageUploadInput.click(); }); imageUploadInput.addEventListener('change', function (event) { const file = event.target.files[0]; if (file) { const reader = new FileReader(); reader.onload = function (e) { showImagePreview(e.target.result); // Base64 format }; reader.readAsDataURL(file); // Convert to Base64 } }); // Show image preview function showImagePreview(imageUrl) { const imagePreviewContainer = document.getElementById('imagePreviewContainer'); const imagePreview = document.getElementById('imagePreview'); imagePreview.src = imageUrl; imagePreviewContainer.style.display = 'block'; resetImagePreviewListeners(); // Reset the listeners for confirm and cancel buttons } // Handle file upload preview and convert to Base64 document.getElementById('select-file').addEventListener('click', function () { fileUploadInput.click(); }); fileUploadInput.addEventListener('change', function (event) { const file = event.target.files[0]; if (file) { const reader = new FileReader(); reader.onload = function (e) { showFilePreview(file.name, e.target.result, file.type, file); // Pass the file object }; reader.readAsDataURL(file); // Convert to Base64 } }); function showFilePreview(fileName, fileContentBase64, fileType, file) { const filePreviewContainer = document.getElementById('filePreviewContainer'); const filePreviewName = document.getElementById('filePreviewName'); const previewContent = document.getElementById('previewContent'); filePreviewName.textContent = `Selected File: ${fileName}`; filePreviewContainer.style.display = 'block'; // Clear previous preview content previewContent.innerHTML = ''; // Get the file extension const fileExtension = fileName.split('.').pop().toLowerCase(); const iconSrc = fileIcons['.' + fileExtension] || 'path/to/default-icon.png'; // Default icon if extension not found // Display different types of previews if (fileType.startsWith('image/')) { const img = document.createElement('img'); img.src = fileContentBase64; img.style.width = '100%'; // Make the image responsive previewContent.appendChild(img); } else if (fileType.startsWith('application/pdf')) { const pdfCanvas = document.createElement('canvas'); pdfCanvas.style.width = '100%' previewContent.appendChild(pdfCanvas); renderPDF(fileContentBase64, pdfCanvas); // Render PDF to canvas } else { // Create an image element for the corresponding file type const fileIcon = document.createElement('img'); fileIcon.src = iconSrc; // Set the image source based on the file extension fileIcon.alt = 'File icon'; fileIcon.style.width = '100px'; // Set a fixed width for the icon fileIcon.style.display = 'block'; // Center the image fileIcon.style.margin = '0 auto'; // Center the icon horizontally previewContent.appendChild(fileIcon); // Add the icon to the preview content } resetFilePreviewListeners(fileContentBase64, file); // Pass the file to reset listeners } // Function to render PDF using PDF.js async function renderPDF(pdfBase64, canvas) { const pdfData = atob(pdfBase64.split(',')[1]); // Decode Base64 to binary const loadingTask = pdfjsLib.getDocument({ data: pdfData }); loadingTask.promise.then(pdf => { pdf.getPage(1).then(page => { const viewport = page.getViewport({ scale: 1.5 }); // Scale for better readability canvas.width = viewport.width; canvas.height = viewport.height; const renderContext = { canvasContext: canvas.getContext('2d'), viewport: viewport }; page.render(renderContext); }); }).catch(error => { console.error('Error rendering PDF:', error); const errorMsg = document.createElement('p'); errorMsg.textContent = 'Failed to render PDF.'; canvas.parentNode.appendChild(errorMsg); }); } // Reset listeners for image preview function resetImagePreviewListeners() { const confirmImageButton = document.getElementById('confirmImageButton'); const cancelImagePreview = document.getElementById('cancelImagePreview'); // Remove existing event listeners confirmImageButton.replaceWith(confirmImageButton.cloneNode(true)); cancelImagePreview.replaceWith(cancelImagePreview.cloneNode(true)); document.getElementById('confirmImageButton').addEventListener('click', function () { const imagesend = { content: document.getElementById('imagePreview').src, type: 'image' }; chatMessages.push(imagesend); sendMessagesToAPI(imagesend); // Send to backend immediately document.getElementById('imagePreviewContainer').style.display = 'none'; resetFileInput(imageUploadInput); // Reset the input after confirming }); document.getElementById('cancelImagePreview').addEventListener('click', function () { document.getElementById('imagePreviewContainer').style.display = 'none'; resetFileInput(imageUploadInput); // Reset the input after canceling }); } function resetFilePreviewListeners(fileContentBase64, file) { const confirmFileButton = document.getElementById('confirmFileButton'); const cancelFilePreview = document.getElementById('cancelFilePreview'); // Remove existing event listeners confirmFileButton.replaceWith(confirmFileButton.cloneNode(true)); cancelFilePreview.replaceWith(cancelFilePreview.cloneNode(true)); document.getElementById('confirmFileButton').addEventListener('click', function () { const dataUrl = `data:${file.type};base64,${fileContentBase64.split(',')[1]}`; // Create a valid data URL const filesend = { content: dataUrl, type: 'document', fileName: file.name }; chatMessages.push(filesend); sendMessagesToAPI(filesend); // Send to backend immediately document.getElementById('filePreviewContainer').style.display = 'none'; resetFileInput(fileUploadInput); // Reset the input after confirming }); document.getElementById('cancelFilePreview').addEventListener('click', function () { document.getElementById('filePreviewContainer').style.display = 'none'; resetFileInput(fileUploadInput); // Reset the input after canceling }); } // Function to reset file input to allow re-upload of the same file in Chrome function resetFileInput(inputElement) { inputElement.value = ''; // Reset the file input element to ensure the same file can be selected again } // Video Recording Functionality const startVideoRecordingButton = document.getElementById('startVideoRecording'); const stopVideoRecordingButton = document.getElementById('stopVideoRecording'); const videoPreviewContainer = document.getElementById('videoPreviewContainer'); const videoPreview = document.getElementById('videoPreview'); let videoRecorder; let videoChunks = []; // Start Video Recording startVideoRecordingButton.addEventListener('click', function () { navigator.mediaDevices.getUserMedia({ video: true, audio: true }) .then((stream) => { videoRecorder = new MediaRecorder(stream); videoRecorder.start(); video.srcObject = stream; video.play(); startVideoRecordingButton.style.display = 'none'; stopVideoRecordingButton.style.display = 'inline'; videoRecorder.addEventListener('dataavailable', (event) => { videoChunks.push(event.data); }); }) .catch((err) => { console.error('Camera or microphone access denied or error:', err); }); }); // Stop Video Recording and convert to Base64 stopVideoRecordingButton.addEventListener('click', function () { videoRecorder.stop(); stopVideoRecordingButton.style.display = 'none'; startVideoRecordingButton.style.display = 'inline'; videoRecorder.addEventListener('stop', () => { const videoBlob = new Blob(videoChunks, { type: 'video/mp4' }); const reader = new FileReader(); reader.onloadend = function () { const videoBase64 = reader.result; // Base64 format tempMedia = { type: 'video', content: videoBase64 }; // Store in temp until confirmation videoPreview.src = videoBase64; videoPreviewContainer.style.display = 'block'; resetVideoPreviewListeners(); // Reset listeners for video videoChunks = []; // Reset video chunks for the next recording }; reader.readAsDataURL(videoBlob); // Convert to Base64 stopCameraStream(); // Stop the camera stream cameraContainer.style.display = 'none'; // Hide camera container }); }); // Reset Video Preview Listeners function resetVideoPreviewListeners() { const confirmVideoButton = document.getElementById('confirmVideoButton'); const cancelVideoPreview = document.getElementById('cancelVideoPreview'); confirmVideoButton.onclick = function () { const videosend = { content: tempMedia.content, type: 'video' }; chatMessages.push(videosend); sendMessagesToAPI(videosend); // Send to backend immediately videoPreviewContainer.style.display = 'none'; tempMedia = { type: null, content: null }; // Clear temp data }; cancelVideoPreview.onclick = function () { videoPreviewContainer.style.display = 'none'; tempMedia = { type: null, content: null }; // Clear temp data }; } // ----------------------------- // Voice Recording functionality const startRecordingButton = document.getElementById('startRecording'); const stopRecordingButton = document.getElementById('stopRecording'); const cancelRecordingButton = document.getElementById('cancelRecording'); const cancelPreviewButton = document.getElementById('cancelPreview'); // New cancel button for preview const audioPreview = document.getElementById('audioPreview'); const addRecordingButton = document.getElementById('addRecording'); const recordContainer = document.getElementById('recordContainer'); let mediaRecorder; let audioChunks = []; // Start recording startRecordingButton.addEventListener('click', function () { navigator.mediaDevices.getUserMedia({ audio: true }) .then((stream) => { mediaRecorder = new MediaRecorder(stream); mediaRecorder.start(); // Change button visibility during recording startRecordingButton.style.display = 'none'; stopRecordingButton.style.display = 'flex'; stopRecordingButton.style.alignItems = 'center'; cancelRecordingButton.style.display = 'inline-block'; recordContainer.style.display = 'flex'; // Show the record container mediaRecorder.addEventListener('dataavailable', (event) => { audioChunks.push(event.data); }); }) .catch((err) => { console.error('Microphone access denied or error:', err); }); }); // Stop recording and preview the audio stopRecordingButton.addEventListener('click', function () { mediaRecorder.stop(); stopRecordingButton.style.display = 'none'; startRecordingButton.style.display = 'inline'; cancelRecordingButton.style.display = 'none'; mediaRecorder.addEventListener('stop', () => { const audioBlob = new Blob(audioChunks, { type: 'audio/wav' }); // Convert Blob to base64 const reader = new FileReader(); reader.readAsDataURL(audioBlob); // Convert blob to base64 reader.onloadend = function () { const base64Audio = reader.result; // Show the audio preview and option to add to chat audioPreview.src = base64Audio; audioPreview.style.display = 'inline-block'; addRecordingButton.style.display = 'inline-block'; cancelPreviewButton.style.display = 'inline-block'; // Show cancel button in preview audioChunks = []; // Reset the chunks for the next recording }; }); }); // Cancel recording cancelRecordingButton.addEventListener('click', function () { if (mediaRecorder && mediaRecorder.state !== 'inactive') { mediaRecorder.stop(); } // Reset button visibility and hide the record container stopRecordingButton.style.display = 'none'; startRecordingButton.style.display = 'inline'; cancelRecordingButton.style.display = 'none'; recordContainer.style.display = 'none'; // Hide the record container // Hide preview and reset everything audioPreview.src = ''; audioPreview.style.display = 'none'; addRecordingButton.style.display = 'none'; audioChunks = []; }); // Cancel in preview mode cancelPreviewButton.addEventListener('click', function () { // Hide everything related to the preview audioPreview.src = ''; audioPreview.style.display = 'none'; addRecordingButton.style.display = 'none'; cancelPreviewButton.style.display = 'none'; recordContainer.style.display = 'none'; audioChunks = []; }); // Add recording to chat addRecordingButton.addEventListener('click', function () { const base64Audio = audioPreview.src; if (base64Audio) { appendAudioToChat(base64Audio); // Reset preview and hide controls audioPreview.src = ''; audioPreview.style.display = 'none'; addRecordingButton.style.display = 'none'; cancelPreviewButton.style.display = 'none'; // Hide preview cancel button recordContainer.style.display = 'none'; // Hide the record container after adding to chat } }); // Append base64 audio to chat function appendAudioToChat(base64Audio) { const audiosend = { content: base64Audio, type: 'audio' }; chatMessages.push(audiosend); sendMessagesToAPI(audiosend); // Send to backend immediately } // ------------------------------------------------ // Progress Bar Functionality const modal = document.getElementById('myModal'); const openModal = document.getElementById('openModal'); const closeModal = document.getElementById('closeModal'); const percentInput = document.getElementById('percentInput'); const percentValue = document.getElementById('percentValue'); const progressBar = document.querySelector('.progress-bar'); const submitButton = document.getElementById('submitButton'); const progressBar1 = document.querySelector('.progress-bar-1'); const percentValue1 = document.getElementById('percentValue-1'); const circumference = 440; openModal.addEventListener('click', function (event) { event.preventDefault(); modal.style.display = 'flex'; }); closeModal.addEventListener('click', function () { modal.style.display = 'none'; }); window.addEventListener('click', function (event) { if (event.target === modal) { modal.style.display = 'none'; } }); percentInput.addEventListener('input', function () { const value = parseInt(percentInput.value, 10); if (value >= 0 && value <= 100) { updateProgressBar(progressBar, value); updateDisplay(value, percentValue); } }); submitButton.addEventListener('click', function () { const value = parseInt(percentInput.value, 10); if (value >= 0 && value <= 100) { updateProgressBar(progressBar1, value); updateDisplay(value, percentValue1); modal.style.display = 'none'; } }); function updateProgressBar(element, value) { if (element) { const offset = circumference - (value / 100) * circumference; element.style.strokeDashoffset = offset; } } function updateDisplay(value, displayElement) { if (displayElement) { displayElement.innerHTML = `${value}<span>%</span>`; } } // Tabs functionality const tabs = document.querySelectorAll('.navtab'); const contents = document.querySelectorAll('.content'); const underline = document.querySelector('.underline'); function updateUnderline() { const activeTab = document.querySelector('.navtab.active'); underline.style.width = `${activeTab.offsetWidth}px`; underline.style.left = `${activeTab.offsetLeft}px`; } tabs.forEach(tab => { tab.addEventListener('click', () => { tabs.forEach(t => t.classList.remove('active')); tab.classList.add('active'); const target = tab.getAttribute('data-target'); contents.forEach(content => { if (content.id === target) { content.classList.add('active'); } else { content.classList.remove('active'); } }); updateUnderline(); // Scroll to bottom for chat updates if (target === 'updates') { setTimeout(scrollToBottom, 100); } }); }); window.addEventListener('resize', updateUnderline); updateUnderline(); });