shadowfacts.net/site/js/comments.js

67 lines
1.8 KiB
JavaScript
Raw Normal View History

2019-03-01 23:42:28 +00:00
fetchComments();
async function fetchComments() {
const res = await fetch(`/comments?id=${permalink}`);
const comments = await res.json();
2019-08-18 21:15:31 +00:00
const rootId = new URL(permalink, document.location);
2019-03-01 23:42:28 +00:00
const tree = buildCommentsTree(comments, rootId)[0];
const html = renderCommentList(tree);
2019-08-18 21:15:31 +00:00
document.getElementById("comments-container").innerHTML += html;
2019-03-01 23:42:28 +00:00
}
function buildCommentsTree(comments, parent) {
console.log(`Building tree for ${parent}`);
2019-08-18 21:15:31 +00:00
let [children, rem] = partition(comments, it => {
const inReplyTo = new URL(it.inReplyTo);
return inReplyTo.hostname === parent.hostname && inReplyTo.pathname === parent.pathname;
});
2019-03-01 23:42:28 +00:00
for (const child of children) {
2019-08-18 21:15:31 +00:00
const [subChildren, subRem] = buildCommentsTree(rem, new URL(child.id));
2019-03-01 23:42:28 +00:00
rem = subRem;
child.children = subChildren;
}
return [children, rem]
}
function partition(array, fn) {
const trueArr = [];
const falseArr = [];
for (const el of array) {
(fn(el) ? trueArr : falseArr).push(el);
}
return [trueArr, falseArr];
}
function renderCommentList(comments) {
const rendered = comments.map(renderComment).join("\n");
return `<ul class="comments-list">` + rendered + `</ul>`;
}
function renderComment(comment) {
const formattedDate = new Date(comment.published).toLocaleString("en-us", {
month: "short",
day: "numeric",
year: "numeric",
hour: "numeric",
minute: "numeric"
});
return `
<div class="comment">
<img class="comment-user-avatar" src="${comment.author.icon}">
<div class="comment-main">
<p class="comment-info">
<a class="comment-user-name" href="${comment.author.id}">${comment.author.name}</a>
on
<a class="comment-date" href="${comment.id}">${formattedDate}</a>
</p>
<div class="comment-body">
${comment.content}
</div>
<div class="comment-children">
${renderCommentList(comment.children)}
</div>
</div>
</div>
`;
2019-08-18 21:15:31 +00:00
}