From a306363f9d102a162d582f0f19920f6b6578a0f6 Mon Sep 17 00:00:00 2001 From: Mitja Felicijan Date: Sun, 30 Jan 2022 21:39:50 +0100 Subject: Added comments made with Nginx NJS --- template/script.js | 78 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 77 insertions(+), 1 deletion(-) (limited to 'template/script.js') diff --git a/template/script.js b/template/script.js index 4c508ed..0e1291c 100755 --- a/template/script.js +++ b/template/script.js @@ -1,4 +1,4 @@ -window.addEventListener('load', () => { +window.addEventListener('load', async () => { // dither image on mouse over replace // document.querySelectorAll('article img').forEach(img => { // const ditheredImage = img.src; @@ -24,4 +24,80 @@ window.addEventListener('load', () => { evt.target.style.transform = 'scaleX(1)'; }); } + + // comments code + const commentsEndpoint = 'https://mitjafelicijan.com/comments-api'; + const commentsPlaceholder = document.querySelector('.comments'); + + if (commentsPlaceholder) { + const guid = commentsPlaceholder.dataset.guid; + const name = commentsPlaceholder.querySelector('input'); + const comment = commentsPlaceholder.querySelector('textarea'); + const submit = commentsPlaceholder.querySelector('button'); + const comments = commentsPlaceholder.querySelector('ul'); + + if (guid) { + await readAndRenderComments(guid, comments); + + submit.addEventListener('click', async() => { + submit.disabled = true; + await writeComments(guid, name.value, comment.value); + + submit.disabled = false; + name.value = ''; + comment.value = ''; + + await readAndRenderComments(guid, comments); + }); + } + } + + async function writeComments(guid, name, comment) { + const response = await fetch(commentsEndpoint, { + method: 'POST', + headers: { + 'Accept': 'application/json', + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + action: 'write', + guid, + name, + comment, + }) + }); + } + + async function readAndRenderComments(guid, commentsPlaceholder) { + const response = await fetch(commentsEndpoint, { + method: 'POST', + headers: { + 'Accept': 'application/json', + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + action: 'read', + guid, + }) + }); + + // remove all existing comments from list + commentsPlaceholder.innerHTML = ''; + + const commentList = await response.json(); + for (const comment of commentList.reverse()) { + const date = new Date(comment.date).toLocaleDateString('en-US', { + year: 'numeric', + month: 'long', + day: 'numeric', + hour: 'numeric', + minute: 'numeric' + }); + + const commentElement = document.createElement('li'); + commentElement.innerHTML = `

${comment.name} - ${date}

${comment.comment}


`; + commentsPlaceholder.appendChild(commentElement); + } + } + }); -- cgit v1.2.3