2022-08-25 04:17:34 +00:00
|
|
|
// 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) => {
|
2022-08-30 03:00:15 +00:00
|
|
|
e.preventDefault();
|
2022-08-25 04:17:34 +00:00
|
|
|
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
|
2023-10-24 04:55:55 +00:00
|
|
|
"id": ""+tableID,
|
2022-08-25 04:17:34 +00:00
|
|
|
"unlike": !liking,
|
2022-08-30 03:00:15 +00:00
|
|
|
"page": window.location.pathname + window.location.search + window.location.hash,
|
2022-08-25 04:17:34 +00:00
|
|
|
}),
|
|
|
|
})
|
|
|
|
.then((response) => response.json())
|
|
|
|
.then((data) => {
|
2023-07-19 05:30:29 +00:00
|
|
|
if (data.StatusCode !== 200) {
|
|
|
|
window.alert(data.data.error);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2022-08-25 04:17:34 +00:00
|
|
|
let likes = data.data.likes;
|
|
|
|
if (likes === 0) {
|
|
|
|
$label.innerHTML = "Like";
|
|
|
|
} else {
|
|
|
|
$label.innerHTML = `Like (${likes})`;
|
|
|
|
}
|
|
|
|
}).catch(resp => {
|
|
|
|
window.alert(resp);
|
|
|
|
}).finally(() => {
|
|
|
|
busy = false;
|
|
|
|
})
|
|
|
|
});
|
|
|
|
});
|
2023-07-19 05:30:29 +00:00
|
|
|
});
|