website/web/static/js/likes.js
Noah 8419958b25 Likes on Comments, and other minor improvements
* Add "Like" buttons to comments and forum posts.
* Make "private" profiles more private (logged-in users see only their profile
  pic, display name, and can friend request or message, if they are not approved
  friends of the private user)
* Add "logged-out view" visibility setting to profiles: to share a link to your
  page on other sites. Opt-in setting - default is login required to view your
  public profile page.
* CSRF cookie fix.
* Updated FAQ & Privacy pages.
2022-08-29 20:00:15 -07:00

58 lines
1.9 KiB
JavaScript

// Like button handler.
document.addEventListener('DOMContentLoaded', () => {
const red = "has-text-danger";
let busy = false;
// Bind to the like buttons.
(document.querySelectorAll(".nonshy-like-button") || []).forEach(node => {
node.addEventListener("click", (e) => {
e.preventDefault();
if (busy) return;
let $icon = node.querySelector(".icon"),
$label = node.querySelector(".nonshy-likes"),
tableName = node.dataset.tableName,
tableID = node.dataset.tableId,
liking = false;
// Toggle the color of the heart.
if ($icon.classList.contains(red)) {
$icon.classList.remove(red);
} else {
liking = true;
$icon.classList.add(red);
}
// Ajax request to backend.
busy = true;
return fetch("/v1/likes", {
method: "POST",
mode: "same-origin",
cache: "no-cache",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
"name": tableName, // TODO
"id": parseInt(tableID),
"unlike": !liking,
"page": window.location.pathname + window.location.search + window.location.hash,
}),
})
.then((response) => response.json())
.then((data) => {
let likes = data.data.likes;
if (likes === 0) {
$label.innerHTML = "Like";
} else {
$label.innerHTML = `Like (${likes})`;
}
}).catch(resp => {
window.alert(resp);
}).finally(() => {
busy = false;
})
});
});
});