function commentForm(parentId) { return `
`; } function commentDisplay(comment, replies) { return `
${typeof replies === "string" ? `` : ""}${comment.author ? comment.author : "Anonymous"} commented ${moment(new Date(comment.timestamp * 1000)).fromNow()}:
${md.render(comment.text)}
${typeof replies === "string" ? `
${replies ? replies : ""}
` : ""}
`; } const container = document.getElementById("soudan"); container.style.display = "none"; container.innerHTML = `

Make a comment

${commentForm()}

Comments

`; const md = window.markdownit().disable("image"); const form = document.getElementById("soudan-comment-form"); const commentContainer = document.getElementById("soudan-comments"); const commentContainerHeader = document.getElementById("soudan-comments-header"); const contentId = document.querySelector("meta[name=\"soudan-content-id\"]").getAttribute("content"); function submitForm(form, e) { let data = { url: window.location.href, comment: { contentId } }; new FormData(form).forEach((value, key) => { data.comment[key] = value === "" ? null : value; }); if (data.comment.parent) { data.comment.parent = parseInt(data.comment.parent); } fetch(url, { method: "POST", body: JSON.stringify(data), headers: { "Content-Type": "application/json" } }) .then(response => { if (!response.ok) { Promsise.reject(); } form.querySelector("textarea").value = ""; reloadComments(); }) .catch(error => alert("Something went wrong posting your comment!")) e.preventDefault(); } function reloadComments(jump) { fetch(`${url}/${contentId}`) .then(response => { return response.json().then(json => { return response.ok ? json : Promise.reject(json); }); }) .then(comments => { let commentCount = comments.length; comments.forEach(comment => { if (comment.replies) { commentCount += comment.replies.length; } }); commentContainerHeader.innerHTML = `${commentCount} Comment${commentCount == 1 ? "" : "s"}`; let html = ""; if (comments.length == 0) { html = "

No comments yet! Be the first to make one.

"; } else { comments.forEach(comment => { if (comment.replies) { let replies = ""; comment.replies.forEach(reply => { replies += commentDisplay(reply); }); html += commentDisplay(comment, replies); } else { html += commentDisplay(comment, ""); } }); } commentContainer.innerHTML = html; soudan.style.display = ""; if (jump && window.location.hash) { const target = document.getElementById(window.location.hash.substring(1)); if (target) { window.scrollTo(0, target.offsetTop); target.classList.add("soudan-highlighted"); } } }) } function reply(id) { const replies = document.getElementById(id).querySelector(".soudan-replies"); replies.innerHTML = `

Reply

${commentForm(id)}${replies.innerHTML}`; } reloadComments(true);