增加评论开关,尝试修复循环依赖

This commit is contained in:
mtvpls
2025-12-03 18:20:34 +08:00
parent 567ee54c67
commit 4e05c7bcaa
11 changed files with 416 additions and 194 deletions
+115
View File
@@ -269,6 +269,7 @@ interface SiteConfig {
FluidSearch: boolean;
DanmakuApiBase: string;
DanmakuApiToken: string;
EnableComments: boolean;
}
// 视频源数据类型
@@ -3384,6 +3385,7 @@ const ConfigFileComponent = ({ config, refreshConfig }: { config: AdminConfig |
const SiteConfigComponent = ({ config, refreshConfig }: { config: AdminConfig | null; refreshConfig: () => Promise<void> }) => {
const { alertModal, showAlert, hideAlert } = useAlertModal();
const { isLoading, withLoading } = useLoadingState();
const [showEnableCommentsModal, setShowEnableCommentsModal] = useState(false);
const [siteSettings, setSiteSettings] = useState<SiteConfig>({
SiteName: '',
Announcement: '',
@@ -3397,6 +3399,7 @@ const SiteConfigComponent = ({ config, refreshConfig }: { config: AdminConfig |
FluidSearch: true,
DanmakuApiBase: 'http://localhost:9321',
DanmakuApiToken: '87654321',
EnableComments: false,
});
// 豆瓣数据源相关状态
@@ -3461,6 +3464,7 @@ const SiteConfigComponent = ({ config, refreshConfig }: { config: AdminConfig |
FluidSearch: config.SiteConfig.FluidSearch || true,
DanmakuApiBase: config.SiteConfig.DanmakuApiBase || 'http://localhost:9321',
DanmakuApiToken: config.SiteConfig.DanmakuApiToken || '87654321',
EnableComments: config.SiteConfig.EnableComments || false,
});
}
}, [config]);
@@ -3516,6 +3520,29 @@ const SiteConfigComponent = ({ config, refreshConfig }: { config: AdminConfig |
}));
};
// 处理评论开关变化
const handleCommentsToggle = (checked: boolean) => {
if (checked) {
// 如果要开启评论,弹出确认框
setShowEnableCommentsModal(true);
} else {
// 直接关闭评论
setSiteSettings((prev) => ({
...prev,
EnableComments: false,
}));
}
};
// 确认开启评论
const handleConfirmEnableComments = () => {
setSiteSettings((prev) => ({
...prev,
EnableComments: true,
}));
setShowEnableCommentsModal(false);
};
// 保存站点配置
const handleSave = async () => {
await withLoading('saveSiteConfig', async () => {
@@ -3964,6 +3991,40 @@ const SiteConfigComponent = ({ config, refreshConfig }: { config: AdminConfig |
</div>
</div>
{/* 评论功能配置 */}
<div className='space-y-4 pt-4 border-t border-gray-200 dark:border-gray-700'>
<h3 className='text-sm font-semibold text-gray-900 dark:text-gray-100'>
</h3>
{/* 开启评论 */}
<div>
<div className='flex items-center justify-between'>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
</label>
<button
type='button'
onClick={() => handleCommentsToggle(!siteSettings.EnableComments)}
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 ${siteSettings.EnableComments
? buttonStyles.toggleOn
: buttonStyles.toggleOff
}`}
>
<span
className={`inline-block h-4 w-4 transform rounded-full ${buttonStyles.toggleThumb} transition-transform ${siteSettings.EnableComments
? buttonStyles.toggleThumbOn
: buttonStyles.toggleThumbOff
}`}
/>
</button>
</div>
<p className='mt-1 text-xs text-gray-500 dark:text-gray-400'>
</p>
</div>
</div>
{/* 操作按钮 */}
<div className='flex justify-end'>
<button
@@ -3988,6 +4049,60 @@ const SiteConfigComponent = ({ config, refreshConfig }: { config: AdminConfig |
timer={alertModal.timer}
showConfirm={alertModal.showConfirm}
/>
{/* 开启评论确认弹窗 */}
{showEnableCommentsModal && createPortal(
<div className='fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4' onClick={() => setShowEnableCommentsModal(false)}>
<div className='bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full' onClick={(e) => e.stopPropagation()}>
<div className='p-6'>
<div className='flex items-center justify-between mb-6'>
<h3 className='text-xl font-semibold text-gray-900 dark:text-gray-100'>
</h3>
<button
onClick={() => setShowEnableCommentsModal(false)}
className='text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors'
>
<svg className='w-6 h-6' fill='none' stroke='currentColor' viewBox='0 0 24 24'>
<path strokeLinecap='round' strokeLinejoin='round' strokeWidth={2} d='M6 18L18 6M6 6l12 12' />
</svg>
</button>
</div>
<div className='mb-6'>
<div className='bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4'>
<div className='flex items-center space-x-2 mb-2'>
<AlertTriangle className='w-5 h-5 text-yellow-600 dark:text-yellow-400' />
<span className='text-sm font-medium text-yellow-800 dark:text-yellow-300'>
</span>
</div>
<p className='text-sm text-yellow-700 dark:text-yellow-400'>
</p>
</div>
</div>
{/* 操作按钮 */}
<div className='flex justify-end space-x-3'>
<button
onClick={() => setShowEnableCommentsModal(false)}
className={`px-6 py-2.5 text-sm font-medium ${buttonStyles.secondary}`}
>
</button>
<button
onClick={handleConfirmEnableComments}
className={`px-6 py-2.5 text-sm font-medium ${buttonStyles.primary}`}
>
</button>
</div>
</div>
</div>
</div>,
document.body
)}
</div>
);
};
+5 -1
View File
@@ -41,6 +41,7 @@ export async function POST(request: NextRequest) {
FluidSearch,
DanmakuApiBase,
DanmakuApiToken,
EnableComments,
} = body as {
SiteName: string;
Announcement: string;
@@ -54,6 +55,7 @@ export async function POST(request: NextRequest) {
FluidSearch: boolean;
DanmakuApiBase: string;
DanmakuApiToken: string;
EnableComments: boolean;
};
// 参数校验
@@ -69,7 +71,8 @@ export async function POST(request: NextRequest) {
typeof DisableYellowFilter !== 'boolean' ||
typeof FluidSearch !== 'boolean' ||
typeof DanmakuApiBase !== 'string' ||
typeof DanmakuApiToken !== 'string'
typeof DanmakuApiToken !== 'string' ||
typeof EnableComments !== 'boolean'
) {
return NextResponse.json({ error: '参数格式错误' }, { status: 400 });
}
@@ -101,6 +104,7 @@ export async function POST(request: NextRequest) {
FluidSearch,
DanmakuApiBase,
DanmakuApiToken,
EnableComments,
};
// 写入数据库
+3
View File
@@ -54,6 +54,7 @@ export default async function RootLayout({
let disableYellowFilter =
process.env.NEXT_PUBLIC_DISABLE_YELLOW_FILTER === 'true';
let fluidSearch = process.env.NEXT_PUBLIC_FLUID_SEARCH !== 'false';
let enableComments = false;
let customCategories = [] as {
name: string;
type: 'movie' | 'tv';
@@ -77,6 +78,7 @@ export default async function RootLayout({
query: category.query,
}));
fluidSearch = config.SiteConfig.FluidSearch;
enableComments = config.SiteConfig.EnableComments;
}
// 将运行时配置注入到全局 window 对象,供客户端在运行时读取
@@ -89,6 +91,7 @@ export default async function RootLayout({
DISABLE_YELLOW_FILTER: disableYellowFilter,
CUSTOM_CATEGORIES: customCategories,
FLUID_SEARCH: fluidSearch,
EnableComments: enableComments,
};
return (
+107 -86
View File
@@ -41,6 +41,7 @@ import { getVideoResolutionFromM3u8, processImageUrl } from '@/lib/utils';
import EpisodeSelector from '@/components/EpisodeSelector';
import PageLayout from '@/components/PageLayout';
import DoubanComments from '@/components/DoubanComments';
import { useEnableComments } from '@/hooks/useEnableComments';
// 扩展 HTMLVideoElement 类型以支持 hls 属性
declare global {
@@ -60,6 +61,7 @@ interface WakeLockSentinel {
function PlayPageClient() {
const router = useRouter();
const searchParams = useSearchParams();
const enableComments = useEnableComments();
// -----------------------------------------------------------------------------
// 状态变量(State
@@ -597,13 +599,17 @@ function PlayPageClient() {
try {
// 在销毁前从弹幕插件读取最新配置并保存
if (danmakuPluginRef.current?.option && artPlayerRef.current.storage) {
// 获取当前弹幕设置的快照,避免循环引用
const currentDanmakuSettings = danmakuSettingsRef.current;
const danmakuPluginOption = danmakuPluginRef.current.option;
const currentSettings = {
...danmakuSettingsRef.current,
opacity: danmakuPluginRef.current.option.opacity || danmakuSettingsRef.current.opacity,
fontSize: danmakuPluginRef.current.option.fontSize || danmakuSettingsRef.current.fontSize,
speed: danmakuPluginRef.current.option.speed || danmakuSettingsRef.current.speed,
marginTop: (danmakuPluginRef.current.option.margin && danmakuPluginRef.current.option.margin[0]) ?? danmakuSettingsRef.current.marginTop,
marginBottom: (danmakuPluginRef.current.option.margin && danmakuPluginRef.current.option.margin[1]) ?? danmakuSettingsRef.current.marginBottom,
...currentDanmakuSettings,
opacity: danmakuPluginOption.opacity || currentDanmakuSettings.opacity,
fontSize: danmakuPluginOption.fontSize || currentDanmakuSettings.fontSize,
speed: danmakuPluginOption.speed || currentDanmakuSettings.speed,
marginTop: (danmakuPluginOption.margin && danmakuPluginOption.margin[0]) ?? currentDanmakuSettings.marginTop,
marginBottom: (danmakuPluginOption.margin && danmakuPluginOption.margin[1]) ?? currentDanmakuSettings.marginBottom,
};
// 保存到 localStorage 和 art.storage
@@ -901,63 +907,71 @@ function PlayPageClient() {
setSkipConfig(newConfig);
if (!newConfig.enable && !newConfig.intro_time && !newConfig.outro_time) {
await deleteSkipConfig(currentSourceRef.current, currentIdRef.current);
artPlayerRef.current.setting.update({
name: '跳过片头片尾',
html: '跳过片头片尾',
switch: skipConfigRef.current.enable,
onSwitch: function (item: any) {
const newConfig = {
...skipConfigRef.current,
enable: !item.switch,
};
handleSkipConfigChange(newConfig);
return !item.switch;
},
});
artPlayerRef.current.setting.update({
name: '设置片头',
html: '设置片头',
icon: '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="5" cy="12" r="2" fill="#ffffff"/><path d="M9 12L17 12" stroke="#ffffff" stroke-width="2"/><path d="M17 6L17 18" stroke="#ffffff" stroke-width="2"/></svg>',
tooltip:
skipConfigRef.current.intro_time === 0
? '设置片头时间'
: `${formatTime(skipConfigRef.current.intro_time)}`,
onClick: function () {
const currentTime = artPlayerRef.current?.currentTime || 0;
if (currentTime > 0) {
const newConfig = {
...skipConfigRef.current,
intro_time: currentTime,
};
handleSkipConfigChange(newConfig);
return `${formatTime(currentTime)}`;
}
},
});
artPlayerRef.current.setting.update({
name: '设置片尾',
html: '设置片尾',
icon: '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M7 6L7 18" stroke="#ffffff" stroke-width="2"/><path d="M7 12L15 12" stroke="#ffffff" stroke-width="2"/><circle cx="19" cy="12" r="2" fill="#ffffff"/></svg>',
tooltip:
skipConfigRef.current.outro_time >= 0
? '设置片尾时间'
: `-${formatTime(-skipConfigRef.current.outro_time)}`,
onClick: function () {
const outroTime =
-(
artPlayerRef.current?.duration -
artPlayerRef.current?.currentTime
) || 0;
if (outroTime < 0) {
const newConfig = {
...skipConfigRef.current,
outro_time: outroTime,
};
handleSkipConfigChange(newConfig);
return `-${formatTime(-outroTime)}`;
}
},
});
// 安全地更新播放器设置,仅在播放器存在时执行
if (artPlayerRef.current && artPlayerRef.current.setting) {
try {
artPlayerRef.current.setting.update({
name: '跳过片头片尾',
html: '跳过片头片尾',
switch: skipConfigRef.current.enable,
onSwitch: function (item: any) {
const newConfig = {
...skipConfigRef.current,
enable: !item.switch,
};
handleSkipConfigChange(newConfig);
return !item.switch;
},
});
artPlayerRef.current.setting.update({
name: '设置片头',
html: '设置片头',
icon: '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="5" cy="12" r="2" fill="#ffffff"/><path d="M9 12L17 12" stroke="#ffffff" stroke-width="2"/><path d="M17 6L17 18" stroke="#ffffff" stroke-width="2"/></svg>',
tooltip:
skipConfigRef.current.intro_time === 0
? '设置片头时间'
: `${formatTime(skipConfigRef.current.intro_time)}`,
onClick: function () {
const currentTime = artPlayerRef.current?.currentTime || 0;
if (currentTime > 0) {
const newConfig = {
...skipConfigRef.current,
intro_time: currentTime,
};
handleSkipConfigChange(newConfig);
return `${formatTime(currentTime)}`;
}
},
});
artPlayerRef.current.setting.update({
name: '设置片尾',
html: '设置片尾',
icon: '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M7 6L7 18" stroke="#ffffff" stroke-width="2"/><path d="M7 12L15 12" stroke="#ffffff" stroke-width="2"/><circle cx="19" cy="12" r="2" fill="#ffffff"/></svg>',
tooltip:
skipConfigRef.current.outro_time >= 0
? '设置片尾时间'
: `-${formatTime(-skipConfigRef.current.outro_time)}`,
onClick: function () {
const outroTime =
-(
artPlayerRef.current?.duration -
artPlayerRef.current?.currentTime
) || 0;
if (outroTime < 0) {
const newConfig = {
...skipConfigRef.current,
outro_time: outroTime,
};
handleSkipConfigChange(newConfig);
return `-${formatTime(-outroTime)}`;
}
},
});
} catch (settingErr) {
console.warn('更新播放器设置失败:', settingErr);
}
}
} else {
await saveSkipConfig(
currentSourceRef.current,
@@ -1828,7 +1842,7 @@ function PlayPageClient() {
window.removeEventListener('beforeunload', handleBeforeUnload);
document.removeEventListener('visibilitychange', handleVisibilityChange);
};
}, [currentEpisodeIndex, detail, artPlayerRef.current]);
}, [currentEpisodeIndex, detail]);
// 清理定时器
useEffect(() => {
@@ -2231,15 +2245,20 @@ function PlayPageClient() {
? '设置片头时间'
: `${formatTime(skipConfigRef.current.intro_time)}`,
onClick: function () {
const currentTime = artPlayerRef.current?.currentTime || 0;
if (currentTime > 0) {
const newConfig = {
...skipConfigRef.current,
intro_time: currentTime,
};
handleSkipConfigChange(newConfig);
return `${formatTime(currentTime)}`;
// 安全地获取当前播放时间,避免循环依赖
const player = artPlayerRef.current;
if (player && player.currentTime) {
const currentTime = player.currentTime || 0;
if (currentTime > 0) {
const newConfig = {
...skipConfigRef.current,
intro_time: currentTime,
};
handleSkipConfigChange(newConfig);
return `${formatTime(currentTime)}`;
}
}
return '';
},
},
{
@@ -2251,19 +2270,21 @@ function PlayPageClient() {
? '设置片尾时间'
: `-${formatTime(-skipConfigRef.current.outro_time)}`,
onClick: function () {
const outroTime =
-(
artPlayerRef.current?.duration -
artPlayerRef.current?.currentTime
) || 0;
if (outroTime < 0) {
const newConfig = {
...skipConfigRef.current,
outro_time: outroTime,
};
handleSkipConfigChange(newConfig);
return `-${formatTime(-outroTime)}`;
// 安全地获取播放器时长和当前时间,避免循环依赖
const player = artPlayerRef.current;
if (player && player.duration && player.currentTime) {
const outroTime =
-(player.duration - player.currentTime) || 0;
if (outroTime < 0) {
const newConfig = {
...skipConfigRef.current,
outro_time: outroTime,
};
handleSkipConfigChange(newConfig);
return `-${formatTime(-outroTime)}`;
}
}
return '';
},
},
],
@@ -2496,7 +2517,7 @@ function PlayPageClient() {
console.error('创建播放器失败:', err);
setError('播放器初始化失败');
}
}, [Artplayer, Hls, videoUrl, loading, blockAdEnabled]);
}, [videoUrl, loading, blockAdEnabled, currentEpisodeIndex, detail]);
// 当组件卸载时清理定时器、Wake Lock 和播放器资源
useEffect(() => {
@@ -3283,7 +3304,7 @@ function PlayPageClient() {
</div>
{/* 豆瓣评论区域 */}
{videoDoubanId !== 0 && (
{videoDoubanId !== 0 && enableComments && (
<div className='mt-6 px-4'>
<div className='bg-white/50 dark:bg-gray-800/50 backdrop-blur-sm rounded-xl border border-gray-200/50 dark:border-gray-700/50 overflow-hidden'>
{/* 标题 */}
+13
View File
@@ -1,6 +1,7 @@
'use client';
import { useEffect, useState, useCallback } from 'react';
import { useEnableComments } from '@/hooks/useEnableComments';
interface DoubanComment {
id: string;
@@ -17,6 +18,11 @@ interface DoubanCommentsProps {
doubanId: number;
}
// 获取运行时配置的类型
interface RuntimeConfig {
EnableComments: boolean;
}
export default function DoubanComments({ doubanId }: DoubanCommentsProps) {
const [comments, setComments] = useState<DoubanComment[]>([]);
const [loading, setLoading] = useState(false);
@@ -26,6 +32,13 @@ export default function DoubanComments({ doubanId }: DoubanCommentsProps) {
const [hasStartedLoading, setHasStartedLoading] = useState(false);
const limit = 20;
const enableComments = useEnableComments();
// 如果评论功能被禁用,不显示任何内容
if (!enableComments) {
return null;
}
const fetchComments = useCallback(async (startIndex: number) => {
try {
console.log('正在获取评论,起始位置:', startIndex);
+3
View File
@@ -50,6 +50,9 @@ interface SidebarProps {
declare global {
interface Window {
__sidebarCollapsed?: boolean;
RUNTIME_CONFIG?: {
EnableComments: boolean;
};
}
}
+19
View File
@@ -0,0 +1,19 @@
import { useState, useEffect } from 'react';
interface RuntimeConfig {
EnableComments: boolean;
}
export function useEnableComments(): boolean {
const [enableComments, setEnableComments] = useState(true);
useEffect(() => {
// 在客户端获取运行时配置
if (typeof window !== 'undefined') {
const runtimeConfig = (window as any).RUNTIME_CONFIG as RuntimeConfig;
setEnableComments(runtimeConfig?.EnableComments ?? true);
}
}, []);
return enableComments;
}
+2
View File
@@ -19,6 +19,8 @@ export interface AdminConfig {
// 弹幕配置
DanmakuApiBase: string;
DanmakuApiToken: string;
// 评论功能开关
EnableComments: boolean;
};
UserConfig: {
Users: {
+7
View File
@@ -221,6 +221,8 @@ async function getInitConfig(configFile: string, subConfig: {
// 弹幕配置
DanmakuApiBase: process.env.DANMAKU_API_BASE || 'http://localhost:9321',
DanmakuApiToken: process.env.DANMAKU_API_TOKEN || '87654321',
// 评论功能开关
EnableComments: false,
},
UserConfig: {
Users: [],
@@ -332,6 +334,7 @@ export function configSelfCheck(adminConfig: AdminConfig): AdminConfig {
FluidSearch: true,
DanmakuApiBase: 'http://localhost:9321',
DanmakuApiToken: '87654321',
EnableComments: false,
};
}
// 确保弹幕配置存在
@@ -341,6 +344,10 @@ export function configSelfCheck(adminConfig: AdminConfig): AdminConfig {
if (!adminConfig.SiteConfig.DanmakuApiToken) {
adminConfig.SiteConfig.DanmakuApiToken = '87654321';
}
// 确保评论开关存在
if (adminConfig.SiteConfig.EnableComments === undefined) {
adminConfig.SiteConfig.EnableComments = false;
}
if (!adminConfig.UserConfig) {
adminConfig.UserConfig = { Users: [] };
}