import request from "./request.js"; const messages = document.getElementById("messages"); function renderMessage(message) { const messageElement = document.createElement("div"); messageElement.classList.add("message"); messageElement.setAttribute("id", "message-" + message.id); messageElement.innerHTML = `

${new Date(message.time).toLocaleString()}

${message.author.name} ${message.author.name}:

${message.content}


${!message.deleted ? `
` : "

This message has been deleted

"}

${message.reactCount}

`; messages.appendChild(messageElement); messages.innerHTML += "
"; }; /** * Main Renderer */ (async () => { const { result } = await fetch(`/api/threads/${messages.getAttribute("value")}/messages/`).then(res => res.json()); if (result?.error) { document.getElementById("messages").innerHTML += '

THIS THREAD HAS NOT GOT ANY MESSAGE

'; } else for (const message of result) { const arr = Object.values(message.react || {}) message.reactCount = arr.filter(Boolean).length - arr.filter(x => !x).length; renderMessage(message); } window.scrollTo(0, document.body.scrollHeight); })(); /** * Message Sender */ document.getElementById("send").addEventListener("submit", async e => { e.preventDefault(); const form = e.target; const data = new FormData(form); request("/api/messages", "POST", { threadID: data.get("threadID"), content: data.get("content") }) .then(res => { if (!res) return; form.reset(); res.result.reactCount = 0; renderMessage(res.result); }); }); /** * Button Listener */ document.addEventListener("click", async e => { // e.preventDefault(); if (e.target.id === "delete_thread") { const response = await request("/api/threads/" + e.target.value + "/delete"); if (response.result.deleted) { alert("Thread deleted"); window.location.href = "/threads"; } } else if (e.target.id === "delete_message") { e.preventDefault(); const response = await request(`/api/messages/${e.target.value}/delete`); if (response.result.deleted) { alert("Message deleted"); document.getElementById("message-delete-" + e.target.value).innerHTML="

This message has been deleted

"; } } /*else if (e.target.id === "edit_thread") { window.location.href = "/threads/<%= thread.id }/edit"; } */ if (!e.target.id.includes("like")) return; const res = await request("/api/messages/" + e.target.value + "/react/" + e.target.id) document.getElementById("count" + e.target.value).innerHTML = res.result; });