From 55d4b75ee6af971d79fcdabdec7969f224f09dca Mon Sep 17 00:00:00 2001 From: dan Date: Sun, 14 May 2023 21:53:17 -0400 Subject: init --- client.js | 84 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 client.js (limited to 'client.js') diff --git a/client.js b/client.js new file mode 100644 index 0000000..c2d041c --- /dev/null +++ b/client.js @@ -0,0 +1,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 => + ``; + +const commentFmt = x => + `
${x.content}
${x.created_at}`+ + `${x.deletion_key ? deleteButton(x) :''}
`; + +function commentsRender() { + commentsthread.innerHTML = + `
+ ${comments.map(commentFmt).join('')} +
`; +} + + +/* 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(); -- cgit v1.2.3