-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
66 lines (59 loc) · 2.33 KB
/
script.js
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
const socket = new WebSocket("ws://localhost:8000/ws/chat");
const chatForm = document.getElementById("chatForm");
const userInput = document.getElementById("userInput");
const chatResponse = document.getElementById("chatResponse");
// WebSocket connection established
socket.onopen = function () {
console.log("[open] Connection established");
chatResponse.innerHTML +=
"<p class='system-message'>Connected to the chatbot.</p>";
};
// WebSocket message handling
socket.onmessage = function (event) {
const data = JSON.parse(event.data);
if (data.delta) {
// Sanitize and format the delta response
const formattedResponse = data.delta.replace(/\s+/g, " "); // Normalize whitespace
chatResponse.innerHTML += `<p class="ai-response">${formattedResponse}</p>`;
} else if (data.complete) {
chatResponse.innerHTML += `<br />`; // Add a line break after complete response
}
chatResponse.scrollTop = chatResponse.scrollHeight; // Auto-scroll to bottom
};
// Handling form submission (sending user's message)
chatForm.addEventListener("submit", function (e) {
e.preventDefault();
if (socket.readyState === WebSocket.OPEN) {
const userMessage = userInput.value.trim();
if (userMessage) {
// Sanitize the user message
const sanitizedUserMessage = userMessage
.replace(/</g, "<") // Escape '<'
.replace(/>/g, ">") // Escape '>'
.replace(/&/g, "&"); // Escape '&'
// Append user's message to the chat
chatResponse.innerHTML += `<p class="user-message">You: ${sanitizedUserMessage}</p>`;
socket.send(JSON.stringify({ message: userMessage }));
userInput.value = ""; // Clear input after sending
}
} else {
chatResponse.innerHTML += `<p class="error-message">Connection is not open. Please try again later.</p>`;
}
});
// WebSocket close event
socket.onclose = function (event) {
if (event.wasClean) {
console.log(
`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`
);
} else {
console.log("[close] Connection died");
}
chatResponse.innerHTML +=
"<p class='system-message'>Disconnected from the chatbot.</p>";
};
// WebSocket error event
socket.onerror = function (error) {
console.log(`[error] ${error.message}`);
chatResponse.innerHTML += `<p class="error-message">Error: ${error.message}</p>`;
};