Chatbot / static /js /chat.js
HARI KRISHNA
initial
ec1988c
// DOM Elements
const chatMessages = document.getElementById('chatMessages');
const userInput = document.getElementById('userInput');
const sendButton = document.getElementById('sendButton');
const languageSelect = document.getElementById('languageSelect');
// Initialize chat
document.addEventListener('DOMContentLoaded', () => {
loadChatHistory();
setupEventListeners();
});
// Set up event listeners
function setupEventListeners() {
// Send button click
sendButton.addEventListener('click', sendMessage);
// Enter key press
userInput.addEventListener('keypress', handleKeyPress);
// Input focus
userInput.addEventListener('focus', () => {
userInput.style.borderColor = '#00205b';
});
// Input blur
userInput.addEventListener('blur', () => {
userInput.style.borderColor = '#dee2e6';
});
}
// Handle keyboard input
function handleKeyPress(event) {
if (event.key === 'Enter' && !event.shiftKey) {
event.preventDefault();
sendMessage();
}
}
// Send message to backend
async function sendMessage() {
const message = userInput.value.trim();
const language = languageSelect.value;
if (!message) {
return;
}
// Add user message to chat
addMessage(message, 'user', language);
// Clear input
userInput.value = '';
// Show loading
showLoading(true);
try {
// Send to backend
const response = await fetch('/api/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
message: message,
language: language
})
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
// Add bot response to chat
if (data.response) {
addMessage(data.response, 'bot', language, data.type);
} else if (data.error) {
addMessage(`Error: ${data.error}`, 'bot', language, 'error');
}
} catch (error) {
console.error('Error sending message:', error);
addMessage('Sorry, I encountered an error. Please try again.', 'bot', language, 'error');
} finally {
showLoading(false);
// Scroll to bottom
scrollToBottom();
}
}
// Add message to chat UI
function addMessage(text, sender, lang, type = '') {
const messageDiv = document.createElement('div');
messageDiv.className = `message ${sender}-message`;
const now = new Date();
const timeString = now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
// Format message content (preserve HTML links)
let formattedText = text;
if (sender === 'bot') {
// Add type indicator
const typeBadge = type ? getTypeBadge(type) : '';
formattedText = `${typeBadge}${text}`;
}
messageDiv.innerHTML = `
<div class="message-content">
<strong>${sender === 'user' ? 'You' : 'SASTRA Bot'}:</strong> ${formattedText}
</div>
<div class="message-time text-muted">
${timeString}${getLanguageName(lang)}
</div>
`;
chatMessages.appendChild(messageDiv);
scrollToBottom();
// Save to local storage
saveChatToLocal();
}
// Get type badge for message
function getTypeBadge(type) {
const badges = {
'keyword': '<span class="badge bg-warning me-2">Keyword</span>',
'rag': '<span class="badge bg-info me-2">RAG</span>',
'llm': '<span class="badge bg-primary me-2">LLM</span>',
'error': '<span class="badge bg-danger me-2">Error</span>'
};
return badges[type] || '';
}
// Get language name from code
function getLanguageName(code) {
const languages = {
'en': 'English',
'ta': 'Tamil',
'te': 'Telugu',
'kn': 'Kannada',
'hi': 'Hindi'
};
return languages[code] || code;
}
// Show/hide loading spinner
function showLoading(show) {
if (show) {
// Create loading message
const loadingDiv = document.createElement('div');
loadingDiv.className = 'message bot-message';
loadingDiv.id = 'loadingMessage';
loadingDiv.innerHTML = `
<div class="message-content">
<strong>SASTRA Bot:</strong>
<div class="spinner-border spinner-border-sm text-primary ms-2" role="status">
<span class="visually-hidden">Thinking...</span>
</div>
Thinking...
</div>
`;
chatMessages.appendChild(loadingDiv);
scrollToBottom();
} else {
const loadingMessage = document.getElementById('loadingMessage');
if (loadingMessage) {
loadingMessage.remove();
}
}
}
// Scroll chat to bottom
function scrollToBottom() {
chatMessages.scrollTop = chatMessages.scrollHeight;
}
// Clear chat history
function clearChat() {
if (confirm('Are you sure you want to clear the chat history?')) {
chatMessages.innerHTML = `
<div class="message bot-message">
<div class="message-content">
<strong>SASTRA Bot:</strong> Chat cleared! How can I help you today?
</div>
<div class="message-time text-muted">
Just now
</div>
</div>
`;
localStorage.removeItem('chatHistory');
}
}
// Quick question button handler
function quickQuestion(button) {
const question = button.textContent.trim();
userInput.value = question;
sendMessage();
}
// Load chat history from local storage
function loadChatHistory() {
try {
const saved = localStorage.getItem('chatHistory');
if (saved) {
const history = JSON.parse(saved);
// Keep only last 20 messages
const recentHistory = history.slice(-20);
recentHistory.forEach(msg => {
const messageDiv = document.createElement('div');
messageDiv.className = `message ${msg.sender}-message`;
messageDiv.innerHTML = `
<div class="message-content">
<strong>${msg.sender === 'user' ? 'You' : 'SASTRA Bot'}:</strong> ${msg.text}
</div>
<div class="message-time text-muted">
${msg.time}${getLanguageName(msg.lang)}
</div>
`;
chatMessages.appendChild(messageDiv);
});
scrollToBottom();
}
} catch (error) {
console.error('Error loading chat history:', error);
}
}
// Save chat to local storage
function saveChatToLocal() {
try {
const messages = chatMessages.querySelectorAll('.message');
const history = [];
messages.forEach(msg => {
const sender = msg.classList.contains('user-message') ? 'user' : 'bot';
const content = msg.querySelector('.message-content');
const time = msg.querySelector('.message-time').textContent.split('•')[0].trim();
const lang = msg.querySelector('.message-time').textContent.split('•')[1].trim();
// Extract text from content (remove HTML tags for storage)
const text = content.textContent.replace(/SASTRA Bot:|You:/, '').trim();
history.push({
sender: sender,
text: text,
time: time,
lang: getLanguageCode(lang)
});
});
localStorage.setItem('chatHistory', JSON.stringify(history));
} catch (error) {
console.error('Error saving chat history:', error);
}
}
// Get language code from name
function getLanguageCode(name) {
const languages = {
'English': 'en',
'Tamil': 'ta',
'Telugu': 'te',
'Kannada': 'kn',
'Hindi': 'hi'
};
return languages[name] || 'en';
}
// Auto-resize textarea (if using textarea instead of input)
function autoResizeTextarea(textarea) {
textarea.style.height = 'auto';
textarea.style.height = Math.min(textarea.scrollHeight, 100) + 'px';
}
// Add sample questions
const sampleQuestions = [
"What are the admission requirements for B.Tech?",
"How to apply for scholarships?",
"Tell me about hostel facilities",
"What is the placement percentage?",
"List of courses offered",
"Contact information for admissions office"
];
// Utility function to format links in text
function formatLinks(text) {
const urlRegex = /(https?:\/\/[^\s]+)/g;
return text.replace(urlRegex, url => `<a href="${url}" target="_blank" class="chat-link">${url}</a>`);
}
// Utility function to escape HTML
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
// Initialize chat interface on page load
window.onload = function() {
// Set focus to input
userInput.focus();
// Add some sample questions if chat is empty
if (chatMessages.children.length <= 1) {
// Welcome message already exists
console.log('Chat initialized');
}
};