var chatbox = document.getElementById('chatbox');
var botchat = document.getElementById('botchat');
var chatheader = document.getElementById('chatheader');
var isDragging = false;
var offsetX, offsetY;
chatheader.addEventListener('mousedown', onMouseDown);
function aichat_init() {
// Initially connect
connectWebSocket();
document.getElementById('botchat').classList.add('hide');
document.getElementById('chatbox').classList.remove('hide')
}
function onMouseDown(e) {
isDragging = true;
offsetX = e.clientX - chatbox.offsetLeft;
offsetY = e.clientY - chatbox.offsetTop;
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
}
function onMouseMove(e) {
if (isDragging) {
chatbox.style.left = (e.clientX - offsetX) + 'px';
chatbox.style.top = (e.clientY - offsetY) + 'px';
}
}
function onMouseUp() {
isDragging = false;
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
}
function chatTyping() {
// Create the typing animation element
var typingDiv = document.createElement('div');
typingDiv.id = 'typingDiv';
typingDiv.className = 'message-cont agent'; // Updated class name
typingDiv.innerHTML = 'Agent is typing';
// Append the typing animation element to the messages div
var messages = document.getElementById('messages');
messages.appendChild(typingDiv);
// Scroll the last message into view
typingDiv.scrollIntoView();
}
function sendMessage() {
var userInput = document.getElementById('userInput').value;
if(userInput.length <= 0) return;
const event = {
role: "You",
content: userInput
}
addMessage('You', JSON.stringify(event));
ws.send(userInput);
chatTyping();
}
function addMessage(agent, data) {
const jsonData = JSON.parse(data);
const { choices } = jsonData;
let str = jsonData.content;
const messages = document.getElementById('messages');
const typingDiv = document.getElementById('typingDiv');
// Remove the typing animation element
if (typingDiv) {
messages.removeChild(typingDiv);
}
// Replace all occurrences of \n with
str = str.replace(/\n/g, '
');
// Convert Markdown-style links [text](URL) into clickable HTML links
str = str.replace(/\[([^\]]+)\]\((https?:\/\/[^\s]+)\)/g, '$1');
// Convert bare URLs into clickable links (excluding trailing punctuation)
//str = str.replace(/(https?:\/\/[^\s.,!?]+)/g, '$1');
// Create a new div element for each message
const messageDiv = document.createElement('div');
messageDiv.innerHTML = '' + str + '';
// Add class based on agent
messageDiv.classList.add(agent.toLowerCase());
messageDiv.classList.add('message-cont');
messages.appendChild(messageDiv);
document.getElementById('userInput').value = '';
// Append multiple-choice options if they exist
if (choices && choices.length > 0) {
const choicesDiv = document.createElement('div');
choicesDiv.classList.add('multiple-choice');
choices.forEach((choice) => {
const choiceLabel = document.createElement('div');
choiceLabel.classList.add('choice');
choiceLabel.textContent = choice;
choiceLabel.addEventListener('click', () => choiceClick(choice));
choicesDiv.appendChild(choiceLabel);
});
messages.appendChild(choicesDiv);
}
// Scroll the last message into view
messageDiv.scrollIntoView();
}
function choiceClick(eventInput) {
// Remove all multiple-choice elements
const messages = document.getElementById('messages');
const multipleChoiceElements = messages.getElementsByClassName('multiple-choice');
while (multipleChoiceElements.length > 0) {
multipleChoiceElements[0].remove();
}
const event = {
role: "You",
content: eventInput
}
addMessage('You', JSON.stringify(event));
ws.send(eventInput);
chatTyping();
}
document.getElementById('userInput').addEventListener('keypress', function(e) {
var key = e.which || e.keyCode;
if (key === 13) { // 13 is the key code for Enter
e.preventDefault(); // Prevent any default behavior for the Enter key (like submitting a form)
sendMessage();
}
});
let ws;
function connectWebSocket() {
if(ws) return;
const wsURL = `wss://${window.location.hostname}/ws-aichat`;
ws = new WebSocket(wsURL);
ws.onopen = function() {
console.log('Connected to WebSocket!');
};
ws.onmessage = function(event) {
addMessage("Agent", event.data);
};
ws.onerror = function(error) {
console.log(`Error occurred: ${error.message}`);
};
ws.onclose = function(event) {
const logMsg = event.wasClean
? `Closed cleanly, code=${event.code}, reason=${event.reason}`
: 'Connection died';
console.log(logMsg);
// Reconnect after a delay
setTimeout(connectWebSocket, 5000); // tries to reconnect every 5 seconds
};
}