2021-07-22 20:09:02 +00:00
|
|
|
// VARIABLES
|
|
|
|
let messageCount = 0;
|
|
|
|
let username = localStorage.getItem('username');
|
|
|
|
const form = document.querySelector('form');
|
|
|
|
|
|
|
|
// SEND A MESSAGE
|
|
|
|
|
|
|
|
// GRABS MESSAGE FROM FORM & SENDS
|
|
|
|
form.addEventListener("submit", async function (event) {
|
|
|
|
event.preventDefault();
|
|
|
|
const formData = new FormData(form);
|
|
|
|
|
2021-07-23 14:30:43 +00:00
|
|
|
formMessage = formData.get('message').toString();
|
2021-07-22 20:09:02 +00:00
|
|
|
|
|
|
|
sendMessage()
|
|
|
|
|
|
|
|
})
|
|
|
|
|
|
|
|
//SEND MESSAGE FETCH FUNCTION
|
|
|
|
|
|
|
|
async function sendMessage() {
|
2021-07-23 19:41:55 +00:00
|
|
|
sendMessageInfo = { "name": username, "body": formMessage }
|
2021-07-22 20:09:02 +00:00
|
|
|
fetch('/api/message/send', {
|
|
|
|
method: 'POST',
|
|
|
|
headers: {
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
},
|
|
|
|
body: JSON.stringify(sendMessageInfo),
|
|
|
|
})
|
|
|
|
form.reset()
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// RECIEVE MESSAGES
|
|
|
|
|
|
|
|
let messageUpdate = window.setInterval(fetchMessages, 500);
|
|
|
|
|
|
|
|
async function fetchMessages() {
|
|
|
|
const response = await fetch('/api/message/messages.json');
|
|
|
|
const recievedMessages = await response.json();
|
|
|
|
document.getElementById("innerchatbox").innerHTML = ""
|
|
|
|
|
|
|
|
for (const message of recievedMessages) {
|
2021-07-24 14:10:41 +00:00
|
|
|
printText(message.user.bold().toString() + ": " + message.body.toString());
|
2021-07-22 20:09:02 +00:00
|
|
|
}
|
|
|
|
|
2021-07-24 14:10:41 +00:00
|
|
|
|
2021-07-22 20:09:02 +00:00
|
|
|
if (recievedMessages.length != messageCount) {
|
|
|
|
let scroll = document.getElementById("innerchatbox");
|
|
|
|
scroll.scrollTop = scroll.scrollHeight;
|
2021-07-24 14:10:41 +00:00
|
|
|
}
|
2021-07-22 20:09:02 +00:00
|
|
|
|
|
|
|
messageCount = recievedMessages.length;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// FUNCTION TO PRINT MESSAGES IN THE CHAT BOX
|
|
|
|
|
|
|
|
function printText(text) {
|
|
|
|
let p = document.createElement("p");
|
|
|
|
const div = document.getElementById("innerchatbox");
|
|
|
|
div.appendChild(p)
|
|
|
|
p.innerHTML = text
|
|
|
|
}
|
2021-07-23 06:51:26 +00:00
|
|
|
|
|
|
|
|
|
|
|
//LOGGED IN STUFF
|
|
|
|
//TODO ADD CHECK TO SEE IF USERNAME AND TOKEN MATCHES
|
2021-07-24 14:10:41 +00:00
|
|
|
function loggedIn() {
|
|
|
|
username = localStorage.getItem('username');
|
|
|
|
if (username === null || username === '') {
|
|
|
|
document.querySelector("#loggeduser").innerHTML = 'You are not logged in'
|
|
|
|
} else {
|
|
|
|
document.querySelector("#loggeduser").innerHTML = `You are logged in as ${username}`
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
loggedIn()
|