summaryrefslogtreecommitdiff
path: root/static/js/components/chat.js
blob: e5d11859c4045a28652c076e63365a88f9700bd2 (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
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, scrollTopMax } = document.getElementById(
    "chat-container",
  ) ?? { scrollTop: 0 };
  const isAtEdge = scrollTop > (0.92 * scrollTopMax) || scrollTop === 0;
  document.getElementById("messages").innerHTML = html;
  if (isAtEdge) {
    document.getElementById("chat-container").scrollTop =
      document.getElementById("chat-container").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);