mypastebin/static/js/favorites.js
2025-06-07 01:06:19 +02:00

81 lines
3.0 KiB
JavaScript

document.addEventListener("DOMContentLoaded", function () {
const favoriteButton = document.getElementById("favorite-button");
if (favoriteButton) {
favoriteButton.classList.add("text-light");
favoriteButton.addEventListener("click", function () {
const pasteId = document.body.dataset.pasteId;
if (!pasteId) {
console.error("Error: pasteId no definido en el <body>.");
return;
}
const isFavorited = favoriteButton.classList.contains("text-danger");
const action = isFavorited ? "unfavorite" : "favorite";
fetch(`/paste/${pasteId}/${action}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include"
})
.then(response => response.json())
.then(data => {
if (data.message.includes("Added")) {
favoriteButton.classList.add("text-danger");
favoriteButton.classList.remove("text-secondary");
favoriteButton.setAttribute("title", "Remove from Favorites");
} else {
favoriteButton.classList.add("text-secondary");
favoriteButton.classList.remove("text-danger");
favoriteButton.setAttribute("title", "Add to Favorites");
}
showToast(data.message, "bg-success");
})
.catch(error => {
console.error("Error updating favorites:", error);
showToast("Error updating favorites.", "bg-danger");
});
});
}
document.querySelectorAll(".unfavorite-btn").forEach(button => {
button.addEventListener("click", function () {
const pasteId = this.dataset.id;
fetch(`/paste/${pasteId}/unfavorite`, {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include"
})
.then(response => response.json())
.then(data => {
if (data.success) {
const row = this.closest("tr");
if (row) row.remove();
// Si ya no hay filas, mostrar mensaje vacío
const tableBody = document.querySelector("#favorites-body");
if (tableBody && tableBody.rows.length === 0) {
tableBody.innerHTML = `
<tr>
<td colspan="6" class="text-center text-muted">
No favorites yet.
</td>
</tr>
`;
}
showToast(data.message, "bg-success");
} else {
showToast(data.error || "No se pudo eliminar el favorito.", "bg-danger");
}
})
.catch(error => {
console.error("Error:", error);
showToast("Error al eliminar favorito.", "bg-danger");
});
});
});
});