修复继续观看渐进式加载

This commit is contained in:
mtvpls
2026-03-20 00:17:08 +08:00
parent 0322b2650b
commit dbc32a2a37
2 changed files with 229 additions and 199 deletions
+66 -72
View File
@@ -8,60 +8,71 @@ import { createPortal } from 'react-dom';
import type { PlayRecord } from '@/lib/db.client'; import type { PlayRecord } from '@/lib/db.client';
import { import {
clearAllPlayRecords, clearAllPlayRecords,
getCachedPlayRecordsSnapshot,
getAllPlayRecords, getAllPlayRecords,
subscribeToDataUpdates, subscribeToDataUpdates,
} from '@/lib/db.client'; } from '@/lib/db.client';
import VideoCard from '@/components/VideoCard';
import PlayRecordsPanel from '@/components/PlayRecordsPanel'; import PlayRecordsPanel from '@/components/PlayRecordsPanel';
import VideoCard from '@/components/VideoCard';
import VirtualScrollableRow from '@/components/VirtualScrollableRow'; import VirtualScrollableRow from '@/components/VirtualScrollableRow';
interface ContinueWatchingProps { interface ContinueWatchingProps {
className?: string; className?: string;
} }
type PlayRecordItem = PlayRecord & { key: string };
export default function ContinueWatching({ className }: ContinueWatchingProps) { export default function ContinueWatching({ className }: ContinueWatchingProps) {
const [playRecords, setPlayRecords] = useState< const storageType = process.env.NEXT_PUBLIC_STORAGE_TYPE || 'localstorage';
(PlayRecord & { key: string })[] const cachedDisplayLimit = storageType !== 'localstorage' ? 10 : undefined;
>([]); const [playRecords, setPlayRecords] = useState<PlayRecordItem[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [showConfirmDialog, setShowConfirmDialog] = useState(false); const [showConfirmDialog, setShowConfirmDialog] = useState(false);
const [showPlayRecordsPanel, setShowPlayRecordsPanel] = useState(false); const [showPlayRecordsPanel, setShowPlayRecordsPanel] = useState(false);
// 处理播放记录数据更新的函数 const updatePlayRecords = (
const updatePlayRecords = (allRecords: Record<string, PlayRecord>, limit?: number) => { allRecords: Record<string, PlayRecord>,
// 将记录转换为数组并根据 save_time 由近到远排序 limit?: number
) => {
const recordsArray = Object.entries(allRecords).map(([key, record]) => ({ const recordsArray = Object.entries(allRecords).map(([key, record]) => ({
...record, ...record,
key, key,
})); }));
// 按 save_time 降序排序(最新的在前面) const sortedRecords = recordsArray.sort((a, b) => b.save_time - a.save_time);
const sortedRecords = recordsArray.sort( setPlayRecords(limit ? sortedRecords.slice(0, limit) : sortedRecords);
(a, b) => b.save_time - a.save_time };
);
// 如果指定了 limit,只取前 N 条 const applyCachedSnapshot = () => {
const finalRecords = limit ? sortedRecords.slice(0, limit) : sortedRecords; const cachedRecords = getCachedPlayRecordsSnapshot();
if (Object.keys(cachedRecords).length === 0) {
return false;
}
setPlayRecords(finalRecords); updatePlayRecords(cachedRecords, cachedDisplayLimit);
setLoading(false);
return true;
}; };
useEffect(() => { useEffect(() => {
const unsubscribe = subscribeToDataUpdates(
'playRecordsUpdated',
(newRecords: Record<string, PlayRecord>) => {
updatePlayRecords(newRecords);
setLoading(false);
}
);
const fetchPlayRecords = async () => { const fetchPlayRecords = async () => {
try { try {
const hasCachedSnapshot = applyCachedSnapshot();
if (!hasCachedSnapshot) {
setLoading(true); setLoading(true);
// 从缓存或API获取所有播放记录
const allRecords = await getAllPlayRecords();
// 非 localStorage 模式下,先只显示前 10 条记录
const storageType = process.env.NEXT_PUBLIC_STORAGE_TYPE || 'localstorage';
if (storageType !== 'localstorage') {
updatePlayRecords(allRecords, 10);
} else {
updatePlayRecords(allRecords);
} }
const allRecords = await getAllPlayRecords();
updatePlayRecords(allRecords);
} catch (error) { } catch (error) {
console.error('获取播放记录失败:', error); console.error('获取播放记录失败:', error);
setPlayRecords([]); setPlayRecords([]);
@@ -71,37 +82,23 @@ export default function ContinueWatching({ className }: ContinueWatchingProps) {
}; };
fetchPlayRecords(); fetchPlayRecords();
// 监听播放记录更新事件
const unsubscribe = subscribeToDataUpdates(
'playRecordsUpdated',
(newRecords: Record<string, PlayRecord>) => {
// 同步完成后,加载完整数据(不限制数量)
updatePlayRecords(newRecords);
}
);
return unsubscribe; return unsubscribe;
}, []); }, [cachedDisplayLimit]);
// 如果没有播放记录,则不渲染组件
if (!loading && playRecords.length === 0) { if (!loading && playRecords.length === 0) {
return null; return null;
} }
// 计算播放进度百分比
const getProgress = (record: PlayRecord) => { const getProgress = (record: PlayRecord) => {
if (record.total_time === 0) return 0; if (record.total_time === 0) return 0;
return (record.play_time / record.total_time) * 100; return (record.play_time / record.total_time) * 100;
}; };
// 从 key 中解析 source 和 id
const parseKey = (key: string) => { const parseKey = (key: string) => {
const [source, id] = key.split('+'); const [source, id] = key.split('+');
return { source, id }; return { source, id };
}; };
// 处理清空确认
const handleClearConfirm = async () => { const handleClearConfirm = async () => {
await clearAllPlayRecords(); await clearAllPlayRecords();
setPlayRecords([]); setPlayRecords([]);
@@ -134,23 +131,21 @@ export default function ContinueWatching({ className }: ContinueWatchingProps) {
)} )}
</div> </div>
{loading ? ( {loading ? (
// 加载状态显示灰色占位数据(使用原始 ScrollableRow <div className='flex gap-2 overflow-x-auto scrollbar-hide pb-2 pt-2'>
<div className="flex gap-2 overflow-x-auto scrollbar-hide pt-2 pb-2">
{Array.from({ length: 8 }).map((_, index) => ( {Array.from({ length: 8 }).map((_, index) => (
<div <div
key={index} key={index}
className='min-w-[180px] w-48 sm:min-w-[200px] sm:w-52' className='min-w-[180px] w-48 sm:min-w-[200px] sm:w-52'
> >
<div className='relative aspect-[3/2] w-full overflow-hidden rounded-lg bg-gray-200 animate-pulse dark:bg-gray-800'> <div className='relative aspect-[3/2] w-full overflow-hidden rounded-lg bg-gray-200 animate-pulse dark:bg-gray-800'>
<div className='absolute inset-0 bg-gray-300 dark:bg-gray-700'></div> <div className='absolute inset-0 bg-gray-300 dark:bg-gray-700' />
</div> </div>
<div className='mt-1 h-1 bg-gray-200 rounded animate-pulse dark:bg-gray-800'></div> <div className='mt-1 h-1 rounded bg-gray-200 animate-pulse dark:bg-gray-800' />
<div className='mt-2 h-4 bg-gray-200 rounded animate-pulse dark:bg-gray-800 w-3/4'></div> <div className='mt-2 h-4 w-3/4 rounded bg-gray-200 animate-pulse dark:bg-gray-800' />
</div> </div>
))} ))}
</div> </div>
) : ( ) : (
// 使用虚拟滚动显示真实数据
<div> <div>
<VirtualScrollableRow> <VirtualScrollableRow>
{playRecords.map((record) => { {playRecords.map((record) => {
@@ -175,7 +170,7 @@ export default function ContinueWatching({ className }: ContinueWatchingProps) {
from='playrecord' from='playrecord'
onDelete={() => onDelete={() =>
setPlayRecords((prev) => setPlayRecords((prev) =>
prev.filter((r) => r.key !== record.key) prev.filter((item) => item.key !== record.key)
) )
} }
type={record.total_episodes > 1 ? 'tv' : ''} type={record.total_episodes > 1 ? 'tv' : ''}
@@ -184,7 +179,6 @@ export default function ContinueWatching({ className }: ContinueWatchingProps) {
playTime={record.play_time} playTime={record.play_time}
totalTime={record.total_time} totalTime={record.total_time}
/> />
{/* 新增剧集提示 - 完全独立于 VideoCard */}
{record.new_episodes && record.new_episodes > 0 && ( {record.new_episodes && record.new_episodes > 0 && (
<div <div
style={{ style={{
@@ -197,40 +191,41 @@ export default function ContinueWatching({ className }: ContinueWatchingProps) {
height: '28px', height: '28px',
}} }}
> >
{/* 水波纹动画 - 第一层 */}
<div <div
style={{ style={{
position: 'absolute', position: 'absolute',
inset: '0', inset: '0',
borderRadius: '9999px', borderRadius: '9999px',
backgroundColor: 'rgb(14 165 233)', backgroundColor: 'rgb(14 165 233)',
animation: 'ping-scale 1.5s cubic-bezier(0, 0, 0.2, 1) infinite', animation:
'ping-scale 1.5s cubic-bezier(0, 0, 0.2, 1) infinite',
}} }}
/> />
{/* 水波纹动画 - 第二层 */}
<div <div
style={{ style={{
position: 'absolute', position: 'absolute',
inset: '0', inset: '0',
borderRadius: '9999px', borderRadius: '9999px',
backgroundColor: 'rgb(14 165 233)', backgroundColor: 'rgb(14 165 233)',
animation: 'pulse-scale 2.5s cubic-bezier(0.4, 0, 0.6, 1) infinite', animation:
'pulse-scale 2.5s cubic-bezier(0.4, 0, 0.6, 1) infinite',
}} }}
/> />
{/* 主体徽章 */}
<div <div
style={{ style={{
position: 'absolute', position: 'absolute',
inset: '0', inset: '0',
borderRadius: '9999px', borderRadius: '9999px',
background: 'linear-gradient(to bottom right, rgb(14 165 233), rgb(2 132 199))', background:
'linear-gradient(to bottom right, rgb(14 165 233), rgb(2 132 199))',
color: 'white', color: 'white',
fontSize: '11px', fontSize: '11px',
fontWeight: 'bold', fontWeight: 'bold',
display: 'flex', display: 'flex',
alignItems: 'center', alignItems: 'center',
justifyContent: 'center', justifyContent: 'center',
boxShadow: '0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)', boxShadow:
'0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)',
animation: 'badge-scale 2s ease-in-out infinite', animation: 'badge-scale 2s ease-in-out infinite',
}} }}
> >
@@ -246,43 +241,41 @@ export default function ContinueWatching({ className }: ContinueWatchingProps) {
)} )}
</section> </section>
{/* 确认对话框 */} {showConfirmDialog &&
{showConfirmDialog && createPortal( createPortal(
<div <div
className='fixed inset-0 bg-black bg-opacity-50 z-[9999] flex items-center justify-center p-4 transition-opacity duration-300' className='fixed inset-0 z-[9999] flex items-center justify-center bg-black bg-opacity-50 p-4 transition-opacity duration-300'
onClick={() => setShowConfirmDialog(false)} onClick={() => setShowConfirmDialog(false)}
> >
<div <div
className='bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full border border-red-200 dark:border-red-800 transition-all duration-300' className='max-w-md w-full rounded-lg border border-red-200 bg-white shadow-xl transition-all duration-300 dark:border-red-800 dark:bg-gray-800'
onClick={(e) => e.stopPropagation()} onClick={(event) => event.stopPropagation()}
> >
<div className="p-6"> <div className='p-6'>
{/* 图标和标题 */} <div className='mb-4 flex items-start gap-4'>
<div className="flex items-start gap-4 mb-4"> <div className='flex-shrink-0'>
<div className="flex-shrink-0"> <AlertTriangle className='h-8 w-8 text-red-500' />
<AlertTriangle className="w-8 h-8 text-red-500" />
</div> </div>
<div className="flex-1"> <div className='flex-1'>
<h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-2"> <h3 className='mb-2 text-lg font-semibold text-gray-900 dark:text-gray-100'>
</h3> </h3>
<p className="text-sm text-gray-600 dark:text-gray-400"> <p className='text-sm text-gray-600 dark:text-gray-400'>
</p> </p>
</div> </div>
</div> </div>
{/* 按钮组 */} <div className='mt-6 flex gap-3'>
<div className="flex gap-3 mt-6">
<button <button
onClick={() => setShowConfirmDialog(false)} onClick={() => setShowConfirmDialog(false)}
className="flex-1 px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors" className='flex-1 rounded-lg bg-gray-100 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600'
> >
</button> </button>
<button <button
onClick={handleClearConfirm} onClick={handleClearConfirm}
className="flex-1 px-4 py-2 text-sm font-medium text-white bg-red-600 hover:bg-red-700 rounded-lg transition-colors" className='flex-1 rounded-lg bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700'
> >
</button> </button>
@@ -293,7 +286,8 @@ export default function ContinueWatching({ className }: ContinueWatchingProps) {
document.body document.body
)} )}
{showPlayRecordsPanel && createPortal( {showPlayRecordsPanel &&
createPortal(
<PlayRecordsPanel <PlayRecordsPanel
isOpen={showPlayRecordsPanel} isOpen={showPlayRecordsPanel}
onClose={() => setShowPlayRecordsPanel(false)} onClose={() => setShowPlayRecordsPanel(false)}
+36
View File
@@ -716,6 +716,42 @@ export async function getAllPlayRecords(): Promise<Record<string, PlayRecord>> {
} }
} }
export function getCachedPlayRecordsSnapshot(): Record<string, PlayRecord> {
if (typeof window === 'undefined') {
return {};
}
if (STORAGE_TYPE !== 'localstorage') {
const cachedRecords = cacheManager.getCachedPlayRecords();
if (cachedRecords) {
return cachedRecords;
}
try {
const username = getAuthInfoFromBrowserCookie()?.username;
if (!username) return {};
const raw = localStorage.getItem(`${CACHE_PREFIX}${username}`);
if (!raw) return {};
const userCache = JSON.parse(raw) as UserCacheStore;
return userCache.playRecords?.data || {};
} catch (err) {
console.error('读取用户播放记录快照失败:', err);
return {};
}
}
try {
const raw = localStorage.getItem(PLAY_RECORDS_KEY);
if (!raw) return {};
return JSON.parse(raw) as Record<string, PlayRecord>;
} catch (err) {
console.error('读取本地播放记录快照失败:', err);
return {};
}
}
/** /**
* 保存播放记录。 * 保存播放记录。
* 数据库存储模式下使用乐观更新:先更新缓存(立即生效),再异步同步到数据库。 * 数据库存储模式下使用乐观更新:先更新缓存(立即生效),再异步同步到数据库。