const runChat = async () => { const frenId = new URLSearchParams(document.location.search).get("fren_id") ?? document.getElementById("fren_id").value; const html = await fetch(`/chat/messages?fren_id=${frenId}`).then((r) => r.text(), ); const { scrollTop, scrollHeight, clientTop } = document.getElementById( "chat-container", ) ?? { scrollTop: 0, scrollHeight: 0, clientTop: 0}; const scrollTopMax = scrollHeight - clientTop; const isAtEdge = scrollTop > (0.92 * scrollTopMax) || scrollTop === 0; document.getElementById("messages").innerHTML = html; await new Promise((res) => setTimeout(res, 200)); // wait for html to emplace. if (!document.getElementById("chat-container")) return; const emplacedScrollTopMax = document.getElementById("chat-container").scrollHeight - document.getElementById("chat-container").clientTop; if (isAtEdge) { document.getElementById("chat-container").scrollTop = scrollTopMax; } else { // save the position. document.getElementById("chat-container").scrollTop = scrollTop; } }; setTimeout(() => { if (document.location.pathname.startsWith("/chat")) { runChat().then(() => setInterval(runChat, 2_500)); } }, 200);