Files
monkey-ai-web/src/components/creation/WorkFeed/WorkDetailDrawer.jsx
T
zhanjunhao 8a48765a46 chore(repo): 移除重复版权文件头并纳入共享单测
集中保留原版权声明,移除文件头检查和全局测试忽略规则。验证:全量单测、受影响用例复测及静态检查通过。
2026-11-20 11:23:49 +08:00

352 lines
11 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.
import {
Star as ActionStar,
Copy as ActionCopy,
} from '@/components/common/icons/ActionIcons';
import React, { useEffect, useRef, useState } from 'react';
import { Button, SideSheet, Spin } from '@/components/ui';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { ERROR_ACTIONS } from '../../../helpers/creationError';
import { copy, renderQuota, showSuccess } from '../../../helpers';
import { useIsMobile } from '../../../hooks/common/useIsMobile';
import { adapterOf } from '../../../hooks/creation/creationForm';
import {
elapsedSeconds,
formatSeconds,
isActiveTask,
isSlowTask,
} from '../../../hooks/creation/creationTasks';
import { RefundNote, ResultImage, altOf, failureOf } from './WorkCard';
import ApiCodePanel from './ApiCodePanel';
import { sheetHeight } from '../viewport';
import './work-feed.css';
const LEGACY_MODE_LABELS = {
'text-to-image': '文生图',
'image-to-image': '图生图',
};
const formatTime = (ms) => {
if (!ms) return '-';
try {
return new Date(ms).toLocaleString();
} catch (e) {
return '-';
}
};
const DetailVideo = ({ task, onRefresh }) => {
const { t } = useTranslation();
const triedRef = useRef('');
const [failed, setFailed] = useState(false);
useEffect(() => setFailed(false), [task.videoUrl]);
if (!task.videoUrl || failed) {
return (
<div className='wf-placeholder'>
{failed ? t('视频暂不可用') : <Spin />}
</div>
);
}
return (
<video
src={task.videoUrl}
controls
playsInline
preload='metadata'
aria-label={altOf(task, t)}
onError={async () => {
if (triedRef.current === task.videoUrl) {
setFailed(true);
return;
}
triedRef.current = task.videoUrl;
const next = await onRefresh(task);
if (!next || next === task.videoUrl) setFailed(true);
}}
/>
);
};
/**
* 作品详情抽屉(WP B-6,改造自 ImageDetailModal):大图 / 播放器 + 参数 + 操作。
* 桌面右侧抽屉,移动端底部抽屉。打开时拉取详情(参数快照 request、视频播放地址)。
*
* props: task(作品流中的最新对象), visible, onClose, estSeconds,
* getActions(task, index) → [{ key, label, icon, onClick, danger }],
* onFavorite, onCancel, fetchDetail, onRefreshImage, onRefreshVideo
*/
const WorkDetailDrawer = ({
task,
visible,
onClose,
estSeconds = 0,
p90 = 0,
now,
getActions,
onFavorite,
onCancel,
fetchDetail,
onRefreshImage,
onRefreshVideo,
}) => {
const { t } = useTranslation();
const navigate = useNavigate();
const isMobile = useIsMobile();
const [index, setIndex] = useState(0);
const [loadingDetail, setLoadingDetail] = useState(false);
const taskId = task?.id;
useEffect(() => {
setIndex(0);
}, [taskId]);
// 打开时拉取一次详情(快照 / 播放地址 / regenerate_supported)
const fetchedRef = useRef('');
useEffect(() => {
if (!visible || !task || fetchedRef.current === task.id) return;
fetchedRef.current = task.id;
let alive = true;
setLoadingDetail(true);
fetchDetail(task).finally(() => {
if (alive) setLoadingDetail(false);
});
return () => {
alive = false;
};
// 只按作品 id 触发
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [visible, taskId]);
useEffect(() => {
if (!visible) fetchedRef.current = '';
}, [visible]);
if (!task) return null;
const active = isActiveTask(task);
const req = task.request || {};
const modeLabels = adapterOf(task.kind).modeLabels || {};
const modeKey = task.mode || req.mode || '';
const modeLabel = modeKey
? t(modeLabels[modeKey] || LEGACY_MODE_LABELS[modeKey] || modeKey)
: '';
const actions = getActions ? getActions(task, index) : [];
// 失败原因的下一步动作:重试 → 再生成;修改提示词 / 重新上传 → 复用参数;余额不足 → 去充值
const failure = task.status === 'failed' ? failureOf(t, task) : null;
const failureAction = (() => {
if (!failure || !failure.actionLabel) return null;
const action = failure.info.action;
if (action === ERROR_ACTIONS.TOPUP) {
return { topup: true, onClick: () => navigate('/console/topup') };
}
const key = action === ERROR_ACTIONS.RETRY ? 'regenerate' : 'reuse';
const hit = actions.find((a) => a.key === key);
return hit ? { onClick: hit.onClick } : null;
})();
const params = [
[t('模型'), task.model || '-'],
modeLabel ? [t('生成模式'), modeLabel] : null,
task.kind === 'image' && task.size
? [t('尺寸'), task.size.replace('x', '×')]
: null,
task.kind === 'image' && task.quality ? [t('画质'), task.quality] : null,
task.kind === 'image' && task.n > 1 ? [t('张数'), task.n] : null,
task.kind === 'video' && task.ratio ? [t('比例'), task.ratio] : null,
task.kind === 'video' && task.resolution
? [t('分辨率'), task.resolution]
: null,
task.kind === 'video' && task.duration > 0
? [t('时长'), formatSeconds(task.duration)]
: null,
typeof req.seed === 'number' ? [t('种子'), req.seed] : null,
[t('创建时间'), formatTime(task.createdAt)],
task.finishedAt && task.startedAt && !active
? [t('耗时'), formatSeconds((task.finishedAt - task.startedAt) / 1000)]
: null,
task.quota > 0 ? [t('消耗'), renderQuota(task.quota)] : null,
task.quotedQuota > 0 ? [t('预估'), renderQuota(task.quotedQuota)] : null,
].filter(Boolean);
const images = task.images || [];
const elapsed = elapsedSeconds(task, now);
let media;
if (task.status === 'success') {
media =
task.kind === 'video' ? (
<DetailVideo task={task} onRefresh={onRefreshVideo} />
) : (
<ResultImage
task={task}
index={index}
onRefresh={onRefreshImage}
alt={altOf(task, t)}
/>
);
} else if (active) {
media = (
<div className='wf-placeholder'>
<Spin />
<span>{task.status === 'queued' ? t('排队中') : t('生成中')}</span>
<span className='wf-num'>
{estSeconds > 0
? t('已用时 {{elapsed}} / 预计 {{est}}', {
elapsed: formatSeconds(elapsed),
est: formatSeconds(estSeconds),
})
: t('已用时 {{elapsed}}', { elapsed: formatSeconds(elapsed) })}
</span>
{isSlowTask(task, p90, now) ? (
<span className='wf-slow' role='note'>
{t('比平时慢,可以切到其他页面,完成后会提醒你')}
</span>
) : null}
</div>
);
} else {
media = <div className='wf-placeholder'>{t('生成失败')}</div>;
}
return (
<SideSheet
visible={visible}
onCancel={onClose}
title={task.kind === 'video' ? t('视频详情') : t('图片详情')}
placement={isMobile ? 'bottom' : 'right'}
width={isMobile ? undefined : 'min(720px, 92vw)'}
height={isMobile ? sheetHeight(92) : undefined}
bodyStyle={{
paddingBottom: 'calc(16px + env(safe-area-inset-bottom, 0px))',
}}
className='app-scrollbar'
>
<div className='wf-detail'>
<div className='wf-detail-media'>{media}</div>
{task.kind === 'image' && images.length > 1 ? (
<div
className='wf-thumbs app-scrollbar'
role='tablist'
aria-label={t('结果图片')}
>
{images.map((img, i) => (
<button
key={i}
type='button'
role='tab'
aria-selected={i === index}
aria-label={t('第 {{n}} 张', { n: i + 1 })}
className={`wf-thumb${i === index ? ' is-active' : ''}`}
onClick={() => setIndex(i)}
>
{img.url ? <img src={img.url} alt='' loading='lazy' /> : null}
</button>
))}
</div>
) : null}
{task.status === 'failed' ? (
<div className='wf-detail-alert' role='note'>
{failure ? (
<>
<strong>{failure.title}</strong>
{failure.detail ? <div>{failure.detail}</div> : null}
{failure.info.category !== 'unknown' &&
failure.title !== task.failReason ? (
<div className='wf-detail-raw'>{task.failReason}</div>
) : null}
</>
) : (
<div>{t('生成失败')}</div>
)}
<RefundNote task={task} />
{failureAction ? (
<Button
size='small'
type={failureAction.topup ? 'warning' : 'tertiary'}
onClick={failureAction.onClick}
>
{failure.actionLabel}
</Button>
) : null}
</div>
) : null}
<div className='wf-detail-actions'>
{!active ? (
<Button
icon={
<ActionStar
size={14}
aria-hidden='true'
fill={task.favorited ? 'currentColor' : 'none'}
/>
}
type={task.favorited ? 'warning' : 'tertiary'}
aria-pressed={task.favorited}
onClick={() => onFavorite(task)}
>
{task.favorited ? t('已收藏') : t('收藏')}
</Button>
) : null}
{active && task.cancelable ? (
<Button type='danger' onClick={() => onCancel(task)}>
{t('取消任务')}
</Button>
) : null}
{actions.map((action) => (
<Button
key={action.key}
icon={action.icon}
type={action.danger ? 'danger' : 'tertiary'}
onClick={() => action.onClick(task)}
>
{action.label}
</Button>
))}
</div>
<section>
<div className='flex items-center justify-between gap-2'>
<h3 className='wf-detail-section-title'>{t('提示词')}</h3>
{task.prompt ? (
<Button
size='small'
theme='borderless'
icon={<ActionCopy size={12} aria-hidden='true' />}
onClick={async () => {
if (await copy(task.prompt)) showSuccess(t('已复制'));
}}
>
{t('复制')}
</Button>
) : null}
</div>
<p className='wf-detail-prompt'>{task.prompt || t('(无提示词)')}</p>
</section>
<section>
<h3 className='wf-detail-section-title'>
{t('参数')}
{loadingDetail ? (
<Spin size='small' wrapperClassName='ml-2' />
) : null}
</h3>
<dl className='wf-params'>
{params.map(([label, value]) => (
<div key={label}>
<dt>{label}</dt>
<dd title={String(value)}>{value}</dd>
</div>
))}
</dl>
</section>
{!active ? <ApiCodePanel key={task.id} task={task} /> : null}
</div>
</SideSheet>
);
};
export default WorkDetailDrawer;