phantasmobile/app/static/js/comments.js
2023-07-16 11:26:14 +05:30

80 lines
2.8 KiB
JavaScript

function renderComments(cdiv, data) {
cdiv.innerHTML = `
<h3>
<span class="icon">${icon.down}</span>
Comments
</h3>
<div class="block">
<div class="comments-content">
</div>
</div>
`
const content = cdiv.querySelector('.comments-content')
comments.forEach(comment => {
var c = document.createElement('div')
c.className = 'comment'
c.innerHTML = `
<div class="text">${comment.text}</div>
<div class="meta">
by <span class="name">${comment.name}</span>
on
<span class="date">${comment.date}</span>
</div>
`
content.append(c)
})
var add = document.querySelector('.add-comment')
add.style.display = 'block'
cdiv.querySelector('.block').append(add)
cdiv.querySelector('h3').addEventListener("click", event => {
var img = cdiv.querySelector('h3 .icon')
if (cdiv.classList.contains("collapsed")) {
cdiv.classList.remove("collapsed")
img.innerHTML = icon.down
} else {
cdiv.classList.add("collapsed")
img.innerHTML = icon.right
}
})
}
document.querySelector('button#add-comment').addEventListener('click', event => {
var data = {}, csrf;
document.querySelector('.add-comment').querySelectorAll('input,textarea').forEach(input => {
if (input.name == 'csrfmiddlewaretoken') {
csrf = input.value.trim()
} else {
data[input.name] = input.value.trim()
if (!data[input.name]) {
delete data[input.name]
}
}
})
data.item = pandora.comment
fetch("/comment/", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrf
},
body: JSON.stringify(data)
}).then(response => {
return response.json()
}).then(response => {
var comment = document.createElement('div')
comment.classList.add('comment')
comment.innerHTML = `
<div class="text"></div>
<div class="meta">
by <span class="name"></span>
on
<span class="date"></span>
</div>
`
comment.querySelector('.name').innerText = response.name
comment.querySelector('.date').innerText = response.date
comment.querySelector('.text').innerText = response.text
document.querySelector('.comments .comments-content').append(comment)
document.querySelector('.add-comment textarea').value = ''
})
})