chat.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. let chatLog = [];
  2. function attachChat(room) {
  3. let chatButton = document.getElementById("chat-submit");
  4. chatButton.addEventListener("click", event => {
  5. let chatInput = document.getElementById("chat-input");
  6. if(chatInput.value.length > 3) {
  7. sendMessage(chatInput.value);
  8. chatInput.value = "";
  9. }
  10. chatInput.focus();
  11. });
  12. let chatInput = document.getElementById("chat-input");
  13. chatInput.addEventListener("keyup", event => {
  14. if(event.keyCode == 13) { //enter
  15. chatButton.click();
  16. }
  17. });
  18. updateChatLogDisplay();
  19. }
  20. function updateChatLogDisplay() {
  21. let chatLogDisplay = document.getElementById("chat-log");
  22. if(chatLogDisplay) {
  23. chatLogDisplay.innerHTML = formatChat(chatLog);
  24. }
  25. }
  26. function formatChat(log) {
  27. let output = [];
  28. for(let i = 0; i < chatLog.length; i++) {
  29. let message = chatLog[i];
  30. output.push(`${message.user}: ${message.message}`)
  31. }
  32. return output.join("\n");
  33. }
  34. function sendMessage(message) {
  35. broadcast(userData, message);
  36. }
  37. function receiveMessage(source, message) {
  38. if(source != userData) {
  39. toastMessage(`${source.name}: ${message}`, source.style);
  40. }
  41. chatLog.push({user: source.name, userId: source.id, message: message});
  42. updateChatLogDisplay();
  43. }
  44. function broadcast(source, message) {
  45. receiveMessage(source, message);
  46. }