Files
monkey-ai-web/src/pages/ExperienceCenter/components/AICreation/Video/VideoPreviewPanel.jsx
T

912 lines
28 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import {
Wallet as ActionWallet,
Play as ActionPlay,
HelpCircle as ActionHelpCircle,
X as ActionX,
Download as ActionDownload,
Share2 as ActionShare2,
RotateCcw as ActionRotateCcw,
Square as ActionSquare,
} from '@/components/common/icons/ActionIcons';
import { writeClipboardText } from '../../../../../helpers/clipboard';
import React, { useState, useEffect } from 'react';
import {
Card,
Button,
Progress,
Empty,
Space,
Typography,
Spin,
Tooltip,
} from '@/components/ui';
import { Film, Loader2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { showError, showSuccess } from '../../../../../helpers';
import { useNavigate } from 'react-router-dom';
import { formatQuoteAmount } from '../../../../../hooks/creation/useCreationQuote';
import {
canCancelVideoTask,
canRegenerateVideoTask,
getVideoURLFromDetail,
normalizeVideoTaskStatus,
} from '../../../../../helpers/videoTask';
import './VideoPreviewPanel.css';
const { Title, Text, Paragraph } = Typography;
// 估价 budget_source → 预算层级名(i18n key);org_budget 实际值为 org_budget:<subject_type>
const BUDGET_SOURCE_LABELS = {
org_budget: '部门 / 项目预算',
token: '令牌额度',
org_member: '成员额度',
org_gift: '企业赠送额度',
org: '企业额度',
membership: '会员额度',
gift: '赠送余额',
user: '账户余额',
};
const budgetSourceLabel = (source) =>
BUDGET_SOURCE_LABELS[String(source || '').split(':')[0]] || '';
const VideoPreviewPanel = ({
formData,
generating,
currentTask,
onGenerate,
onCancel,
selectedModel,
selectedTaskForPlay, // 新增:从任务列表选择的任务
onRegenerate, // 新增:再生成回调
onClearSelectedTask, // 新增:清除选中任务的回调(关闭视频播放)
submitBlock = '', // 不能提交的原因(为空表示可提交)
submitting = false,
quote = null,
quoteLoading = false,
quoteFailed = false,
estSeconds = 0,
}) => {
const { t } = useTranslation();
const navigate = useNavigate();
const [windowWidth, setWindowWidth] = useState(window.innerWidth);
// 监听窗口大小变化
useEffect(() => {
const handleResize = () => {
setWindowWidth(window.innerWidth);
};
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
// 根据屏幕宽度获取响应式配置
const getResponsiveConfig = () => {
if (windowWidth > 1600) {
return {
minHeight: '400px',
padding: '40px',
videoMaxHeight: '600px',
buttonSize: 'large',
titleSize: 4,
iconSize: 64,
progressWidth: 120,
};
}
if (windowWidth > 1280) {
return {
minHeight: '350px',
padding: '32px',
videoMaxHeight: '500px',
buttonSize: 'default',
titleSize: 5,
iconSize: 56,
progressWidth: 100,
};
}
if (windowWidth > 1024) {
return {
minHeight: '300px',
padding: '24px',
videoMaxHeight: '400px',
buttonSize: 'default',
titleSize: 5,
iconSize: 48,
progressWidth: 90,
};
}
// 小屏幕
return {
minHeight: '250px',
padding: '16px',
videoMaxHeight: '350px',
buttonSize: 'small',
titleSize: 6,
iconSize: 40,
progressWidth: 80,
};
};
const config = getResponsiveConfig();
// 处理下载
const handleDownload = () => {
const task = selectedTaskForPlay || currentTask;
const videoUrl = getVideoURLFromDetail(task);
if (videoUrl) {
const link = document.createElement('a');
link.href = videoUrl;
link.download = `video_${task.task_id || 'download'}.mp4`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
};
// 处理分享
const handleShare = async () => {
const task = selectedTaskForPlay || currentTask;
const videoUrl = getVideoURLFromDetail(task);
if (videoUrl) {
if (navigator.share) {
try {
await navigator.share({
title: t('视频分享'),
text: task.prompt || t('AI生成的视频'),
url: videoUrl,
});
} catch (err) {
// 用户取消分享或分享失败
copyToClipboard(videoUrl);
}
} else {
// 不支持分享API,复制链接
copyToClipboard(videoUrl);
}
}
};
// 复制到剪贴板
const copyToClipboard = (text) => {
writeClipboardText(text)
.then(() => showSuccess(t('链接已复制')))
.catch(() => showError(t('复制失败,请手动复制')));
};
// 处理生成视频(同时关闭当前播放的视频)
const handleGenerate = () => {
// 先清除选中的任务,关闭视频播放窗口
if (onClearSelectedTask) {
onClearSelectedTask();
}
// 然后开始生成
if (onGenerate) {
onGenerate();
}
};
// 处理关闭视频播放窗口
const handleCloseVideo = () => {
if (onClearSelectedTask) {
onClearSelectedTask();
}
};
// 处理重新生成
const handleRegenerate = () => {
const task = selectedTaskForPlay || currentTask;
if (onRegenerate && task) {
onRegenerate(task);
} else {
// 如果没有提供 onRegenerate 回调,则直接调用 onGenerate
onGenerate();
}
};
// 判断按钮是否禁用(原因由 useVideoGeneration 按 schema 计算)
const isButtonDisabled = Boolean(submitBlock);
// 余额 / 预算不足:按钮变为"去充值"(估价失败时不阻止提交)
const needTopUp = !isButtonDisabled && quote?.balance_enough === false;
// 估价文案:"预计 ¥x · 约 N 秒 · 失败自动退还"
const renderQuoteText = () => {
const parts = [];
const item = quote?.items?.[0];
const amount =
item && !item.error
? formatQuoteAmount(item.display_amount, item.currency)
: '';
if (quoteFailed || (quote && !amount)) {
parts.push(t('价格以实际扣费为准'));
} else if (amount) {
parts.push(
item.approximate
? t('预计约 {{amount}}', { amount })
: t('预计 {{amount}}', { amount }),
);
} else if (quoteLoading) {
parts.push(t('正在估价...'));
}
if (estSeconds > 0) parts.push(t('约 {{n}} 秒', { n: estSeconds }));
if (parts.length === 0) return null;
parts.push(t('失败自动退还'));
return parts.join(' · ');
};
// 渲染顶部操作栏(始终显示)
const renderTopBar = () => {
// 优先显示从任务列表选择的任务
const displayTask = selectedTaskForPlay || currentTask;
const normalizedStatus = normalizeVideoTaskStatus(displayTask?.status);
const isCompleted = normalizedStatus === 'success';
// 检查是否有视频URL
let _hasVideo = false;
if (displayTask) {
const videoUrl = getVideoURLFromDetail(displayTask);
_hasVideo = isCompleted && !!videoUrl;
}
return (
<div
style={{
padding: windowWidth > 768 ? '16px 20px' : '12px 16px',
display: 'flex',
alignItems: 'center',
gap: '12px',
backgroundColor: 'var(--ui-color-bg-1)',
borderBottom: '1px solid var(--ui-color-border)',
flexShrink: 0,
}}
>
{needTopUp ? (
<Button
type='warning'
theme='solid'
size={windowWidth > 768 ? 'default' : 'small'}
icon={<ActionWallet size={16} />}
onClick={() => navigate('/console/topup')}
style={{ fontWeight: 600 }}
>
{t('去充值')}
</Button>
) : (
<Button
type='primary'
theme='solid'
size={windowWidth > 768 ? 'default' : 'small'}
icon={<ActionPlay size={16} fill='currentColor' />}
onClick={isButtonDisabled ? undefined : handleGenerate}
disabled={isButtonDisabled || submitting}
loading={submitting}
style={{
fontWeight: 600,
background:
isButtonDisabled || submitting
? undefined
: 'linear-gradient(135deg, var(--ui-color-primary) 0%, var(--ui-color-primary-active, var(--ui-color-primary)) 100%)',
border: 'none',
}}
>
{submitting
? t('提交中...')
: windowWidth > 768
? t('开始生成')
: t('生成')}
</Button>
)}
{/* 估价 / 余额不足说明 */}
{!isButtonDisabled && (
<Text
type={needTopUp ? 'warning' : 'tertiary'}
style={{
fontSize: '12px',
fontVariantNumeric: 'tabular-nums',
minWidth: 0,
}}
aria-live='polite'
>
{needTopUp
? budgetSourceLabel(quote?.budget_source)
? t('{{source}}不足,请充值后再生成', {
source: t(budgetSourceLabel(quote.budget_source)),
})
: t('余额或预算不足,请充值后再生成')
: renderQuoteText()}
</Text>
)}
{/* 禁用提示 */}
{isButtonDisabled && !submitting && (
<Text type='tertiary' style={{ fontSize: '12px' }} role='note'>
{submitBlock}
</Text>
)}
{/* 生成中状态提示 */}
{generating && displayTask && (
<Text
type='tertiary'
style={{
fontSize: '12px',
display: 'flex',
alignItems: 'center',
gap: '4px',
}}
>
<Loader2 size={12} className='animate-spin' />
{displayTask.progress || '0%'}
</Text>
)}
<div style={{ flex: 1 }} />
<Tooltip
content={
<div style={{ padding: '12px', maxWidth: '300px' }}>
<div
style={{
fontWeight: 600,
marginBottom: '8px',
fontSize: '14px',
}}
>
{t('使用提示')}
</div>
<div style={{ fontSize: '13px', lineHeight: '1.8' }}>
• {t('详细的提示词能获得更好的效果')}
<br />• {t('建议使用高质量的首帧图片')}
<br />• {t('视频生成可能需要 1-3 分钟')}
<br />• {t('可在任务队列中查看历史记录')}
</div>
</div>
}
position='bottomRight'
trigger='hover'
showArrow={true}
>
<Button
icon={<ActionHelpCircle size={18} />}
type='tertiary'
size={windowWidth > 768 ? 'default' : 'small'}
/>
</Tooltip>
</div>
);
};
// 渲染预览区域
const renderPreview = () => {
// 优先显示从任务列表选择的任务
const displayTask = selectedTaskForPlay || currentTask;
// 统一转换状态为小写进行比较
const normalizedStatus = normalizeVideoTaskStatus(displayTask?.status);
// 生成完成 - 优先检查,包括从任务列表点击播放的情况
const isCompleted = normalizedStatus === 'success';
const videoUrl = getVideoURLFromDetail(displayTask);
const taskData = displayTask?.request || {};
// 如果是已完成的任务且有视频URL,直接显示(无论是从任务列表还是当前生成)
if (isCompleted && videoUrl) {
return (
<div style={{ textAlign: 'center', padding: config.padding }}>
{/* 视频播放器容器 */}
<div
style={{
position: 'relative',
marginBottom: windowWidth > 768 ? '24px' : '16px',
}}
>
{/* 关闭按钮 */}
<Button
icon={<ActionX size={16} />}
type='tertiary'
theme='borderless'
size='small'
onClick={handleCloseVideo}
style={{
position: 'absolute',
top: '8px',
right: '8px',
zIndex: 10,
backgroundColor: 'rgba(0, 0, 0, 0.5)',
color: 'white',
borderRadius: '50%',
}}
/>
{/* 视频播放器 */}
<video
controls
style={{
width: '100%',
maxHeight: config.videoMaxHeight,
borderRadius: '8px',
}}
src={videoUrl}
/>
</div>
{/* 操作按钮 */}
<Space wrap={windowWidth <= 768}>
<Button
type='primary'
size={config.buttonSize}
icon={<ActionDownload size={16} />}
onClick={handleDownload}
>
{windowWidth > 768 ? t('下载视频') : t('下载')}
</Button>
<Button
size={config.buttonSize}
icon={<ActionShare2 size={16} />}
onClick={handleShare}
>
{t('分享')}
</Button>
{canRegenerateVideoTask(displayTask) && (
<Button
size={config.buttonSize}
icon={<ActionRotateCcw size={16} />}
onClick={handleRegenerate}
>
{windowWidth > 768 ? t('再生成') : t('重新')}
</Button>
)}
</Space>
{/* 视频信息 */}
<div
style={{
marginTop: windowWidth > 768 ? '24px' : '16px',
padding: windowWidth > 768 ? '16px' : '12px',
backgroundColor: 'var(--ui-color-fill-0)',
borderRadius: '8px',
textAlign: 'left',
}}
>
<Space vertical spacing='small' style={{ width: '100%' }}>
{(taskData.prompt || displayTask.prompt) && (
<div>
<Text
strong
style={{ fontSize: windowWidth > 768 ? '14px' : '12px' }}
>
{t('提示词')}:
</Text>
<Paragraph
copyable
style={{
fontSize: windowWidth > 768 ? '13px' : '11px',
marginTop: '4px',
}}
>
{taskData.prompt || displayTask.prompt}
</Paragraph>
</div>
)}
{taskData.negative_prompt && (
<div>
<Text
strong
style={{ fontSize: windowWidth > 768 ? '14px' : '12px' }}
>
{t('反向提示词')}:
</Text>
<Paragraph
copyable
style={{
fontSize: windowWidth > 768 ? '13px' : '11px',
marginTop: '4px',
}}
>
{taskData.negative_prompt}
</Paragraph>
</div>
)}
<div>
<Text
type='tertiary'
style={{ fontSize: windowWidth > 768 ? '12px' : '10px' }}
>
{t('模型')}:{' '}
{taskData.model ||
displayTask.properties?.upstream_model_name ||
displayTask.properties?.origin_model_name ||
(typeof selectedModel === 'object'
? selectedModel?.model_name
: selectedModel)}{' '}
| {t('时长')}:{' '}
{taskData.duration || displayTask.properties?.duration || '-'}
s | {t('分辨率')}:{' '}
{taskData.resolution ||
displayTask.properties?.resolution ||
'-'}
</Text>
</div>
</Space>
</div>
</div>
);
}
// 生成中(只在没有 selectedTaskForPlay 时显示)
if (generating && displayTask && !selectedTaskForPlay) {
return (
<div
style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
minHeight: config.minHeight,
padding: config.padding,
}}
>
<Spin
size={windowWidth > 768 ? 'large' : 'default'}
indicator={<Loader2 className='animate-spin' size={32} />}
/>
<Title
heading={config.titleSize}
style={{ marginTop: '24px', marginBottom: '8px' }}
>
{t('视频生成中...')}
</Title>
<Text
type='tertiary'
style={{ fontSize: windowWidth > 768 ? '14px' : '12px' }}
>
{normalizedStatus === 'queued' && t('等待处理')}
{normalizedStatus === 'in_progress' && t('正在生成')}
</Text>
{/* 进度条 */}
{displayTask.progress !== undefined &&
(() => {
// 解析进度值,处理字符串格式(如 "50%")
let percentValue = 0;
if (typeof displayTask.progress === 'string') {
percentValue =
parseInt(displayTask.progress.replace('%', '')) || 0;
} else if (typeof displayTask.progress === 'number') {
percentValue = displayTask.progress;
}
return (
<Progress
percent={percentValue}
showInfo
type='circle'
style={{ marginTop: '24px' }}
width={config.progressWidth}
/>
);
})()}
{/* 任务信息 */}
<div style={{ marginTop: '24px', textAlign: 'center' }}>
<Space vertical spacing='small'>
<Text
type='tertiary'
style={{ fontSize: windowWidth > 768 ? '13px' : '11px' }}
>
{t('任务ID')}: {displayTask.task_id}
</Text>
<Text
type='tertiary'
style={{ fontSize: windowWidth > 768 ? '13px' : '11px' }}
>
{t('模型')}:{' '}
{typeof selectedModel === 'object'
? selectedModel?.model_name
: selectedModel}
</Text>
{displayTask.estimated_time && (
<Text
type='tertiary'
style={{ fontSize: windowWidth > 768 ? '13px' : '11px' }}
>
{t('预计时间')}: {displayTask.estimated_time}s
</Text>
)}
</Space>
</div>
{canCancelVideoTask(displayTask) && (
<Button
type='danger'
size={config.buttonSize}
icon={<ActionSquare size={16} fill='currentColor' />}
onClick={onCancel}
style={{ marginTop: '32px' }}
>
{t('取消生成')}
</Button>
)}
</div>
);
}
// 生成失败 - 检查 'failed' 或 'failure' 状态
const isFailed =
normalizedStatus === 'failed' || normalizedStatus === 'failure';
if (isFailed) {
return (
<div
style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
minHeight: config.minHeight,
padding: config.padding,
}}
>
<Empty
title={t('生成失败')}
description={
displayTask.fail_reason || displayTask.error || t('未知错误')
}
/>
{canRegenerateVideoTask(displayTask) && (
<Button
type='primary'
size={config.buttonSize}
icon={<ActionRotateCcw size={16} />}
onClick={handleRegenerate}
style={{ marginTop: '24px' }}
>
{t('重新生成')}
</Button>
)}
</div>
);
}
// 初始状态或图生视频预览
if (formData.mode === 'image2video' && formData.image) {
return (
<div style={{ textAlign: 'center', padding: config.padding }}>
<Title
heading={config.titleSize + 1}
style={{ marginBottom: '16px' }}
>
{t('首帧预览')}
</Title>
<img
src={formData.imagePreview || formData.image}
alt='Preview'
style={{
maxWidth: '100%',
maxHeight: windowWidth > 1024 ? '500px' : '350px',
borderRadius: '8px',
}}
/>
</div>
);
}
// 默认空状态 - 纯CSS电影感动画背景(无网络资源消耗)
return (
<div
style={{
display: 'flex',
flexDirection: 'column',
minHeight: config.minHeight,
height: '100%',
position: 'relative',
borderRadius: '12px',
overflow: 'hidden',
margin: '16px',
background:
'linear-gradient(135deg, #0a0a0a 0%, #1a1a2e 50%, #16213e 100%)',
}}
>
{/* CSS动画背景 - 流动光效(增强版) */}
<div
style={{
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
overflow: 'hidden',
pointerEvents: 'none',
}}
>
{/* 动态光晕1 - 紫色 */}
<div
className='video-preview-glow1'
style={{
position: 'absolute',
width: '60%',
height: '60%',
top: '10%',
left: '5%',
background:
'radial-gradient(ellipse at center, color-mix(in srgb, var(--brand-gradient-via) 35%, transparent) 0%, color-mix(in srgb, var(--brand-gradient-via) 10%, transparent) 40%, transparent 70%)',
borderRadius: '50%',
filter: 'blur(40px)',
}}
/>
{/* 动态光晕2 - 橙红色 */}
<div
className='video-preview-glow2'
style={{
position: 'absolute',
width: '50%',
height: '50%',
bottom: '10%',
right: '5%',
background:
'radial-gradient(ellipse at center, rgba(251, 146, 60, 0.3) 0%, rgba(251, 146, 60, 0.1) 40%, transparent 70%)',
borderRadius: '50%',
filter: 'blur(40px)',
}}
/>
{/* 动态光晕3 - 金色中心 */}
<div
className='video-preview-glow3'
style={{
position: 'absolute',
width: '40%',
height: '40%',
top: '30%',
left: '30%',
background:
'radial-gradient(ellipse at center, rgba(251, 191, 36, 0.25) 0%, transparent 60%)',
borderRadius: '50%',
filter: 'blur(30px)',
}}
/>
</div>
{/* 电影宽银幕效果 - 上下黑边 */}
<div
style={{
position: 'absolute',
top: 0,
left: 0,
right: 0,
height: '6%',
background:
'linear-gradient(180deg, rgba(0,0,0,0.95) 0%, transparent 100%)',
zIndex: 2,
}}
/>
<div
style={{
position: 'absolute',
bottom: 0,
left: 0,
right: 0,
height: '6%',
background:
'linear-gradient(0deg, rgba(0,0,0,0.95) 0%, transparent 100%)',
zIndex: 2,
}}
/>
{/* 中央内容区域 */}
<div
style={{
flex: 1,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
padding: config.padding,
color: 'white',
position: 'relative',
zIndex: 3,
}}
>
<div
style={{
backgroundColor: 'rgba(255, 255, 255, 0.1)',
borderRadius: '50%',
padding: windowWidth > 1024 ? '32px' : '24px',
marginBottom: windowWidth > 768 ? '32px' : '24px',
border: '1px solid rgba(255, 255, 255, 0.2)',
boxShadow: '0 8px 32px rgba(0, 0, 0, 0.3)',
transition: 'transform 0.3s ease',
}}
onMouseEnter={(e) => {
e.currentTarget.style.transform = 'scale(1.05)';
}}
onMouseLeave={(e) => {
e.currentTarget.style.transform = 'scale(1)';
}}
>
<Film
size={config.iconSize}
style={{
color: 'rgba(255, 220, 180, 0.9)',
filter: 'drop-shadow(0 2px 12px rgba(255,200,150,0.4))',
}}
/>
</div>
<Title
heading={config.titleSize}
style={{
marginBottom: '12px',
color: 'rgba(255, 250, 245, 0.95)',
fontWeight: 700,
textShadow: '0 4px 20px rgba(0, 0, 0, 0.6)',
letterSpacing: '3px',
}}
>
{t('AI 视频生成')}
</Title>
<Text
style={{
marginBottom: windowWidth > 768 ? '24px' : '16px',
textAlign: 'center',
fontSize: windowWidth > 768 ? '16px' : '14px',
padding: '0 16px',
color: 'rgba(255, 255, 255, 0.7)',
maxWidth: '500px',
lineHeight: '1.8',
textShadow: '0 2px 8px rgba(0, 0, 0, 0.5)',
}}
>
{formData.mode === 'text2video'
? t('输入提示词,让 AI 为你创造精彩视频')
: t('上传图片并输入提示词,生成动态视频')}
</Text>
</div>
</div>
);
};
return (
<Card
style={{ height: '100%', display: 'flex', flexDirection: 'column' }}
styles={{
body: {
flex: 1,
display: 'flex',
flexDirection: 'column',
overflow: 'hidden',
padding: 0,
},
}}
>
{/* 始终显示的顶部操作栏 */}
{renderTopBar()}
{/* 内容区域 */}
<div style={{ flex: 1, overflow: 'auto' }}>{renderPreview()}</div>
</Card>
);
};
export default VideoPreviewPanel;