From dabce4a95416daa8658903e844a2fd44caddf1e9 Mon Sep 17 00:00:00 2001 From: Russell Ballestrini Date: Thu, 4 Apr 2024 10:01:32 -0400 Subject: [PATCH] allow user to prevent autoscrolling streamed chunks. modified: templates/chat.html --- templates/chat.html | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/templates/chat.html b/templates/chat.html index ad7d269..f837e0f 100644 --- a/templates/chat.html +++ b/templates/chat.html @@ -192,7 +192,6 @@ // Connect to the server using socket.io with dynamic scheme (http or https) const socket = io.connect(window.location.protocol + "//" + document.domain + ":" + location.port); - // Retrieve username and room name from the URL parameters const urlParams = new URLSearchParams(window.location.search); const username = urlParams.get("username"); @@ -208,6 +207,18 @@ const dompurify_config = { ] }; +// keeping track of scrolling to prevent autoscrolling. +let userHasScrolledUp = false; + +document.addEventListener('DOMContentLoaded', (event) => { + const chatContainer = document.getElementById("chat"); + + chatContainer.addEventListener('scroll', () => { + const distanceFromBottom = chatContainer.scrollHeight - chatContainer.scrollTop - chatContainer.clientHeight; + userHasScrolledUp = distanceFromBottom > 5; + }); +}); + // Function to handle sending the message function sendMessage() { const message = document.getElementById("message").value; @@ -308,7 +319,7 @@ socket.on("message", (data) => { addLineNumbers(block); }); - // Scroll to the bottom of the chat container + // Scroll to the bottom of the chat container to show the new message. if (data.id) { document.getElementById("chat").scrollTop = document.getElementById("chat").scrollHeight; } @@ -441,8 +452,10 @@ socket.on("message_chunk", (data) => { addLineNumbers(block); }); - // Scroll to the bottom of the chat container - document.getElementById("chat").scrollTop = document.getElementById("chat").scrollHeight; + // Scroll to the bottom of the chat container, but skip it if the user has scrolled up. + if (!userHasScrolledUp) { + document.getElementById("chat").scrollTop = document.getElementById("chat").scrollHeight; + } });