From d8dc54f8021c36ca0b0992ef69d83dc2cec7df8d Mon Sep 17 00:00:00 2001 From: Lynne Date: Mon, 20 Jan 2020 14:06:39 +1000 Subject: [PATCH] only keep 50 most recent messages, disable input box while waiting for a reply --- app/static/script.js | 30 +++++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/app/static/script.js b/app/static/script.js index 4779116..05414af 100644 --- a/app/static/script.js +++ b/app/static/script.js @@ -1,10 +1,12 @@ +var chatlog = []; + function sendMessage() { let id = window.location.href.split("/").slice(-1)[0] message = document.getElementById("chatbox-input-box").value document.getElementById("chatbox-input-box").value = '' - let chatbox = document.getElementById("chatbox"); - chatbox.innerHTML += `
${message}
`; - chatbox.scrollTop = chatbox.scrollHeight; + document.getElementById("chatbox-input-box").disabled = true; + chatlog.push(["user", message]) + renderChatlog(); var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4) { @@ -13,8 +15,10 @@ function sendMessage() { } else { message = "Encountered an error while trying to get a response."; } - chatbox.innerHTML += `
${message}
`; - chatbox.scrollTop = chatbox.scrollHeight; + chatlog.push(["bot", message]); + renderChatlog(); + document.getElementById("chatbox-input-box").disabled = false; + } }; xhttp.open("GET", `/bot/chat/${id}/message`, true); @@ -22,3 +26,19 @@ function sendMessage() { return false; } +function renderChatlog() { + let chatbox = document.getElementById("chatbox"); + let out = ""; + if (chatlog.length > 50) { + chatlog.shift(); //only keep the 50 most recent messages to avoid slowdown + } + chatlog.forEach(function(item, i) { + if (item[0] == "user") { + out += `
${item[1]}
`; + } else { + out += `
${item[1]}
`; + } + }) + chatbox.innerHTML = out; + chatbox.scrollTop = chatbox.scrollHeight; +}