summaryrefslogtreecommitdiff
path: root/static/js/components/chat.js
blob: ad876adaa39c8411789f77f3d42814443c856486 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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;
  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);