blob: c2d041c22e7fcbc41df598288712969ff6b7257d (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
|
/* Config */
const baseUrl = 'https://comments.dotemgo.com/comments';
const pageId = '{{site-url}}{{uri}}';
const commentsUrl = `${baseUrl}?page_url=${pageId}`;
/* State */
let comments = [];
/* GUI components */
const deleteButton = x =>
`<button style='float:right;' onclick='handleDelete("${x.id}", "${x.deletion_key}")'>`+
`delete</button>`;
const commentFmt = x =>
`<div class='comment' id='comment${x.id}'>${x.content}<br/>${x.created_at}`+
`${x.deletion_key ? deleteButton(x) :''}</div>`;
function commentsRender() {
commentsthread.innerHTML =
`<div id='commentsthreadinner'>
${comments.map(commentFmt).join('')}
</div>`;
}
/* API calls */
// GET comments
function fetchComments() {
fetch(commentsUrl)
.then(r => r.ok && r.json())
.then(xs => {
comments = xs;
if (comments.length) {
commentsRender();
}
})
}
// POST new comment
function createComment(comment) {
const xs = new BigUint64Array(1);
crypto.getRandomValues(xs);
comment.deletion_key = xs[0].toString();
fetch(baseUrl, {
method: 'POST',
body: JSON.stringify(comment),
headers: {'content-type': 'application/json'}
}).then(r => r.ok && r.text())
.then(id => {
const newComment = {id, created_at: 'just now', ...comment}
comments = [newComment, ...comments];
commentsRender();
})
}
/* Action Handlers */
function handleCommentFormSubmit() {
if (commentcontent.value !== "") {
createComment({page_url: pageId, content: commentcontent.value});
commentcontent.value = '';
}
}
// DELETE comment
function handleDelete(commentId, deletionKey) {
console.log('deleting:',{commentId,deletionKey});
fetch(
`${baseUrl}?comment=${commentId}&deletion_key=${deletionKey}`,
{method: 'DELETE'}
).then(r => {
if (r.ok) {
comments = comments.filter(x => x.id !== commentId);
commentsRender();
}
});
}
/* init */
fetchComments();
|