added my lists page

This commit is contained in:
2025-12-06 14:28:40 +01:00
parent 9832384627
commit e5ec8aa7e5
21 changed files with 2400 additions and 44 deletions

View File

@@ -1,16 +1,196 @@
const animeId = window.location.pathname.split('/').pop();
let player;
let totalEpisodes = 0;
let currentPage = 1;
const itemsPerPage = 12;
let extensionName;
let currentAnimeData = null;
let isInList = false;
let currentListEntry = null;
const API_BASE = '/api';
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
let extensionName;
// Auth helpers
function getAuthToken() {
return localStorage.getItem('token');
}
function getAuthHeaders() {
const token = getAuthToken();
return {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
};
}
// Check if anime is in list
async function checkIfInList() {
try {
const response = await fetch(`${API_BASE}/list`, {
headers: getAuthHeaders()
});
if (response.ok) {
const data = await response.json();
const entry = data.results?.find(item =>
item.entry_id === parseInt(animeId) &&
item.source === (extensionName || 'anilist')
);
if (entry) {
isInList = true;
currentListEntry = entry;
updateAddToListButton();
}
}
} catch (error) {
console.error('Error checking list:', error);
}
}
// Update button state
function updateAddToListButton() {
const btn = document.getElementById('add-to-list-btn');
if (isInList) {
btn.innerHTML = `
<svg width="20" height="20" fill="currentColor" viewBox="0 0 24 24">
<path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
</svg>
In Your List
`;
btn.style.background = 'rgba(34, 197, 94, 0.2)';
btn.style.color = '#22c55e';
btn.style.borderColor = 'rgba(34, 197, 94, 0.3)';
} else {
btn.innerHTML = '+ Add to List';
}
}
// Open add to list modal
function openAddToListModal() {
if (isInList) {
// If already in list, open edit modal with current data
document.getElementById('modal-status').value = currentListEntry.status || 'PLANNING';
document.getElementById('modal-progress').value = currentListEntry.progress || 0;
document.getElementById('modal-score').value = currentListEntry.score || '';
document.getElementById('modal-title').textContent = 'Edit List Entry';
document.getElementById('modal-delete-btn').style.display = 'block';
} else {
// New entry defaults
document.getElementById('modal-status').value = 'PLANNING';
document.getElementById('modal-progress').value = 0;
document.getElementById('modal-score').value = '';
document.getElementById('modal-title').textContent = 'Add to List';
document.getElementById('modal-delete-btn').style.display = 'none';
}
document.getElementById('modal-progress').max = totalEpisodes || 999;
document.getElementById('add-list-modal').classList.add('active');}
// Close modal
function closeAddToListModal() {
document.getElementById('add-list-modal').classList.remove('active');
}
// Save to list
async function saveToList() {
const status = document.getElementById('modal-status').value;
const progress = parseInt(document.getElementById('modal-progress').value) || 0;
const score = parseFloat(document.getElementById('modal-score').value) || null;
try {
const response = await fetch(`${API_BASE}/list/entry`, {
method: 'POST',
headers: getAuthHeaders(),
body: JSON.stringify({
entry_id: animeId,
source: extensionName || 'anilist',
entry_type: 'ANIME',
status: status,
progress: progress,
score: score
})
});
if (!response.ok) {
throw new Error('Failed to save entry');
}
// Si la operación fue exitosa, actualizamos currentListEntry con el nuevo campo type
isInList = true;
currentListEntry = {
entry_id: parseInt(animeId),
source: extensionName || 'anilist',
entry_type: 'ANIME', // <--- También se actualiza aquí
status,
progress,
score
};
updateAddToListButton();
closeAddToListModal();
showNotification(isInList ? 'Updated successfully!' : 'Added to your list!', 'success');
} catch (error) {
console.error('Error saving to list:', error);
showNotification('Failed to save. Please try again.', 'error');
}
}
// Delete from list
async function deleteFromList() {
if (!confirm('Remove this anime from your list?')) return;
try {
const response = await fetch(`${API_BASE}/list/entry/${animeId}`, {
method: 'DELETE',
headers: getAuthHeaders()
});
if (!response.ok) {
throw new Error('Failed to delete entry');
}
isInList = false;
currentListEntry = null;
updateAddToListButton();
closeAddToListModal();
showNotification('Removed from your list', 'success');
} catch (error) {
console.error('Error deleting from list:', error);
showNotification('Failed to remove. Please try again.', 'error');
}
}
// Show notification
function showNotification(message, type = 'info') {
const notification = document.createElement('div');
notification.style.cssText = `
position: fixed;
top: 100px;
right: 20px;
background: ${type === 'success' ? '#22c55e' : type === 'error' ? '#ef4444' : '#8b5cf6'};
color: white;
padding: 1rem 1.5rem;
border-radius: 12px;
box-shadow: 0 10px 30px rgba(0,0,0,0.3);
z-index: 9999;
font-weight: 600;
animation: slideInRight 0.3s ease;
`;
notification.textContent = message;
document.body.appendChild(notification);
setTimeout(() => {
notification.style.animation = 'slideOutRight 0.3s ease';
setTimeout(() => notification.remove(), 300);
}, 3000);
}
async function loadAnime() {
try {
@@ -36,6 +216,8 @@ async function loadAnime() {
return;
}
currentAnimeData = data;
const title = data.title?.english || data.title?.romaji || data.title || "Unknown Title";
document.title = `${title} | WaifuBoard`;
document.getElementById('title').innerText = title;
@@ -44,7 +226,6 @@ async function loadAnime() {
if (extensionName) {
posterUrl = data.image || '';
} else {
posterUrl = data.coverImage?.extraLarge || '';
}
@@ -181,6 +362,9 @@ async function loadAnime() {
renderEpisodes();
// Check if in list after loading anime data
await checkIfInList();
} catch (err) {
console.error('Error loading anime:', err);
document.getElementById('title').innerText = "Error loading anime";
@@ -274,4 +458,30 @@ searchInput.addEventListener('input', (e) => {
}
});
// Close modal on outside click
document.addEventListener('DOMContentLoaded', () => {
const modal = document.getElementById('add-list-modal');
if (modal) {
modal.addEventListener('click', (e) => {
if (e.target.id === 'add-list-modal') {
closeAddToListModal();
}
});
}
});
// Add animations
const style = document.createElement('style');
style.textContent = `
@keyframes slideInRight {
from { transform: translateX(400px); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
@keyframes slideOutRight {
from { transform: translateX(0); opacity: 1; }
to { transform: translateX(400px); opacity: 0; }
}
`;
document.head.appendChild(style);
loadAnime();

View File

@@ -6,6 +6,13 @@ const itemsPerPage = 12;
let extensionName = null;
let bookSlug = null;
// NUEVAS VARIABLES GLOBALES PARA LISTA
let currentBookData = null;
let isInList = false;
let currentListEntry = null;
const API_BASE = '/api';
function getBookUrl(id, source = 'anilist') {
return `/api/book/${id}?source=${source}`;
}
@@ -14,6 +21,222 @@ function getChaptersUrl(id, source = 'anilist') {
return `/api/book/${id}/chapters?source=${source}`;
}
// ==========================================================
// 1. FUNCIONES DE AUTENTICACIÓN Y LISTA
// ==========================================================
// Auth helpers
function getAuthToken() {
return localStorage.getItem('token');
}
function getAuthHeaders() {
const token = getAuthToken();
return {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
};
}
// Check if book is in list
async function checkIfInList() {
try {
const response = await fetch(`${API_BASE}/list`, {
headers: getAuthHeaders()
});
if (response.ok) {
const data = await response.json();
const idToSearch = extensionName ? bookSlug : bookId;
const entry = data.results?.find(item =>
item.entry_id === idToSearch &&
item.source === (extensionName || 'anilist')
);
if (entry) {
isInList = true;
currentListEntry = entry;
updateAddToListButton();
}
}
} catch (error) {
console.error('Error checking list:', error);
}
}
// Update button state
function updateAddToListButton() {
const btn = document.getElementById('add-to-list-btn');
if (!btn) return;
if (isInList) {
btn.innerHTML = `
<svg width="20" height="20" fill="currentColor" viewBox="0 0 24 24">
<path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
</svg>
In Your Library
`;
btn.style.background = 'rgba(34, 197, 94, 0.2)';
btn.style.color = '#22c55e';
btn.style.borderColor = 'rgba(34, 197, 94, 0.3)';
btn.onclick = openAddToListModal;
} else {
btn.innerHTML = '+ Add to Library';
btn.style.background = null; // Restablecer estilos si no está en lista
btn.style.color = null;
btn.style.borderColor = null;
btn.onclick = openAddToListModal;
}
}
// Open add to list modal
function openAddToListModal() {
if (!currentBookData) return;
// Obtener el total de capítulos/volúmenes
const totalUnits = currentBookData.chapters || currentBookData.volumes || 999;
if (isInList) {
// If already in list, open edit modal with current data
document.getElementById('modal-status').value = currentListEntry.status || 'PLANNING';
document.getElementById('modal-progress').value = currentListEntry.progress || 0;
document.getElementById('modal-score').value = currentListEntry.score || '';
document.getElementById('modal-title').textContent = 'Edit Library Entry';
document.getElementById('modal-delete-btn').style.display = 'block';
} else {
// New entry defaults
document.getElementById('modal-status').value = 'PLANNING';
document.getElementById('modal-progress').value = 0;
document.getElementById('modal-score').value = '';
document.getElementById('modal-title').textContent = 'Add to Library';
document.getElementById('modal-delete-btn').style.display = 'none';
}
// Ajustar etiqueta de progreso según el formato
const progressLabel = document.getElementById('modal-progress-label');
if (progressLabel) {
const format = currentBookData.format?.toUpperCase() || 'MANGA';
if (format === 'MANGA' || format === 'ONE_SHOT' || format === 'MANHWA') {
progressLabel.textContent = 'Chapters Read';
} else {
progressLabel.textContent = 'Volumes/Parts Read';
}
}
document.getElementById('modal-progress').max = totalUnits;
document.getElementById('add-list-modal').classList.add('active');
}
// Close modal
function closeAddToListModal() {
document.getElementById('add-list-modal').classList.remove('active');
}
// Save to list
async function saveToList() {
const status = document.getElementById('modal-status').value;
const progress = parseInt(document.getElementById('modal-progress').value) || 0;
const score = parseFloat(document.getElementById('modal-score').value) || null;
if (!currentBookData) {
showNotification('Cannot save: Book data not loaded.', 'error');
return;
}
// Determinar el tipo de entrada (MANGA o NOVEL basado en el formato)
const format = currentBookData.format?.toUpperCase() || 'MANGA';
const entryType = (format === 'MANGA' || format === 'ONE_SHOT' || format === 'MANHWA') ? 'MANGA' : 'NOVEL';
const idToSave = extensionName ? bookSlug : bookId;
try {
const response = await fetch(`${API_BASE}/list/entry`, {
method: 'POST',
headers: getAuthHeaders(),
body: JSON.stringify({
entry_id: idToSave,
source: extensionName || 'anilist',
entry_type: entryType,
status: status,
progress: progress,
score: score
})
});
if (!response.ok) {
throw new Error('Failed to save entry');
}
isInList = true;
currentListEntry = { entry_id: idToSave, source: extensionName || 'anilist', entry_type: entryType, status, progress, score };
updateAddToListButton();
closeAddToListModal();
showNotification(isInList ? 'Updated successfully!' : 'Added to your library!', 'success');
} catch (error) {
console.error('Error saving to list:', error);
showNotification('Failed to save. Please try again.', 'error');
}
}
// Delete from list
async function deleteFromList() {
if (!confirm('Remove this book from your library?')) return;
const idToDelete = extensionName ? bookSlug : bookId;
try {
const response = await fetch(`${API_BASE}/list/entry/${idToDelete}`, {
method: 'DELETE',
headers: getAuthHeaders()
});
if (!response.ok) {
throw new Error('Failed to delete entry');
}
isInList = false;
currentListEntry = null;
updateAddToListButton();
closeAddToListModal();
showNotification('Removed from your library', 'success');
} catch (error) {
console.error('Error deleting from list:', error);
showNotification('Failed to remove. Please try again.', 'error');
}
}
// Show notification
function showNotification(message, type = 'info') {
const notification = document.createElement('div');
notification.style.cssText = `
position: fixed;
top: 100px;
right: 20px;
background: ${type === 'success' ? '#22c55e' : type === 'error' ? '#ef4444' : '#8b5cf6'};
color: white;
padding: 1rem 1.5rem;
border-radius: 12px;
box-shadow: 0 10px 30px rgba(0,0,0,0.3);
z-index: 9999;
font-weight: 600;
animation: slideInRight 0.3s ease;
`;
notification.textContent = message;
document.body.appendChild(notification);
setTimeout(() => {
notification.style.animation = 'slideOutRight 0.3s ease';
setTimeout(() => notification.remove(), 300);
}, 3000);
}
// ==========================================================
// 2. FUNCIÓN PRINCIPAL DE CARGA (init)
// ==========================================================
async function init() {
try {
const path = window.location.pathname;
@@ -46,6 +269,8 @@ async function init() {
return;
}
currentBookData = data; // <--- GUARDAR DATOS GLOBALES
let title, description, score, year, status, format, chapters, poster, banner, genres;
if (extensionName) {
@@ -125,11 +350,18 @@ async function init() {
loadChapters(idForFetch);
await checkIfInList(); // <--- COMPROBAR ESTADO DE LA LISTA
} catch (err) {
console.error("Metadata Error:", err);
}
}
// ==========================================================
// 3. FUNCIONES DE CARGA Y RENDERIZADO DE CAPÍTULOS
// (Sin cambios, pero se incluyen para completar el script)
// ==========================================================
async function loadChapters(idForFetch) {
const tbody = document.getElementById('chapters-body');
if (!tbody) return;
@@ -291,4 +523,34 @@ function openReader(bookId, chapterId, provider) {
window.location.href = `/read/${p}/${c}/${bookId}${extension}`;
}
// ==========================================================
// 4. LISTENERS Y ARRANQUE
// ==========================================================
// Close modal on outside click
document.addEventListener('DOMContentLoaded', () => {
const modal = document.getElementById('add-list-modal');
if (modal) {
modal.addEventListener('click', (e) => {
if (e.target.id === 'add-list-modal') {
closeAddToListModal();
}
});
}
});
// Add animations (Copied from anime.js)
const style = document.createElement('style');
style.textContent = `
@keyframes slideInRight {
from { transform: translateX(400px); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
@keyframes slideOutRight {
from { transform: translateX(0); opacity: 1; }
to { transform: translateX(400px); opacity: 0; }
}
`;
document.head.appendChild(style);
init();

428
src/scripts/list.js Normal file
View File

@@ -0,0 +1,428 @@
// API Configuration
const API_BASE = '/api';
let currentList = [];
let filteredList = [];
let currentEditingEntry = null;
// Get token from localStorage
function getAuthToken() {
return localStorage.getItem('token');
}
// Create headers with auth token
function getAuthHeaders() {
const token = getAuthToken();
return {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
};
}
// Initialize on page load
document.addEventListener('DOMContentLoaded', async () => {
await loadList();
setupEventListeners();
});
// ==========================================================
// FUNCIÓN: Poblar Filtro de Fuente (NUEVA LÓGICA)
// ==========================================================
async function populateSourceFilter() {
const select = document.getElementById('source-filter');
if (!select) return;
// Opciones base
select.innerHTML = `
<option value="all">All Sources</option>
<option value="anilist">AniList</option>
<option value="local">Local</option>
`;
try {
const response = await fetch(`${API_BASE}/extensions`);
if (response.ok) {
const data = await response.json();
const extensions = data.extensions || [];
// Añadir cada nombre de extensión como una opción
extensions.forEach(extName => {
// Evitar duplicar 'anilist' o 'local'
if (extName.toLowerCase() !== 'anilist' && extName.toLowerCase() !== 'local') {
const option = document.createElement('option');
option.value = extName;
// Capitalizar el nombre
option.textContent = extName.charAt(0).toUpperCase() + extName.slice(1);
select.appendChild(option);
}
});
}
} catch (error) {
console.error('Error loading extensions:', error);
}
}
// Setup all event listeners
function setupEventListeners() {
// View toggle
document.querySelectorAll('.view-btn').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.view-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
const view = btn.dataset.view;
const container = document.getElementById('list-container');
if (view === 'list') {
container.classList.add('list-view');
} else {
container.classList.remove('list-view');
}
});
});
// Filters
document.getElementById('status-filter').addEventListener('change', applyFilters);
document.getElementById('source-filter').addEventListener('change', applyFilters);
document.getElementById('type-filter').addEventListener('change', applyFilters);
document.getElementById('sort-filter').addEventListener('change', applyFilters);
// Search
document.querySelector('.search-input').addEventListener('input', (e) => {
const query = e.target.value.toLowerCase();
if (query) {
filteredList = currentList.filter(item =>
item.title?.toLowerCase().includes(query)
);
} else {
filteredList = [...currentList];
}
applyFilters();
});
}
// Load list from API (MODIFICADO para incluir populateSourceFilter)
async function loadList() {
const loadingState = document.getElementById('loading-state');
const emptyState = document.getElementById('empty-state');
const container = document.getElementById('list-container');
// Ejecutar la carga de extensiones antes de la lista principal
await populateSourceFilter();
try {
loadingState.style.display = 'flex';
emptyState.style.display = 'none';
container.innerHTML = '';
const response = await fetch(`${API_BASE}/list`, {
headers: getAuthHeaders()
});
if (!response.ok) {
throw new Error('Failed to load list');
}
const data = await response.json();
currentList = data.results || [];
filteredList = [...currentList];
loadingState.style.display = 'none';
if (currentList.length === 0) {
emptyState.style.display = 'flex';
} else {
updateStats();
applyFilters();
}
} catch (error) {
console.error('Error loading list:', error);
loadingState.style.display = 'none';
alert('Failed to load your list. Please try again.');
}
}
// Update statistics
function updateStats() {
const total = currentList.length;
const watching = currentList.filter(item => item.status === 'WATCHING').length;
const completed = currentList.filter(item => item.status === 'COMPLETED').length;
const planning = currentList.filter(item => item.status === 'PLANNING').length;
document.getElementById('total-count').textContent = total;
document.getElementById('watching-count').textContent = watching;
document.getElementById('completed-count').textContent = completed;
document.getElementById('planned-count').textContent = planning;
}
// Apply filters and sorting
function applyFilters() {
const statusFilter = document.getElementById('status-filter').value;
const sourceFilter = document.getElementById('source-filter').value;
const typeFilter = document.getElementById('type-filter').value;
const sortFilter = document.getElementById('sort-filter').value;
// Filter
let filtered = [...filteredList];
if (statusFilter !== 'all') {
filtered = filtered.filter(item => item.status === statusFilter);
}
if (sourceFilter !== 'all') {
filtered = filtered.filter(item => item.source === sourceFilter);
}
// Filtrado por tipo
if (typeFilter !== 'all') {
filtered = filtered.filter(item => (item.entry_type || 'ANIME') === typeFilter);
}
// Sort
switch (sortFilter) {
case 'title':
filtered.sort((a, b) => (a.title || '').localeCompare(b.title || ''));
break;
case 'score':
filtered.sort((a, b) => (b.score || 0) - (a.score || 0));
break;
case 'progress':
filtered.sort((a, b) => (b.progress || 0) - (a.progress || 0));
break;
case 'updated':
default:
filtered.sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at));
break;
}
renderList(filtered);
}
// Render list items
function renderList(items) {
const container = document.getElementById('list-container');
container.innerHTML = '';
if (items.length === 0) {
container.innerHTML = '<div class="empty-state"><p>No entries match your filters</p></div>';
return;
}
items.forEach(item => {
const element = createListItem(item);
container.appendChild(element);
});
}
// Create individual list item (ACTUALIZADO para MANGA/NOVEL)
function createListItem(item) {
const div = document.createElement('div');
div.className = 'list-item';
div.onclick = () => openEditModal(item);
const posterUrl = item.poster || '/public/assets/placeholder.png';
const progress = item.progress || 0;
// Determinar total de unidades basado en el tipo
const totalUnits = item.entry_type === 'ANIME' ?
item.total_episodes || 0 :
item.total_chapters || 0;
const progressPercent = totalUnits > 0 ? (progress / totalUnits) * 100 : 0;
const score = item.score ? item.score.toFixed(1) : null;
// Determinar la etiqueta de unidad (Episodes, Chapters, Volumes, etc.)
const entryType = (item.entry_type || 'ANIME').toUpperCase();
let unitLabel = 'units';
if (entryType === 'ANIME') {
unitLabel = 'episodes';
} else if (entryType === 'MANGA') {
unitLabel = 'chapters';
} else if (entryType === 'NOVEL') {
unitLabel = 'chapters/volumes';
}
// Ajustar etiquetas de estado según el tipo (Watching/Reading)
const statusLabels = {
'WATCHING': entryType === 'ANIME' ? 'Watching' : 'Reading',
'COMPLETED': 'Completed',
'PLANNING': entryType === 'ANIME' ? 'Plan to Watch' : 'Plan to Read',
'PAUSED': 'Paused',
'DROPPED': 'Dropped'
};
div.innerHTML = `
<img src="${posterUrl}" alt="${item.title || 'Entry'}" class="item-poster" onerror="this.src='/public/assets/placeholder.png'">
<div class="item-content">
<h3 class="item-title">${item.title || 'Unknown Title'}</h3>
<div class="item-meta">
<span class="meta-pill status-pill">${statusLabels[item.status] || item.status}</span>
<span class="meta-pill type-pill">${entryType}</span>
<span class="meta-pill source-pill">${item.source.toUpperCase()}</span>
</div>
<div class="progress-bar-container">
<div class="progress-bar" style="width: ${progressPercent}%"></div>
</div>
<div class="progress-text">
<span>${progress}${totalUnits > 0 ? ` / ${totalUnits}` : ''} ${unitLabel}</span> ${score ? `<span class="score-badge">⭐ ${score}</span>` : ''}
</div>
</div>
`;
return div;
}
// Open edit modal (ACTUALIZADO para MANGA/NOVEL)
function openEditModal(item) {
currentEditingEntry = item;
document.getElementById('edit-status').value = item.status;
document.getElementById('edit-progress').value = item.progress || 0;
document.getElementById('edit-score').value = item.score || '';
// Ajusta el texto del campo de progreso en el modal
const entryType = (item.entry_type || 'ANIME').toUpperCase();
const progressLabel = document.querySelector('label[for="edit-progress"]');
if (progressLabel) {
if (entryType === 'MANGA') {
progressLabel.textContent = 'Chapters Read';
} else if (entryType === 'NOVEL') {
progressLabel.textContent = 'Chapters/Volumes Read';
} else {
progressLabel.textContent = 'Episodes Watched';
}
}
// Establecer el max del progreso
const totalUnits = item.entry_type === 'ANIME' ?
item.total_episodes || 999 :
item.total_chapters || 999;
document.getElementById('edit-progress').max = totalUnits;
document.getElementById('edit-modal').style.display = 'flex';
}
// Close edit modal
function closeEditModal() {
currentEditingEntry = null;
document.getElementById('edit-modal').style.display = 'none';
}
// Save entry changes
async function saveEntry() {
if (!currentEditingEntry) return;
const status = document.getElementById('edit-status').value;
const progress = parseInt(document.getElementById('edit-progress').value) || 0;
const score = parseFloat(document.getElementById('edit-score').value) || null;
try {
const response = await fetch(`${API_BASE}/list/entry`, {
method: 'POST',
headers: getAuthHeaders(),
body: JSON.stringify({
entry_id: currentEditingEntry.entry_id,
source: currentEditingEntry.source,
entry_type: currentEditingEntry.entry_type || 'ANIME',
status: status,
progress: progress,
score: score
})
});
if (!response.ok) {
throw new Error('Failed to update entry');
}
closeEditModal();
await loadList();
showNotification('Entry updated successfully!', 'success');
} catch (error) {
console.error('Error updating entry:', error);
showNotification('Failed to update entry', 'error');
}
}
// Delete entry
async function deleteEntry() {
if (!currentEditingEntry) return;
if (!confirm('Are you sure you want to remove this entry from your list?')) {
return;
}
try {
const response = await fetch(`${API_BASE}/list/entry/${currentEditingEntry.entry_id}`, {
method: 'DELETE',
headers: getAuthHeaders()
});
if (!response.ok) {
throw new Error('Failed to delete entry');
}
closeEditModal();
await loadList();
showNotification('Entry removed from list', 'success');
} catch (error) {
console.error('Error deleting entry:', error);
showNotification('Failed to remove entry', 'error');
}
}
// Show notification (unchanged)
function showNotification(message, type = 'info') {
const notification = document.createElement('div');
notification.style.cssText = `
position: fixed;
top: 100px;
right: 20px;
background: ${type === 'success' ? '#22c55e' : type === 'error' ? '#ef4444' : '#8b5cf6'};
color: white;
padding: 1rem 1.5rem;
border-radius: 12px;
box-shadow: 0 10px 30px rgba(0,0,0,0.3);
z-index: 9999;
font-weight: 600;
animation: slideInRight 0.3s ease;
`;
notification.textContent = message;
document.body.appendChild(notification);
setTimeout(() => {
notification.style.animation = 'slideOutRight 0.3s ease';
setTimeout(() => notification.remove(), 300);
}, 3000);
}
// Add keyframe animations (unchanged)
const style = document.createElement('style');
style.textContent = `
@keyframes slideInRight {
from {
transform: translateX(400px);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
@keyframes slideOutRight {
from {
transform: translateX(0);
opacity: 1;
}
to {
transform: translateX(400px);
opacity: 0;
}
}
`;
document.head.appendChild(style);
// Close modal on outside click (unchanged)
document.getElementById('edit-modal').addEventListener('click', (e) => {
if (e.target.id === 'edit-modal') {
closeEditModal();
}
});

View File

@@ -588,9 +588,6 @@ async function redirectToAniListLogin() {
const data = await res.json();
localStorage.setItem('token', data.token);
token = data.token;
localStorage.setItem('anilist_link_user', currentUserId);
const clientId = 32898;
const redirectUri = encodeURIComponent(