Files
monkey-ai-web/src/components/creation/WorkFeed/WorkFeed.jsx
T
qiubaishen 7025e3f9b4 refactor(ui): 将合并引入的 Semi 组件迁移到 Ant Design 适配层
- 创作台、WeyAi 设置、OrgResolver 共 23 个文件改从 @/components/ui 引入
- Popover 改用 open/trigger='click'/onOpenChange,移除 .semi-portal 判定
- Dropdown.Title / Item active 改为 menu group / selectedKeys
- Slider tooltip.formatter、Checkbox.Group、TagInput maxCount、DatePicker 取 Date 参数
- --semi-color-* 改为 --ui-color-*,遮罩色用 antd 默认,.semi-* 选择器改为 .ant-*
- docs/UI_MIGRATION.md 记录组件映射、视觉差异与风险
2026-11-10 12:48:02 +08:00

989 lines
31 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, {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { Button, Modal, Spin } from '@/components/ui';
import {
Clapperboard,
Columns2,
Dices,
Download,
Film,
ImageIcon,
ImagePlus,
PenLine,
RotateCcw,
SlidersHorizontal,
Trash2,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { showError, showInfo, showSuccess } from '../../../helpers';
import { trackCreationEvent } from '../../../helpers/creationEvents';
import { templateGroupsOf } from '../../../constants/creationTemplates';
import { templateParamsSummary } from '../../../hooks/creation/creationDock';
import {
formFromImageRequest,
formFromLegacyTask,
} from '../../../hooks/image/imageCreation';
import { formFromTaskRequest } from '../../../hooks/video/videoCreation';
import { adapterOf } from '../../../hooks/creation/creationForm';
import {
comparableBatchTasks,
groupBatchRows,
} from '../../../hooks/creation/creationCompare';
import {
GROUP_LABEL_KEYS,
PAGE_SIZE,
activeFilterCount,
filterTasks,
groupTasksByDate,
hasClientFilter,
isActiveTask,
nextEmptyStreak,
shouldAutoLoad,
taskImageRef,
taskLastFrameRef,
variationParams,
} from '../../../hooks/creation/creationTasks';
import ImageCompareModal from '../../../pages/ExperienceCenter/components/AICreation/ImageCompareModal';
import WorkCard from './WorkCard';
import WorkDetailDrawer from './WorkDetailDrawer';
import './work-feed.css';
const COMPARE_MAX = 4;
/** 对比视图(ImageCompareModal)需要的作品结构。 */
const compareItemOf = (task) => ({
id: task.id,
imageUrl: task.images?.[0]?.url,
model: task.model,
width: task.width,
height: task.height,
quality: task.quality,
prompt: task.prompt,
});
const newSlotId = () =>
`slot-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
// 结果不可按 task:// 引用时,下载后按本地图片处理
const urlToFile = async (url, filename) => {
const resp = await fetch(url);
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
const blob = await resp.blob();
const ext = (blob.type.split('/')[1] || 'png').replace('jpeg', 'jpg');
return new File([blob], `${filename}.${ext}`, {
type: blob.type || 'image/png',
});
};
const triggerDownload = (href, filename) => {
const link = document.createElement('a');
link.href = href;
link.download = filename;
link.target = '_blank';
link.rel = 'noopener';
link.style.display = 'none';
document.body.appendChild(link);
link.click();
requestAnimationFrame(() => document.body.removeChild(link));
};
/** 作品 → formFromLegacyTask 需要的旧任务结构(无参数快照的旧任务)。 */
const legacyShapeOf = (task) => ({
taskData: task.taskData || {},
width: task.width,
height: task.height,
quality: task.quality,
n: task.n,
negativePrompt: task.taskData?.negative_prompt,
mode: task.mode,
sourceImageUrl: task.sourceImageUrl,
prompt: task.prompt,
model: task.model,
});
/** 每秒刷新"已用时"(仅在有进行中作品时计时)。 */
const useNow = (enabled) => {
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
if (!enabled) return undefined;
setNow(Date.now());
const timer = setInterval(() => setNow(Date.now()), 1000);
return () => clearInterval(timer);
}, [enabled]);
return now;
};
/**
* 空作品流 = 灵感模板墙(WP B-7,方案 §4.4):按分组展示静态模板,点击填入提示词 +
* 推荐模型 / 参数并聚焦创作台。
*/
const TemplateWall = ({ kind, onApply, onStart }) => {
const { t } = useTranslation();
const groups = useMemo(() => templateGroupsOf(kind), [kind]);
const Icon = kind === 'video' ? Clapperboard : ImageIcon;
return (
<div className='wf-wall'>
<div className='wf-wall-head'>
<p className='wf-wall-eyebrow'>{t('灵感模板')}</p>
<h2 className='wf-wall-title'>
{kind === 'video'
? t('从一个模板开始你的第一个视频')
: t('从一个模板开始你的第一张作品')}
</h2>
<p className='wf-wall-desc'>
{t('点击模板会填好提示词与推荐参数,可在下方创作台继续修改')}
</p>
</div>
{groups.map((group) => (
<section
key={group.group || 'default'}
className='wf-wall-group'
aria-label={group.group ? t(group.group) : t('灵感模板')}
>
{group.group ? (
<h3 className='wf-group-title'>
{t(group.group)}
<span className='wf-group-count'>{group.items.length}</span>
</h3>
) : null}
<div className='wf-wall-grid'>
{group.items.map((tpl) => {
const summary = templateParamsSummary(tpl);
return (
<button
key={tpl.id}
type='button'
className='wf-tpl'
onClick={() => onApply(tpl)}
aria-label={t('使用模板:{{title}}', { title: t(tpl.title) })}
>
<span className='wf-tpl-head'>
<span className='wf-tpl-icon' aria-hidden='true'>
<Icon size={16} />
</span>
<span className='wf-tpl-title'>{t(tpl.title)}</span>
{summary ? (
<span className='wf-tpl-meta'>{summary}</span>
) : null}
</span>
<span className='wf-tpl-prompt'>{tpl.prompt}</span>
</button>
);
})}
</div>
</section>
))}
<div className='wf-wall-foot'>
<Button onClick={onStart}>{t('自己写提示词')}</Button>
</div>
</div>
);
};
/**
* 作品流(WP B-6,方案 §4.1 / §4.4 / §4.5):按日期分组、进行中置顶;图像 / 视频卡片;详情抽屉;
* 多选对比(图像);无限滚动;加载 / 空 / 错误态;状态变化 aria-live 播报。
*
* props:
* kind, api = useCreationTasks(kind), form = useCreationForm(kind),
* selecting / onSelectingChange(图像多选对比,开关在 FilterBar)
* onUseAsVideoFirstFrame?(task, ref, previewUrl):图像"用作视频首帧"跨页入口(WP C-3,未传时不显示)
* onContinueVideo?(task):覆盖视频"续写下一段"的默认实现(默认在本页回填尾帧为首帧)
*/
const WorkFeed = ({
kind,
api,
form,
selecting = false,
onSelectingChange,
onUseAsVideoFirstFrame,
onContinueVideo,
}) => {
const { t } = useTranslation();
const {
tasks,
filters,
loading,
loadingMore,
error,
hasMore,
loadMore,
reload,
resetFilters,
announcement,
} = api;
const visibleTasks = useMemo(
() => filterTasks(tasks, filters),
[tasks, filters],
);
const hasActive = useMemo(() => tasks.some(isActiveTask), [tasks]);
const now = useNow(hasActive);
const groups = useMemo(
() => groupTasksByDate(visibleTasks, Date.now()),
[visibleTasks],
);
// 预计耗时 p50 / p90(来自 schema est_seconds;超过 p90 显示慢任务提示)
const estByModel = useMemo(() => {
const map = new Map();
(form.models || []).forEach((m) => {
const p50 = Number(m?.est_seconds?.p50) || 0;
if (m?.model && p50 > 0) map.set(m.model, p50);
});
return map;
}, [form.models]);
const p90ByModel = useMemo(() => {
const map = new Map();
(form.models || []).forEach((m) => {
const p90 = Number(m?.est_seconds?.p90) || 0;
if (m?.model && p90 > 0) map.set(m.model, p90);
});
return map;
}, [form.models]);
// 模型 schema 中的种子参数("换种子再来"只对支持指定种子的模型显示)
const seedParamOf = useCallback(
(modelName) => {
const model = (form.models || []).find((m) => m?.model === modelName);
if (!model) return null;
return (
adapterOf(kind)
.requestParamsOf(model)
.find((p) => p.key === 'seed') || null
);
},
[form.models, kind],
);
// ---------------------------------------------------------------------------
// 详情抽屉
// ---------------------------------------------------------------------------
const [detailId, setDetailId] = useState('');
const detailTask = useMemo(
() => tasks.find((task) => task.id === detailId) || null,
[tasks, detailId],
);
const openDetail = useCallback((task) => setDetailId(task.id), []);
const closeDetail = useCallback(() => setDetailId(''), []);
// ---------------------------------------------------------------------------
// 二次创作:复用参数 / 再生成 / 用作参考图 / 编辑此图 / 下载 / 删除
// ---------------------------------------------------------------------------
const resolveFilled = useCallback(
async (task) => {
let full = task;
if (!full.request) full = (await api.fetchDetail(task)) || task;
if (kind === 'video') {
if (!full.request) {
showError(t('该任务不支持复用参数'));
return null;
}
const filled = formFromTaskRequest(full.request, { newId: newSlotId });
return {
filled: { ...filled, modelName: filled.modelName || full.model },
missing: 0,
supported: full.regenerateSupported === true,
};
}
const filled = full.request
? formFromImageRequest(full.request, { newId: newSlotId })
: formFromLegacyTask(legacyShapeOf(full), { newId: newSlotId });
return {
filled: {
modelName: filled.modelName || full.model || '',
mode: filled.mode,
prompt: filled.prompt,
params: filled.params,
images: {
first_frame: null,
last_frame: null,
reference_images: filled.references,
},
},
missing: filled.missingReferences,
supported: Boolean(full.request) && full.regenerateSupported !== false,
};
},
[api, kind, t],
);
const reuse = useCallback(
async (task) => {
const r = await resolveFilled(task);
if (!r) return;
if (r.missing > 0) showInfo(t('部分参考图已失效,请重新上传'));
if (form.prefill(r.filled)) {
trackCreationEvent('reuse_params', {
kind,
model: r.filled.modelName || '',
regenerate: false,
});
closeDetail();
}
},
[resolveFilled, form, closeDetail, kind, t],
);
// 再生成 = 回填 + 参数仍有效时立即提交;参考图失效 / 快照不完整时只回填并提示
const regenerate = useCallback(
async (task) => {
const r = await resolveFilled(task);
if (!r) return;
const autoSubmit = r.supported && r.missing === 0;
if (!autoSubmit) {
showInfo(t('原参数部分已失效,已回填,请确认后生成'));
}
if (form.prefill(r.filled, { autoSubmit })) {
trackCreationEvent('reuse_params', {
kind,
model: r.filled.modelName || '',
regenerate: true,
});
closeDetail();
}
},
[resolveFilled, form, closeDetail, kind, t],
);
// 换种子再来(WP C-3):同一请求换一个随机种子;参数原样有效时立即提交,否则只回填
const variation = useCallback(
async (task) => {
const r = await resolveFilled(task);
if (!r) return;
const filled = {
...r.filled,
params: variationParams(
r.filled.params,
seedParamOf(r.filled.modelName || task.model),
),
};
const autoSubmit = r.supported && r.missing === 0;
if (!autoSubmit) {
showInfo(t('原参数部分已失效,已回填,请确认后生成'));
}
if (form.prefill(filled, { autoSubmit })) {
trackCreationEvent('reuse_params', {
kind,
model: filled.modelName || '',
regenerate: true,
variation: true,
});
closeDetail();
}
},
[resolveFilled, seedParamOf, form, closeDetail, kind, t],
);
// 续写下一段(WP C-3):尾帧作为首帧(task://id#last_frame,后端优先已转存的尾帧),
// 图生视频、同模型同参数,提示词沿用原文供修改
const continueVideo = useCallback(
async (task) => {
let full = task;
if (!full.request) full = (await api.fetchDetail(task)) || task;
const base = full.request
? formFromTaskRequest(full.request, { newId: newSlotId })
: { modelName: '', prompt: '', params: {} };
const filled = {
modelName: base.modelName || full.model,
mode: 'image2video',
prompt: base.prompt || full.prompt || '',
params: base.params || {},
images: {
first_frame: {
id: newSlotId(),
status: 'ready',
ref: taskLastFrameRef(full.id),
previewUrl: full.lastFrameUrl || null,
source: 'task',
identityType: 'aigc',
},
last_frame: null,
reference_images: [],
},
};
if (
form.prefill(filled, {
notice: t('已将尾帧放入首帧,描述下一段内容后生成'),
})
) {
closeDetail();
}
},
[api, form, closeDetail, t],
);
const handleContinueVideo = onContinueVideo || continueVideo;
const addReference = useCallback(
async (task, index) => {
const image = task.images?.[index];
if (!image?.url) {
showError(t('该图片暂不可用作参考图'));
return false;
}
if (image.reusable) {
form.setImageRef('reference_images', undefined, {
ref: taskImageRef(task.id, index),
previewUrl: image.url,
});
return true;
}
try {
const file = await urlToFile(
image.url,
`reference-${task.id}-${index}`,
);
return await form.pickImage('reference_images', undefined, file);
} catch (e) {
showError(t('参考图加载失败'));
return false;
}
},
[form, t],
);
const applyAsReference = useCallback(
async (task, index = 0) => {
if (!(await addReference(task, index))) return;
form.setMode('edit');
showInfo(t('已加入参考图'));
closeDetail();
form.requestFocus();
},
[addReference, form, closeDetail, t],
);
// 编辑此图:替换参考图槽为这张图,切到编辑模式,光标进入提示词
const editImage = useCallback(
async (task, index = 0) => {
const images = form.form.images || {};
form.setImages({ ...images, reference_images: [] });
if (!(await addReference(task, index))) {
form.setImages(images);
return;
}
form.setMode('edit');
closeDetail();
form.requestFocus();
},
[addReference, form, closeDetail],
);
const download = useCallback(
async (task, index = 0) => {
if (task.kind === 'video') {
const url = task.videoUrl || (await api.refreshVideoUrl(task));
if (!url) {
showError(t('未找到视频URL'));
return;
}
triggerDownload(url, `video_${task.id}.mp4`);
showSuccess(t('开始下载'));
return;
}
const url = task.images?.[index]?.url;
if (!url) {
showError(t('图片不存在'));
return;
}
try {
const resp = await fetch(url);
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
const blob = await resp.blob();
const ext = (blob.type.split('/')[1] || 'png').replace('jpeg', 'jpg');
const objectUrl = URL.createObjectURL(blob);
triggerDownload(objectUrl, `image_${task.id}_${index + 1}.${ext}`);
setTimeout(() => URL.revokeObjectURL(objectUrl), 1000);
showSuccess(t('开始下载'));
} catch (e) {
// 跨域等原因无法读取时,在新窗口打开由用户另存
window.open(url, '_blank', 'noopener');
}
},
[api, t],
);
const confirmDelete = useCallback(
(task) => {
Modal.confirm({
title: t('删除作品'),
content: t('删除后不可恢复,确定删除这个作品吗?'),
okButtonProps: { danger: true },
okText: t('删除'),
cancelText: t('取消'),
onOk: async () => {
if (await api.deleteTask(task)) {
if (detailId === task.id) closeDetail();
}
},
});
},
[api, detailId, closeDetail, t],
);
const getActions = useCallback(
(task, index = 0) => {
const list = [];
const done = task.status === 'success';
const active = isActiveTask(task);
if (!active) {
list.push({
key: 'reuse',
label: t('复用参数'),
icon: <SlidersHorizontal size={14} aria-hidden='true' />,
onClick: () => reuse(task),
});
list.push({
key: 'regenerate',
label: t('再生成'),
icon: <RotateCcw size={14} aria-hidden='true' />,
onClick: () => regenerate(task),
});
}
if (done && seedParamOf(task.model)) {
list.push({
key: 'variation',
label: t('换种子再来'),
icon: <Dices size={14} aria-hidden='true' />,
onClick: () => variation(task),
});
}
if (kind === 'image' && done && task.images?.[index]?.url) {
list.push({
key: 'reference',
label: t('用作参考图'),
icon: <ImagePlus size={14} aria-hidden='true' />,
onClick: () => applyAsReference(task, index),
});
list.push({
key: 'edit',
label: t('编辑此图'),
icon: <PenLine size={14} aria-hidden='true' />,
onClick: () => editImage(task, index),
});
// 只有服务端判定可复用(reusable_as_input)的结果才能以 task:// 带到视频页
if (onUseAsVideoFirstFrame && task.images[index].reusable) {
list.push({
key: 'video-first-frame',
label: t('用作视频首帧'),
icon: <Film size={14} aria-hidden='true' />,
onClick: () =>
onUseAsVideoFirstFrame(
task,
taskImageRef(task.id, index),
task.images[index].url,
),
});
}
}
if (
kind === 'video' &&
done &&
task.reusableAsInput !== false &&
(task.reusableAsInput === true || task.lastFrameUrl)
) {
list.push({
key: 'continue',
label: t('续写下一段'),
icon: <Clapperboard size={14} aria-hidden='true' />,
onClick: () => handleContinueVideo(task),
});
}
if (done) {
list.push({
key: 'download',
label: t('下载'),
icon: <Download size={14} aria-hidden='true' />,
onClick: () => download(task, index),
});
}
if (!active) {
list.push({
key: 'delete',
label: t('删除'),
icon: <Trash2 size={14} aria-hidden='true' />,
danger: true,
onClick: () => confirmDelete(task),
});
}
return list;
},
[
kind,
reuse,
regenerate,
applyAsReference,
editImage,
download,
confirmDelete,
onUseAsVideoFirstFrame,
handleContinueVideo,
variation,
seedParamOf,
t,
],
);
// ---------------------------------------------------------------------------
// 多选对比(图像)
// ---------------------------------------------------------------------------
const [selectedIds, setSelectedIds] = useState([]);
const [compareOpen, setCompareOpen] = useState(false);
useEffect(() => {
if (!selecting) setSelectedIds([]);
}, [selecting]);
const isSelectable = useCallback(
(task) =>
kind === 'image' &&
task.status === 'success' &&
Boolean(task.images?.[0]?.url),
[kind],
);
const toggleSelect = useCallback(
(task) => {
setSelectedIds((prev) => {
if (prev.includes(task.id)) return prev.filter((id) => id !== task.id);
if (prev.length >= COMPARE_MAX) {
showInfo(t('最多选择 {{n}} 张', { n: COMPARE_MAX }));
return prev;
}
return [...prev, task.id];
});
},
[t],
);
const compareTasks = useMemo(
() =>
selectedIds
.map((id) => tasks.find((task) => task.id === id))
.filter(Boolean)
.map(compareItemOf),
[selectedIds, tasks],
);
// 对比生成批次的"对比视图"(WP C-2)
const [batchCompare, setBatchCompare] = useState(null);
const openBatchCompare = useCallback(
(batchTasks) => {
const items = comparableBatchTasks(batchTasks).map(compareItemOf);
if (items.length < 2) {
showInfo(t('至少需要 2 张已完成的图片才能对比'));
return;
}
setBatchCompare(items);
},
[t],
);
// ---------------------------------------------------------------------------
// 无限滚动:哨兵在滚动容器(.cs-feed)内可见时持续加载下一页
// ---------------------------------------------------------------------------
const [sentinelVisible, setSentinelVisible] = useState(false);
const observerRef = useRef(null);
const sentinelRef = useCallback((el) => {
observerRef.current?.disconnect();
observerRef.current = null;
if (!el || typeof IntersectionObserver === 'undefined') {
setSentinelVisible(false);
return;
}
const io = new IntersectionObserver(
([entry]) => setSentinelVisible(entry.isIntersecting),
{ root: el.closest('.cs-feed'), rootMargin: '400px 0px' },
);
io.observe(el);
observerRef.current = io;
}, []);
useEffect(() => () => observerRef.current?.disconnect(), []);
// 本地过滤(关键词 / 模型 / 尺寸 / 进行中)时不把全部历史自动翻完:连续 3 页没有新命中就停,
// 改为"加载更多"按钮(WP B-7)。服务端过滤(成功 / 失败 / 收藏)不受影响。
const clientFiltered = hasClientFilter(filters);
const clientKey = `${filters.status}|${filters.model}|${filters.size}|${filters.keyword}`;
const [emptyStreak, setEmptyStreak] = useState(0);
const matchesBeforeRef = useRef(null);
useEffect(() => {
setEmptyStreak(0);
matchesBeforeRef.current = null;
}, [clientKey]);
const loadNextPage = useCallback(() => {
matchesBeforeRef.current = visibleTasks.length;
loadMore();
}, [visibleTasks.length, loadMore]);
useEffect(() => {
if (loadingMore || matchesBeforeRef.current === null) return;
const before = matchesBeforeRef.current;
matchesBeforeRef.current = null;
if (!clientFiltered) return;
setEmptyStreak((n) => nextEmptyStreak(n, before, visibleTasks.length));
// 只在一页加载结束时结算
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [loadingMore]);
const autoLoad = shouldAutoLoad(filters, emptyStreak);
const loadMoreManually = useCallback(() => {
setEmptyStreak(0);
loadNextPage();
}, [loadNextPage]);
useEffect(() => {
if (
autoLoad &&
sentinelVisible &&
hasMore &&
!loading &&
!loadingMore &&
!error
) {
loadNextPage();
}
}, [
autoLoad,
sentinelVisible,
hasMore,
loading,
loadingMore,
error,
loadNextPage,
]);
// ---------------------------------------------------------------------------
// 渲染
// ---------------------------------------------------------------------------
const filtered = activeFilterCount(filters) > 0;
const renderCard = (task) => {
const active = isActiveTask(task);
return (
<WorkCard
key={task.id}
task={task}
estSeconds={estByModel.get(task.model) || 0}
p90={p90ByModel.get(task.model) || 0}
now={active ? now : 0}
getActions={getActions}
onOpen={openDetail}
onFavorite={api.toggleFavorite}
onCancel={api.cancelTask}
onRefreshImage={api.refreshImageUrl}
onRefreshVideo={api.refreshVideoUrl}
selecting={selecting}
selectable={selecting && isSelectable(task)}
selected={selectedIds.includes(task.id)}
onToggleSelect={toggleSelect}
/>
);
};
const liveRegion = (
<div className='wf-sr-only' role='status' aria-live='polite'>
{announcement}
</div>
);
if (loading && tasks.length === 0) {
return (
<div className='wf' aria-busy='true'>
{liveRegion}
<div className='wf-grid'>
{Array.from({ length: 8 }, (_, i) => (
<div key={i} className='wf-skeleton' />
))}
</div>
</div>
);
}
if (error && tasks.length === 0) {
return (
<div className='wf'>
{liveRegion}
<div className='wf-state' role='alert'>
<p className='wf-state-title'>{t('作品加载失败')}</p>
<span>{t('请检查网络后重试')}</span>
<Button onClick={reload}>{t('重试')}</Button>
</div>
</div>
);
}
if (tasks.length === 0 && !filtered) {
return (
<div className='wf'>
{liveRegion}
<TemplateWall
kind={kind}
onApply={(tpl) => {
if (form.applyTemplate(tpl)) {
showSuccess(t('已套用模板:{{title}}', { title: t(tpl.title) }));
}
}}
onStart={form.requestFocus}
/>
</div>
);
}
return (
<div className='wf'>
{liveRegion}
{selecting ? (
<div className='wf-selectbar' role='region' aria-label={t('多选对比')}>
<span className='wf-selectbar-text'>
{t('已选 {{n}} / {{max}} 张,选择 2~4 张已完成的图片进行对比', {
n: selectedIds.length,
max: COMPARE_MAX,
})}
</span>
<Button
theme='solid'
disabled={selectedIds.length < 2}
onClick={() => setCompareOpen(true)}
>
{t('对比')}
</Button>
<Button type='tertiary' onClick={() => onSelectingChange?.(false)}>
{t('取消')}
</Button>
</div>
) : null}
{visibleTasks.length === 0 ? (
<div className='wf-state'>
<p className='wf-state-title'>{t('没有符合条件的作品')}</p>
{hasMore && autoLoad ? (
<span>{t('正在继续查找更早的作品…')}</span>
) : null}
{hasMore && !autoLoad ? (
<span>{t('已加载的作品中没有匹配项,可继续加载更早的作品')}</span>
) : null}
<div className='wf-state-actions'>
{hasMore && !autoLoad ? (
<Button loading={loadingMore} onClick={loadMoreManually}>
{t('加载更多')}
</Button>
) : null}
<Button onClick={resetFilters}>{t('清除筛选')}</Button>
</div>
</div>
) : (
groups.map((group) => (
<section key={group.key} aria-label={t(GROUP_LABEL_KEYS[group.key])}>
<h2 className='wf-group-title'>
{t(GROUP_LABEL_KEYS[group.key])}
<span className='wf-group-count'>{group.tasks.length}</span>
</h2>
<div className='wf-grid'>
{groupBatchRows(group.tasks).map((row) =>
row.type === 'batch' ? (
<div
key={row.key}
className='wf-batch'
role='group'
aria-label={t('对比生成 · {{n}} 个模型', {
n: row.tasks.length,
})}
>
<div className='wf-batch-head'>
<Columns2 size={14} aria-hidden='true' />
<span className='wf-batch-title'>
{t('对比生成 · {{n}} 个模型', {
n: row.tasks.length,
})}
</span>
{kind === 'image' && !selecting ? (
<Button
size='small'
theme='light'
disabled={comparableBatchTasks(row.tasks).length < 2}
onClick={() => openBatchCompare(row.tasks)}
>
{t('对比视图')}
</Button>
) : null}
</div>
<div className='wf-grid'>
{row.tasks.map((task) => renderCard(task))}
</div>
</div>
) : (
renderCard(row.task)
),
)}
</div>
</section>
))
)}
<div ref={sentinelRef} className='wf-more'>
{loadingMore ? <Spin size='small' /> : null}
{!loadingMore && error ? (
<Button size='small' type='tertiary' onClick={loadNextPage}>
{t('加载失败,点击重试')}
</Button>
) : null}
{!loadingMore &&
!error &&
hasMore &&
!autoLoad &&
visibleTasks.length > 0 ? (
<Button size='small' type='tertiary' onClick={loadMoreManually}>
{t('加载更多')}
</Button>
) : null}
{!loadingMore && !error && !hasMore && tasks.length > PAGE_SIZE ? (
<span>{t('没有更多了')}</span>
) : null}
</div>
<WorkDetailDrawer
task={detailTask}
visible={Boolean(detailTask)}
onClose={closeDetail}
estSeconds={detailTask ? estByModel.get(detailTask.model) || 0 : 0}
p90={detailTask ? p90ByModel.get(detailTask.model) || 0 : 0}
now={now}
getActions={getActions}
onFavorite={api.toggleFavorite}
onCancel={api.cancelTask}
fetchDetail={api.fetchDetail}
onRefreshImage={api.refreshImageUrl}
onRefreshVideo={api.refreshVideoUrl}
/>
{kind === 'image' ? (
<ImageCompareModal
visible={compareOpen || Boolean(batchCompare)}
tasks={batchCompare || compareTasks}
onClose={() => {
setCompareOpen(false);
setBatchCompare(null);
}}
/>
) : null}
</div>
);
};
export default WorkFeed;