const API_BASE = '/api'; let playlists = []; let pollingInterval = null; // Toast Notification System function showToast(message, type = 'info') { const container = document.getElementById('toast-container'); const toast = document.createElement('div'); const colors = { info: 'bg-blue-500/80 border-blue-500/50', success: 'bg-green-500/80 border-green-500/50', error: 'bg-red-500/80 border-red-500/50', warning: 'bg-yellow-500/80 border-yellow-500/50' }; const icons = { info: 'fa-circle-info', success: 'fa-circle-check', error: 'fa-circle-exclamation', warning: 'fa-triangle-exclamation' }; toast.className = `glass-panel ${colors[type] || colors.info} border text-white px-4 py-3 rounded-xl flex items-center gap-3 shadow-xl transform transition-all duration-300 translate-x-full opacity-0`; toast.innerHTML = ` ${message} `; container.appendChild(toast); // Animation in requestAnimationFrame(() => { toast.classList.remove('translate-x-full', 'opacity-0'); }); // Remove after delay setTimeout(() => { toast.classList.add('translate-x-full', 'opacity-0'); setTimeout(() => toast.remove(), 300); }, 3000); } // Format Utilities function formatTimestamp(timestamp) { if (!timestamp) return '从未同步'; const date = new Date(timestamp); const now = new Date(); const diff = now - date; if (diff < 60000) return '刚刚'; if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`; if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`; return date.toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }); } function getStatusConfig(status) { switch (status) { case 'syncing': return { text: '同步中', class: 'bg-yellow-500/80 text-white border-yellow-400/50 animate-pulse' }; case 'success': return { text: '已同步', class: 'bg-green-500/80 text-white border-green-400/50' }; case 'failed': case 'error': return { text: '失败', class: 'bg-red-500/80 text-white border-red-400/50' }; default: return { text: '待同步', class: 'bg-gray-500/50 text-gray-300 border-gray-400/30' }; } } // Core Logic async function loadPlaylists() { try { const response = await fetch(`${API_BASE}/playlists`); if (!response.ok) throw new Error('加载歌单失败'); const data = await response.json(); // Deep compare to avoid unnecessary re-renders if nothing changed // For simplicity, we just check length and status of syncing items // But to ensure progress bars update smoothly, we re-render or update existing // Here we'll re-render for simplicity as the list is likely small playlists = data; updateStats(); renderPlaylists(); // Adjust polling based on activity const anySyncing = playlists.some(p => p.status === 'syncing'); adjustPolling(anySyncing); } catch (error) { console.error('加载歌单失败:', error); showToast(error.message, 'error'); } } function adjustPolling(isActive) { if (isActive && !pollingInterval) { pollingInterval = setInterval(loadPlaylists, 2000); } else if (!isActive && pollingInterval) { clearInterval(pollingInterval); pollingInterval = null; // Poll infrequently when idle just in case pollingInterval = setInterval(loadPlaylists, 10000); } else if (!pollingInterval) { // Default idle polling pollingInterval = setInterval(loadPlaylists, 10000); } } function updateStats() { const total = playlists.length; const synced = playlists.filter(p => p.status === 'success').length; const syncing = playlists.filter(p => p.status === 'syncing').length; const songs = playlists.reduce((acc, curr) => acc + (curr.songs?.length || 0), 0); // Animate numbers animateValue('stat-total', parseInt(document.getElementById('stat-total').innerText), total, 500); animateValue('stat-synced', parseInt(document.getElementById('stat-synced').innerText), synced, 500); animateValue('stat-songs', parseInt(document.getElementById('stat-songs').innerText), songs, 500); animateValue('stat-syncing', parseInt(document.getElementById('stat-syncing').innerText), syncing, 500); const statsContainer = document.getElementById('stats-container'); if (total > 0) { statsContainer.classList.remove('hidden'); } else { statsContainer.classList.add('hidden'); } } function animateValue(id, start, end, duration) { if (start === end) return; const obj = document.getElementById(id); const range = end - start; let current = start; const increment = end > start ? 1 : -1; const stepTime = Math.abs(Math.floor(duration / range)); const timer = setInterval(() => { current += increment; obj.innerHTML = current; if (current == end) { clearInterval(timer); } }, Math.max(stepTime, 20)); // Cap speed } function renderPlaylists() { const grid = document.getElementById('playlist-grid'); const emptyState = document.getElementById('empty-state'); const template = document.getElementById('playlist-card-template'); if (playlists.length === 0) { grid.innerHTML = ''; emptyState.classList.remove('hidden'); return; } emptyState.classList.add('hidden'); // We want to preserve existing elements to keep animations smooth if possible // But full re-render is safer for state consistency. // Optimization: Diffing by ID could be done here. grid.innerHTML = ''; // Simple clear for now playlists.forEach(playlist => { const clone = template.content.cloneNode(true); const card = clone.querySelector('div'); // The root div // Data binding const img = clone.querySelector('.playlist-cover'); img.src = playlist.cover || 'https://p2.music.126.net/6y-UleORITEDbvrOLV0Q8A==/5639395138885805.jpg'; // Fallback image img.alt = playlist.name; clone.querySelector('.playlist-name').textContent = playlist.name; clone.querySelector('.playlist-count').textContent = (playlist.songs || []).length; clone.querySelector('.playlist-date').textContent = formatTimestamp(playlist.lastSyncTime); clone.querySelector('.playlist-id').textContent = `ID: ${playlist.neteaseId}`; clone.querySelector('.playlist-link').href = `https://music.163.com/#/playlist?id=${playlist.neteaseId}`; // Status Badge const statusConfig = getStatusConfig(playlist.status); const badge = clone.querySelector('.playlist-status'); badge.textContent = statusConfig.text; badge.className = `playlist-status px-2.5 py-1 rounded-full text-xs font-medium backdrop-blur-md border ${statusConfig.class}`; // Actions const syncBtn = clone.querySelector('.action-sync'); const deleteBtn = clone.querySelector('.action-delete'); syncBtn.onclick = () => syncPlaylist(playlist.id); deleteBtn.onclick = () => deletePlaylist(playlist.id); if (playlist.status === 'syncing') { syncBtn.disabled = true; syncBtn.classList.add('opacity-50', 'cursor-not-allowed'); syncBtn.querySelector('i').classList.add('fa-spin'); // Show Progress Overlay const overlay = clone.querySelector('.sync-overlay'); overlay.classList.remove('translate-y-full'); clone.querySelector('.sync-message').textContent = playlist.syncMessage || '同步中...'; clone.querySelector('.sync-percent').textContent = `${playlist.syncProgress || 0}%`; clone.querySelector('.sync-progress-bar').style.width = `${playlist.syncProgress || 0}%`; } else { // Hide overlay is default by CSS class } grid.appendChild(clone); }); } // Actions async function addPlaylist() { const input = document.getElementById('playlistInput'); const value = input.value.trim(); if (!value) { showToast('请输入歌单 ID 或链接', 'warning'); return; } const btn = document.querySelector('button[onclick="addPlaylist()"]'); const originalIcon = btn.innerHTML; btn.disabled = true; btn.innerHTML = ' 处理中...'; try { const response = await fetch(`${API_BASE}/playlists`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ url: value }) }); if (!response.ok) { const error = await response.json(); throw new Error(error.error || '添加歌单失败'); } await loadPlaylists(); // Refresh list input.value = ''; showToast('歌单添加成功', 'success'); } catch (error) { console.error('添加歌单失败:', error); showToast(error.message, 'error'); } finally { btn.disabled = false; btn.innerHTML = originalIcon; } } async function deletePlaylist(id) { if (!confirm('确定要移除这个歌单吗?')) return; try { const response = await fetch(`${API_BASE}/playlists/${id}`, { method: 'DELETE' }); if (!response.ok) throw new Error('删除失败'); showToast('歌单已移除', 'success'); // Optimistic update playlists = playlists.filter(p => p.id !== id); updateStats(); renderPlaylists(); } catch (error) { showToast(error.message, 'error'); loadPlaylists(); // Revert on error } } async function syncPlaylist(id) { try { const response = await fetch(`${API_BASE}/playlists/${id}/sync`, { method: 'POST' }); if (!response.ok) throw new Error('启动同步失败'); showToast('已启动同步任务', 'info'); loadPlaylists(); // Update UI immediately to show syncing state } catch (error) { showToast(error.message, 'error'); } } // Input Handler document.getElementById('playlistInput').addEventListener('keypress', (e) => { if (e.key === 'Enter') { addPlaylist(); } }); // Initial Load loadPlaylists();