/* eslint-disable no-console */ 'use client'; import { useEffect, useState } from 'react'; import { createPortal } from 'react-dom'; import { AlertTriangle } from 'lucide-react'; import type { PlayRecord } from '@/lib/db.client'; import { clearAllPlayRecords, getAllPlayRecords, subscribeToDataUpdates, } from '@/lib/db.client'; import VideoCard from '@/components/VideoCard'; import VirtualScrollableRow from '@/components/VirtualScrollableRow'; interface ContinueWatchingProps { className?: string; } export default function ContinueWatching({ className }: ContinueWatchingProps) { const [playRecords, setPlayRecords] = useState< (PlayRecord & { key: string })[] >([]); const [loading, setLoading] = useState(true); const [showConfirmDialog, setShowConfirmDialog] = useState(false); // 处理播放记录数据更新的函数 const updatePlayRecords = (allRecords: Record) => { // 将记录转换为数组并根据 save_time 由近到远排序 const recordsArray = Object.entries(allRecords).map(([key, record]) => ({ ...record, key, })); // 按 save_time 降序排序(最新的在前面) const sortedRecords = recordsArray.sort( (a, b) => b.save_time - a.save_time ); setPlayRecords(sortedRecords); }; useEffect(() => { const fetchPlayRecords = async () => { try { setLoading(true); // 从缓存或API获取所有播放记录 const allRecords = await getAllPlayRecords(); updatePlayRecords(allRecords); } catch (error) { console.error('获取播放记录失败:', error); setPlayRecords([]); } finally { setLoading(false); } }; fetchPlayRecords(); // 监听播放记录更新事件 const unsubscribe = subscribeToDataUpdates( 'playRecordsUpdated', (newRecords: Record) => { updatePlayRecords(newRecords); } ); return unsubscribe; }, []); // 如果没有播放记录,则不渲染组件 if (!loading && playRecords.length === 0) { return null; } // 计算播放进度百分比 const getProgress = (record: PlayRecord) => { if (record.total_time === 0) return 0; return (record.play_time / record.total_time) * 100; }; // 从 key 中解析 source 和 id const parseKey = (key: string) => { const [source, id] = key.split('+'); return { source, id }; }; // 处理清空确认 const handleClearConfirm = async () => { await clearAllPlayRecords(); setPlayRecords([]); setShowConfirmDialog(false); }; return ( <>

继续观看

{!loading && playRecords.length > 0 && ( )}
{loading ? ( // 加载状态显示灰色占位数据(使用原始 ScrollableRow)
{Array.from({ length: 8 }).map((_, index) => (
))}
) : ( // 使用虚拟滚动显示真实数据 {playRecords.map((record) => { const { source, id } = parseKey(record.key); return (
setPlayRecords((prev) => prev.filter((r) => r.key !== record.key) ) } type={record.total_episodes > 1 ? 'tv' : ''} origin={record.origin} orientation='horizontal' playTime={record.play_time} totalTime={record.total_time} />
); })}
)}
{/* 确认对话框 */} {showConfirmDialog && createPortal(
setShowConfirmDialog(false)} >
e.stopPropagation()} >
{/* 图标和标题 */}

清空播放记录

确定要清空所有播放记录吗?此操作不可恢复。

{/* 按钮组 */}
, document.body )} ); }