///
type Message = { id: number; author: string; body: string; created_at: string };
const list = document.querySelector("#messages")!;
const form = document.querySelector("#sign")!;
const status = document.querySelector("#status")!;
const seen = new Set();
function show(m: Message, atTop: boolean) {
if (seen.has(m.id)) return;
seen.add(m.id);
const li = document.createElement("li");
li.innerHTML = ": ";
li.querySelector("b")!.textContent = m.author;
li.querySelector("span")!.textContent = m.body;
atTop ? list.prepend(li) : list.append(li);
}
async function load() {
const messages: Message[] = await (await fetch("/api/messages")).json();
for (const m of messages) show(m, false);
}
// New messages from anyone arrive over the WebSocket, through exe.dev's proxy.
function connect() {
const ws = new WebSocket(new URL("/ws", location.href.replace(/^http/, "ws")));
ws.onopen = () => (status.textContent = "Live: new messages appear without a reload.");
ws.onmessage = (e) => show(JSON.parse(e.data), true);
ws.onclose = () => {
status.textContent = "Reconnecting…";
setTimeout(connect, 1000);
};
}
form.addEventListener("submit", async (e) => {
e.preventDefault();
const input = form.elements.namedItem("body") as HTMLInputElement;
const res = await fetch("/api/messages", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ body: input.value }),
});
if (res.ok) show(await res.json(), true);
input.value = "";
});
load().then(connect);