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

484 lines
15 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 React, { useState, useEffect } from 'react';
import {
Table,
Button,
Space,
Tag,
Progress,
Tooltip,
Modal,
Badge,
Select,
} from '@/components/ui';
import {
ChevronUp,
ChevronDown,
RefreshCw,
Download,
Trash2,
Play,
CheckCircle2,
AlertCircle,
Clock,
Loader2,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useIsMobile } from '../../../../../hooks/common/useIsMobile';
import {
canRegenerateVideoTask,
normalizeVideoTaskStatus,
} from '../../../../../helpers/videoTask';
const VideoTaskQueue = ({
visible,
setVisible,
tasks,
onRefresh,
onDelete,
onDownload,
onPlay, // 新增:播放回调
onRegenerate, // 新增:再生成回调
}) => {
const { t } = useTranslation();
// 断点判定必须按「宽度」。本组件此前 20 多处响应式判断写的是 !isCompact,
// 判的是窗口高度——390x844 的手机上 844 > 768 成立,于是整个队列走桌面分支:
// 8 列合计 1190px 塞进 ~340px 容器、按钮全带文字,实际完全用不了。
const isCompact = useIsMobile();
const [selectedTasks, setSelectedTasks] = useState([]);
const [windowHeight, setWindowHeight] = useState(window.innerHeight);
const [pageSize, setPageSize] = useState(5); // 新增:分页大小状态
// 监听窗口高度变化
useEffect(() => {
const handleResize = () => {
setWindowHeight(window.innerHeight);
};
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
// 计算任务队列高度:不超过屏幕高度的20%(五分之一)
// 同时设置最小高度150px,最大高度300px
const getQueueHeight = () => {
const maxHeightPercent = windowHeight * 0.2; // 屏幕高度的20%
// 手机端工具栏本身会换行占掉 ~100px,再按 20%(844px 屏上仅 169px)会让表格只剩
// 不到 70px,连表头带分页都放不下。窄屏改用更宽松的下限。
const minHeight = isCompact ? 300 : 150;
const maxHeight = isCompact ? 420 : 300;
// 在最小和最大值之间取适当的高度
return Math.max(minHeight, Math.min(maxHeightPercent, maxHeight));
};
const queueHeight = getQueueHeight();
// 状态标签映射
const getStatusTag = (status) => {
// 统一转换为小写进行比较
const normalizedStatus = normalizeVideoTaskStatus(status);
const statusMap = {
queued: { color: 'blue', text: t('排队中'), icon: <Clock size={12} /> },
in_progress: {
color: 'cyan',
text: t('生成中'),
icon: <Loader2 size={12} className='animate-spin' />,
},
success: {
color: 'green',
text: t('已完成'),
icon: <CheckCircle2 size={12} />,
},
completed: {
color: 'green',
text: t('已完成'),
icon: <CheckCircle2 size={12} />,
},
failure: {
color: 'red',
text: t('失败'),
icon: <AlertCircle size={12} />,
},
failed: {
color: 'red',
text: t('失败'),
icon: <AlertCircle size={12} />,
},
canceled: {
color: 'grey',
text: t('已取消'),
icon: <AlertCircle size={12} />,
},
};
const config = statusMap[normalizedStatus] || {
color: 'grey',
text: status,
};
return (
<Tag
color={config.color}
style={{ display: 'inline-flex', alignItems: 'center', gap: '4px' }}
>
{config.icon}
{config.text}
</Tag>
);
};
// 批量下载 - 只下载已完成的任务
const handleBatchDownload = () => {
selectedTasks.forEach((taskId) => {
const task = tasks.find((t) => t.task_id === taskId);
if (task) {
const normalizedStatus = normalizeVideoTaskStatus(task.status);
// 只下载已完成的任务,视频URL会在 onDownload 中获取
if (normalizedStatus === 'success') {
onDownload(task);
}
}
});
};
// 批量删除
const handleBatchDelete = () => {
selectedTasks.forEach((taskId) => {
onDelete(taskId);
});
setSelectedTasks([]);
};
// 表格列定义
const columns = [
{
title: t('任务ID'),
dataIndex: 'task_id',
width: !isCompact ? 120 : 100,
render: (text) => (
<Tooltip content={text}>
<span style={{ cursor: 'pointer' }}>{text?.substring(0, 8)}...</span>
</Tooltip>
),
},
{
title: t('模式'),
dataIndex: 'action',
width: !isCompact ? 100 : 80,
render: (text) => {
// action 字段存储的是 text2video 或 image2video
const isText2Video = text === 'text2video' || text === 'TEXT2VIDEO';
return (
<Tag size={!isCompact ? 'default' : 'small'}>
{isText2Video ? t('文生视频') : t('图生视频')}
</Tag>
);
},
},
{
title: t('模型'),
dataIndex: 'model',
width: !isCompact ? 150 : 120,
render: (model) => model || '-',
},
{
title: t('提示词'),
dataIndex: 'prompt',
width: !isCompact ? 200 : 150,
ellipsis: { showTitle: true },
render: (prompt) => prompt || '-',
},
{
title: t('状态'),
dataIndex: 'status',
width: !isCompact ? 120 : 100,
render: (status) => getStatusTag(status),
},
{
title: t('进度'),
dataIndex: 'progress',
width: !isCompact ? 120 : 100,
render: (progress, record) => {
const normalizedStatus = normalizeVideoTaskStatus(record.status);
if (normalizedStatus === 'success') return '100%';
if (normalizedStatus === 'failure') return '-';
// 去除百分号并转换为数字
const percentValue =
typeof progress === 'string'
? parseInt(progress.replace('%', ''))
: progress || 0;
return <Progress percent={percentValue} showInfo size='small' />;
},
},
{
title: t('创建时间'),
dataIndex: 'created_at',
width: !isCompact ? 160 : 140,
render: (timestamp) => new Date(timestamp * 1000).toLocaleString('zh-CN'),
},
{
title: t('操作'),
dataIndex: 'operate',
width: !isCompact ? 220 : 180,
fixed: 'right',
render: (text, record) => {
const normalizedStatus = normalizeVideoTaskStatus(record.status);
return (
<Space>
{/* 播放和下载按钮:仅根据状态显示,视频URL在点击时才获取 */}
{normalizedStatus === 'success' && (
<>
<Button
size='small'
type='tertiary'
icon={<Play size={14} />}
onClick={() => onPlay && onPlay(record)}
>
{!isCompact ? t('播放') : ''}
</Button>
<Button
size='small'
type='tertiary'
icon={<Download size={14} />}
onClick={() => onDownload(record)}
>
{!isCompact ? t('下载') : ''}
</Button>
</>
)}
{/* 再生成按钮 - 对所有已完成或失败的任务显示 */}
{(normalizedStatus === 'success' ||
normalizedStatus === 'failure') &&
canRegenerateVideoTask(record) && (
<Button
size='small'
type='primary'
icon={<RefreshCw size={14} />}
onClick={() => onRegenerate && onRegenerate(record)}
>
{!isCompact ? t('再生成') : ''}
</Button>
)}
<Button
size='small'
type='danger'
icon={<Trash2 size={14} />}
onClick={() => {
Modal.warning({
title: t('确定删除此任务?'),
content: t('删除后将无法恢复'),
icon: <AlertCircle size={24} style={{ color: '#f59e0b' }} />,
okText: t('确定'),
cancelText: t('取消'),
onOk: () => onDelete(record.task_id),
centered: true,
okButtonProps: { type: 'danger' },
});
}}
>
{!isCompact ? t('删除') : ''}
</Button>
</Space>
);
},
},
];
// 统计信息
const taskStats = {
total: tasks.length,
queued: tasks.filter((t) => normalizeVideoTaskStatus(t.status) === 'queued')
.length,
in_progress: tasks.filter(
(t) => normalizeVideoTaskStatus(t.status) === 'in_progress',
).length,
completed: tasks.filter((t) => {
return normalizeVideoTaskStatus(t.status) === 'success';
}).length,
failed: tasks.filter((t) => {
return normalizeVideoTaskStatus(t.status) === 'failure';
}).length,
};
return (
<>
{/* 折叠触发器 */}
<div
style={{
position: 'absolute',
bottom: visible ? `${queueHeight}px` : '0',
left: 0,
right: 0,
height: '40px',
backgroundColor: 'var(--ui-color-bg-1)',
borderTop: '1px solid var(--ui-color-border)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
cursor: 'pointer',
transition: 'bottom 0.3s',
zIndex: 10,
}}
onClick={() => setVisible(!visible)}
>
<Space>
{visible ? <ChevronDown size={16} /> : <ChevronUp size={16} />}
<span style={{ fontSize: !isCompact ? '14px' : '12px' }}>
{t('任务队列')} ({taskStats.total})
</span>
{taskStats.in_progress > 0 && (
<Badge count={taskStats.in_progress} type='danger' />
)}
</Space>
</div>
{/* 任务队列抽屉 */}
<div
style={{
position: 'absolute',
bottom: visible ? '0' : `-${queueHeight}px`,
left: 0,
right: 0,
height: `${queueHeight}px`,
backgroundColor: 'var(--ui-color-bg-0)',
borderTop: '1px solid var(--ui-color-border)',
transition: 'bottom 0.3s',
display: 'flex',
flexDirection: 'column',
zIndex: 9,
}}
>
{/* 工具栏 */}
<div
style={{
padding: !isCompact ? '12px 16px' : '8px 12px',
borderBottom: '1px solid var(--ui-color-border)',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
flexWrap: 'wrap',
gap: '8px',
}}
>
<Space wrap>
<Button
size={!isCompact ? 'default' : 'small'}
icon={<RefreshCw size={14} />}
onClick={onRefresh}
>
{t('刷新')}
</Button>
{selectedTasks.length > 0 && (
<>
<Button
size={!isCompact ? 'default' : 'small'}
icon={<Download size={14} />}
onClick={handleBatchDownload}
>
{t('批量下载')} ({selectedTasks.length})
</Button>
<Button
size={!isCompact ? 'default' : 'small'}
type='danger'
icon={<Trash2 size={14} />}
onClick={() => {
Modal.warning({
title: t('确定删除选中的任务?'),
content: t('将删除 {{count}} 个任务,删除后将无法恢复', {
count: selectedTasks.length,
}),
icon: (
<AlertCircle size={24} style={{ color: '#f59e0b' }} />
),
okText: t('确定删除'),
cancelText: t('取消'),
onOk: handleBatchDelete,
centered: true,
okButtonProps: { type: 'danger' },
});
}}
>
{t('批量删除')} ({selectedTasks.length})
</Button>
</>
)}
</Space>
{/* 统计信息 */}
<Space wrap>
<Tag size={!isCompact ? 'default' : 'small'} color='blue'>
{t('排队')}: {taskStats.queued}
</Tag>
<Tag size={!isCompact ? 'default' : 'small'} color='cyan'>
{t('生成中')}: {taskStats.in_progress}
</Tag>
<Tag size={!isCompact ? 'default' : 'small'} color='green'>
{t('完成')}: {taskStats.completed}
</Tag>
<Tag size={!isCompact ? 'default' : 'small'} color='red'>
{t('失败')}: {taskStats.failed}
</Tag>
{/* 分页大小选择器 */}
<Select
size={!isCompact ? 'default' : 'small'}
value={pageSize}
onChange={setPageSize}
style={{ width: !isCompact ? '120px' : '100px' }}
>
<Select.Option value={3}>3 {t('条/页')}</Select.Option>
<Select.Option value={5}>5 {t('条/页')}</Select.Option>
<Select.Option value={10}>10 {t('条/页')}</Select.Option>
<Select.Option value={20}>20 {t('条/页')}</Select.Option>
<Select.Option value={50}>50 {t('条/页')}</Select.Option>
</Select>
</Space>
</div>
{/* 任务表格 */}
<div style={{ flex: 1, overflow: 'auto' }}>
<Table
columns={columns}
dataSource={tasks}
rowKey='task_id'
scroll={{ x: 'max-content' }}
pagination={{
pageSize: pageSize,
showSizeChanger: false,
size: !isCompact ? 'default' : 'small',
}}
rowSelection={{
selectedRowKeys: selectedTasks,
onChange: setSelectedTasks,
getCheckboxProps: (record) => ({
disabled: record.status === 'in_progress',
}),
}}
size='small'
empty={t('暂无任务')}
/>
</div>
</div>
</>
);
};
export default VideoTaskQueue;