48 lines
1.6 KiB
JavaScript
Raw Normal View History

2025-01-03 01:47:07 -08:00
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(),
);
2025-01-13 23:03:44 -08:00
const { scrollTop, scrollHeight, clientTop } = document.getElementById(
2025-01-03 01:47:07 -08:00
"chat-container",
2025-01-13 23:03:44 -08:00
) ?? { scrollTop: 0, scrollHeight: 0, clientTop: 0};
2025-01-16 17:19:01 -08:00
const scrollTopMax = scrollHeight - clientTop;
2025-01-05 15:16:26 -08:00
const isAtEdge = scrollTop > (0.92 * scrollTopMax) || scrollTop === 0;
2025-01-03 01:47:07 -08:00
document.getElementById("messages").innerHTML = html;
2025-01-16 17:25:09 -08:00
await new Promise((res) => setTimeout(res, 200)); // wait for html to emplace.
2025-01-13 23:03:44 -08:00
const emplacedScrollTopMax = document.getElementById("chat-container").scrollHeight - document.getElementById("chat-container").clientTop;
2025-01-03 01:47:07 -08:00
if (isAtEdge) {
2025-01-13 23:03:44 -08:00
document.getElementById("chat-container").scrollTop = scrollTopMax;
2025-01-03 01:47:07 -08:00
} else {
// save the position.
document.getElementById("chat-container").scrollTop = scrollTop;
}
};
setTimeout(() => {
2025-01-03 02:12:41 -08:00
if (document.location.pathname.startsWith("/chat")) {
runChat().then(() => setInterval(runChat, 2_500));
2025-01-03 01:47:07 -08:00
}
}, 200);
2025-01-16 17:32:54 -08:00
const form = document.getElementById("chat-form");
form.addEventListener('submit', (event) => {
event.preventDefault();
const message = document.getElementById("message-content").value;
const fren_id = document.getElementById("fren-id").value;
const params = new URLSearchParams();
params.append("fren_id", fren_id);
params.append("message", message);
fetch("/chat", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: params,
}).then(runChat);
});