-
-
- {card.title}
-
-
- {card.value}
-
- {renderChange(card.change)}
+
+
+ {cards.map((card, index) => (
+
+
+
+
+ {card.title}
+
+
+ {card.value}
+
+ {renderChange(card.change)}
+
+
+ {card.icon}
+
-
- {card.icon}
-
-
-
- ))}
+
+ ))}
+
+ {/* 活跃/消耗取自汇总层时会落后一个同步周期(约 30~60 秒),把截止时间标出来,
+ 避免「数字和日志对不上」被当成算错;data_as_of 为 0 表示本次是实时直查。 */}
+ {overview.data_as_of > 0 && (
+
+ {t('活跃与消耗数据截至')} {timestamp2string(overview.data_as_of)}
+
+ )}
);
};
diff --git a/src/components/analytics/TopupChannelChart.jsx b/src/components/analytics/TopupChannelChart.jsx
index 4374579e..38cfc6e6 100644
--- a/src/components/analytics/TopupChannelChart.jsx
+++ b/src/components/analytics/TopupChannelChart.jsx
@@ -45,7 +45,8 @@ const TopupChannelChart = ({ data, title, icon, t }) => {
if (!data || data.length === 0) return null;
const chartData = data.map((item) => ({
- name: item.payment_method || t('未知'),
+ name: item.payment_method ? t(item.payment_method) : t('未知'),
+ rawName: item.payment_method,
value: item.amount || 0,
count: item.count || 0,
}));
@@ -53,7 +54,7 @@ const TopupChannelChart = ({ data, title, icon, t }) => {
// 根据支付渠道名称生成颜色数组
const colorList = chartData.map((item, index) => {
return (
- CHANNEL_COLORS[item.name] ||
+ CHANNEL_COLORS[item.rawName] ||
DEFAULT_COLORS[index % DEFAULT_COLORS.length]
);
});
@@ -80,7 +81,7 @@ const TopupChannelChart = ({ data, title, icon, t }) => {
},
{
key: () => t('笔数'),
- value: (datum) => `${datum?.count || 0} ${t('笔')}`,
+ value: (datum) => t('{{n}} 笔', { n: datum?.count || 0, count: datum?.count || 0 }),
},
],
},
@@ -131,7 +132,7 @@ const TopupChannelChart = ({ data, title, icon, t }) => {
className='flex items-center justify-between text-sm py-1 border-b border-gray-100 dark:border-gray-700 last:border-0'
>
- {item.payment_method}
+ {item.payment_method ? t(item.payment_method) : t('未知')}
diff --git a/src/components/analytics/TrendCharts.jsx b/src/components/analytics/TrendCharts.jsx
index b2cf60bd..2012b0f2 100644
--- a/src/components/analytics/TrendCharts.jsx
+++ b/src/components/analytics/TrendCharts.jsx
@@ -65,7 +65,7 @@ const TrendCharts = ({ title, icon, data, type, t }) => {
{
key: (datum) => datum?.type,
value: (datum) =>
- `${(datum?.value || 0).toLocaleString()} ${t('人')}`,
+ t('{{n}} 人', { n: (datum?.value || 0).toLocaleString(), count: datum?.value || 0 }),
},
],
},
@@ -75,7 +75,7 @@ const TrendCharts = ({ title, icon, data, type, t }) => {
{
key: (datum) => datum?.type,
value: (datum) =>
- `${(datum?.value || 0).toLocaleString()} ${t('人')}`,
+ t('{{n}} 人', { n: (datum?.value || 0).toLocaleString(), count: datum?.value || 0 }),
},
],
},
diff --git a/src/components/analytics/UserSurveyStats.jsx b/src/components/analytics/UserSurveyStats.jsx
index f96cfbeb..0c8d4498 100644
--- a/src/components/analytics/UserSurveyStats.jsx
+++ b/src/components/analytics/UserSurveyStats.jsx
@@ -99,7 +99,7 @@ const UserSurveyStats = ({ title, icon, t }) => {
return null;
const chartData = surveyStats.job_type_stats.map((item) => ({
- name: JOB_TYPE_CONFIG[item.job_type]?.label || t('未知'),
+ name: t(JOB_TYPE_CONFIG[item.job_type]?.label || '未知'),
value: item.count,
percentage: item.percentage,
}));
@@ -122,7 +122,11 @@ const UserSurveyStats = ({ title, icon, t }) => {
content: [
{
key: (datum) => datum?.name,
- value: (datum) => `${datum?.value || 0} ${t('人')}`,
+ value: (datum) =>
+ t('{{n}} 人', {
+ n: datum?.value || 0,
+ count: datum?.value || 0,
+ }),
},
{
key: () => t('占比'),
@@ -151,7 +155,7 @@ const UserSurveyStats = ({ title, icon, t }) => {
return null;
const chartData = surveyStats.ai_tool_stats.map((item) => ({
- name: AI_TOOL_CONFIG[item.ai_tool_usage]?.label || t('未知'),
+ name: t(AI_TOOL_CONFIG[item.ai_tool_usage]?.label || '未知'),
value: item.count,
percentage: item.percentage,
}));
@@ -174,7 +178,11 @@ const UserSurveyStats = ({ title, icon, t }) => {
content: [
{
key: (datum) => datum?.name,
- value: (datum) => `${datum?.value || 0} ${t('人')}`,
+ value: (datum) =>
+ t('{{n}} 人', {
+ n: datum?.value || 0,
+ count: datum?.value || 0,
+ }),
},
{
key: () => t('占比'),
@@ -236,7 +244,11 @@ const UserSurveyStats = ({ title, icon, t }) => {
},
{
key: () => t('新增'),
- value: (datum) => `${datum?.count || 0} ${t('人')}`,
+ value: (datum) =>
+ t('{{n}} 人', {
+ n: datum?.count || 0,
+ count: datum?.count || 0,
+ }),
},
],
},
@@ -279,7 +291,7 @@ const UserSurveyStats = ({ title, icon, t }) => {
<>
{totalUsers > 0 && (
- {totalUsers} {t('人已填写')}
+ {t('{{n}} 人已填写', { n: totalUsers, count: totalUsers })}
)}
>
@@ -394,7 +406,7 @@ const UserSurveyStats = ({ title, icon, t }) => {
{config?.icon}
- {config?.label}
+ {t(config?.label || '')}
@@ -461,7 +473,7 @@ const UserSurveyStats = ({ title, icon, t }) => {
{config?.icon}
- {config?.label}
+ {t(config?.label || '')}
@@ -549,7 +561,10 @@ const UserSurveyStats = ({ title, icon, t }) => {
{JOB_TYPE_CONFIG[item.job_type]?.icon}
- {JOB_TYPE_CONFIG[item.job_type]?.label}
+ {t(
+ JOB_TYPE_CONFIG[item.job_type]
+ ?.label || '',
+ )}
@@ -561,10 +576,10 @@ const UserSurveyStats = ({ title, icon, t }) => {
}
size='small'
>
- {
+ {t(
AI_TOOL_CONFIG[item.ai_tool_usage]
- ?.label
- }
+ ?.label || '',
+ )}
diff --git a/src/components/analytics/orgReport/ActionCenter.jsx b/src/components/analytics/orgReport/ActionCenter.jsx
index 57bf93e7..eb92f339 100644
--- a/src/components/analytics/orgReport/ActionCenter.jsx
+++ b/src/components/analytics/orgReport/ActionCenter.jsx
@@ -158,7 +158,7 @@ const columnsFor = (tab, cny, t, atRisk) => {
: 'var(--ui-color-warning)',
}}
>
- {v < 1 ? t('不足 1 天') : `${v.toFixed(1)} ${t('天')}`}
+ {v < 1 ? t('不足 1 天') : t('{{days}} 天', { days: v.toFixed(1) })}
);
},
diff --git a/src/components/analytics/orgReport/Overview.jsx b/src/components/analytics/orgReport/Overview.jsx
index d36a4c4d..82bcfce9 100644
--- a/src/components/analytics/orgReport/Overview.jsx
+++ b/src/components/analytics/orgReport/Overview.jsx
@@ -195,7 +195,7 @@ export const KpiGrid = ({ report, lists, cny, onJump, t }) => {
},
{
title: t('活跃企业'),
- value: `${(k.active_orgs || 0).toLocaleString()} ${t('家')}`,
+ value: t('{{n}} 家', { n: (k.active_orgs || 0).toLocaleString(), count: k.active_orgs || 0 }),
sub: `${t('活跃率')} ${pct(k.active_orgs, servingOrgs).toFixed(1)}% · ${t('新增')} ${k.new_orgs || 0}`,
compare: (
@@ -212,7 +212,7 @@ export const KpiGrid = ({ report, lists, cny, onJump, t }) => {
},
{
title: t('企业活跃成员'),
- value: `${(k.active_members || 0).toLocaleString()} ${t('人')}`,
+ value: t('{{n}} 人', { n: (k.active_members || 0).toLocaleString(), count: k.active_members || 0 }),
sub: `${t('渗透率')} ${Math.min(100, pct(k.active_members, k.total_members)).toFixed(1)}% · ${t('成员')} ${(k.total_members || 0).toLocaleString()}`,
tip: t('本期通过企业密钥产生调用的去重成员数(按自然日统计)'),
onClick: () => onJump('growth'),
@@ -238,7 +238,7 @@ export const KpiGrid = ({ report, lists, cny, onJump, t }) => {
{
title: t('未来 30 天充值缺口'),
value: formatCny(k.topup_gap_30d, cny),
- sub: `${lists.renewal.length} ${t('家需续费跟进')}`,
+ sub: t('{{n}} 家需续费跟进', { n: lists.renewal.length, count: lists.renewal.length }),
tip: t('按各企业近 7 日日均消耗覆盖 30 天所需金额,减去当前余额后累加'),
accent:
k.topup_gap_30d > 0
diff --git a/src/components/analytics/orgReport/Tables.jsx b/src/components/analytics/orgReport/Tables.jsx
index e0957671..96be1c99 100644
--- a/src/components/analytics/orgReport/Tables.jsx
+++ b/src/components/analytics/orgReport/Tables.jsx
@@ -308,7 +308,7 @@ export const OrgDetailTable = ({ report, filter, setFilter, cny, t }) => {
—
) : (
- {v < 1 ? t('不足 1 天') : `${v.toFixed(0)} ${t('天')}`}
+ {v < 1 ? t('不足 1 天') : t('{{days}} 天', { days: v.toFixed(0) })}
),
sorter: (a, b) =>
diff --git a/src/components/auth/LoginForm.jsx b/src/components/auth/LoginForm.jsx
index ee295880..7c59f26b 100644
--- a/src/components/auth/LoginForm.jsx
+++ b/src/components/auth/LoginForm.jsx
@@ -23,6 +23,7 @@ import React, {
useRef,
useState,
useCallback,
+ useMemo,
lazy,
Suspense,
} from 'react';
@@ -70,6 +71,10 @@ import GlassCard from './GlassCard';
import AuthCardHeader from './AuthCardHeader';
import AuthLoginTabs from './AuthLoginTabs';
import AgreementModal from '../common/DocumentRenderer/AgreementModal';
+import {
+ isMiniProgramWebView,
+ withMiniProgramLogins,
+} from '../../helpers/miniProgram';
// 懒加载 Telegram 登录组件(345KB),只在需要时加载
const TelegramLogin = lazy(() => import('./TelegramLogin'));
@@ -177,7 +182,11 @@ const LoginForm = () => {
// 使用 StatusContext 获取最新状态,而不是从 localStorage 读取
const [statusState] = useContext(StatusContext);
- const status = statusState?.status || {};
+ // WeyAi 小程序的 web-view 里只留站内能完成的登录方式(见 helpers/miniProgram.js)。
+ const status = useMemo(() => {
+ const raw = statusState?.status || {};
+ return isMiniProgramWebView() ? withMiniProgramLogins(raw) : raw;
+ }, [statusState?.status]);
const statusLoaded = statusState?.status !== undefined;
// affCode 只需在挂载时提取一次,避免每次渲染都执行
diff --git a/src/components/auth/RegisterForm.jsx b/src/components/auth/RegisterForm.jsx
index 6bb13944..6cabd452 100644
--- a/src/components/auth/RegisterForm.jsx
+++ b/src/components/auth/RegisterForm.jsx
@@ -23,6 +23,7 @@ import React, {
useRef,
useState,
useCallback,
+ useMemo,
lazy,
Suspense,
} from 'react';
@@ -65,6 +66,10 @@ import AuthCardHeader from './AuthCardHeader';
import AuthLoginTabs from './AuthLoginTabs';
import { ArrowRight, Shield, Smartphone, QrCode } from 'lucide-react';
import AgreementModal from '../common/DocumentRenderer/AgreementModal';
+import {
+ isMiniProgramWebView,
+ withMiniProgramLogins,
+} from '../../helpers/miniProgram';
// 懒加载 Telegram 登录组件(345KB),只在需要时加载
const TelegramLogin = lazy(() => import('./TelegramLogin'));
@@ -148,7 +153,11 @@ const RegisterForm = () => {
// 使用 StatusContext 获取最新状态,而不是从 localStorage 读取
const [statusState] = useContext(StatusContext);
- const status = statusState?.status || {};
+ // WeyAi 小程序的 web-view 里只留站内能完成的注册方式(见 helpers/miniProgram.js)。
+ const status = useMemo(() => {
+ const raw = statusState?.status || {};
+ return isMiniProgramWebView() ? withMiniProgramLogins(raw) : raw;
+ }, [statusState?.status]);
const statusLoaded = statusState?.status !== undefined;
const [showEmailVerification, setShowEmailVerification] = useState(() => {
@@ -235,7 +244,7 @@ const RegisterForm = () => {
const onSubmitWeChatVerificationCode = async () => {
if (turnstileEnabled && turnstileToken === '') {
- showInfo('请稍后几秒重试,Turnstile 正在检查用户环境!');
+ showInfo(t('请稍后几秒重试,Turnstile 正在检查用户环境!'));
return;
}
setWechatCodeSubmitLoading(true);
@@ -253,7 +262,7 @@ const RegisterForm = () => {
showError(message);
}
} catch (error) {
- showError('登录失败,请重试');
+ showError(t('登录失败,请重试'));
} finally {
setWechatCodeSubmitLoading(false);
}
@@ -281,7 +290,7 @@ const RegisterForm = () => {
}
if (username && password) {
if (turnstileEnabled && turnstileToken === '') {
- showInfo('请稍后几秒重试,Turnstile 正在检查用户环境!');
+ showInfo(t('请稍后几秒重试,Turnstile 正在检查用户环境!'));
return;
}
setRegisterLoading(true);
@@ -316,7 +325,7 @@ const RegisterForm = () => {
const sendVerificationCode = async () => {
if (inputs.email === '') return;
if (turnstileEnabled && turnstileToken === '') {
- showInfo('请稍后几秒重试,Turnstile 正在检查用户环境!');
+ showInfo(t('请稍后几秒重试,Turnstile 正在检查用户环境!'));
return;
}
setVerificationCodeLoading(true);
@@ -445,7 +454,7 @@ const RegisterForm = () => {
showError(message);
}
} catch (error) {
- showError('登录失败,请重试');
+ showError(t('登录失败,请重试'));
}
};
@@ -529,7 +538,7 @@ const RegisterForm = () => {
loading={githubLoading}
disabled={githubButtonDisabled}
>
- {githubButtonText}
+ {t(githubButtonText)}
)}
diff --git a/src/components/common/DocumentRenderer/index.jsx b/src/components/common/DocumentRenderer/index.jsx
index 62719497..4df83413 100644
--- a/src/components/common/DocumentRenderer/index.jsx
+++ b/src/components/common/DocumentRenderer/index.jsx
@@ -345,7 +345,12 @@ const DocumentRenderer = ({
const seen = new Map();
const headings = root.querySelectorAll('h2, h3');
headings.forEach((h) => {
- if (h.querySelector('.doc-anchor')) return; // 已处理
+ const existing = h.querySelector('.doc-anchor');
+ if (existing) {
+ // 已处理;切换语言时只刷新读屏文案
+ existing.setAttribute('aria-label', t('复制段落链接'));
+ return;
+ }
let base = h.id || slugify(h.textContent);
if (!base) return;
let id = base;
@@ -357,7 +362,7 @@ const DocumentRenderer = ({
const a = document.createElement('a');
a.href = `#${id}`;
a.className = 'doc-anchor';
- a.setAttribute('aria-label', '复制段落链接');
+ a.setAttribute('aria-label', t('复制段落链接'));
a.textContent = '#';
a.addEventListener('click', (e) => {
e.preventDefault();
@@ -429,7 +434,7 @@ const DocumentRenderer = ({
{t('内容正在准备中')}
- {t('管理员尚未设置') + title + t('内容')}
+ {t('管理员尚未设置{{title}}内容', { title })}
);
@@ -457,7 +462,7 @@ const DocumentRenderer = ({
className='group inline-flex items-center gap-2 px-6 py-2.5 bg-gradient-to-r from-brand-from to-brand-to hover:shadow-lg hover:shadow-brand/30 dark:hover:shadow-brand/20 text-white text-sm font-medium rounded-lg shadow-sm transition-all hover:-translate-y-0.5'
>
- {t('访问') + title}
+ {t('访问{{title}}', { title })}
diff --git a/src/components/common/markdown/MarkdownRenderer.jsx b/src/components/common/markdown/MarkdownRenderer.jsx
index df458fe5..3dc1f10e 100644
--- a/src/components/common/markdown/MarkdownRenderer.jsx
+++ b/src/components/common/markdown/MarkdownRenderer.jsx
@@ -70,6 +70,7 @@ export function Mermaid(props) {
// 等 setIsLoading(false) 触发重渲染时,React 找不到那些被 mermaid 删掉的节点,
// 就抛 removeChild "NotFoundError"。改用 mermaid.render() 拿 svg 字符串后写进 svgRef,
// React 始终认为 svgRef 这个 div 是空的,便不会与 mermaid 的 DOM 改动冲突。
+ const { t } = useTranslation();
const svgRef = useRef(null);
const [hasError, setHasError] = useState(false);
const [isLoading, setIsLoading] = useState(true);
@@ -164,7 +165,7 @@ export function Mermaid(props) {
animation: 'spin 1s linear infinite',
}}
/>
- 加载图表中...
+ {t('加载图表中...')}
)}
{/* React 视角下这个 div 恒为空,SVG 由 effect 通过 innerHTML 注入,互不干涉 */}
@@ -305,7 +306,7 @@ export function PreCode(props) {
color: 'var(--ui-color-text-2)',
}}
>
- HTML预览:
+ {t('HTML预览:')}
@@ -719,6 +720,7 @@ export function MarkdownRenderer(props) {
previousContentLength = 0,
...otherProps
} = props;
+ const { t } = useTranslation();
return (
- 正在渲染...
+ {t('正在渲染...')}
) : (
)}
diff --git a/src/components/common/ui/Loading.jsx b/src/components/common/ui/Loading.jsx
index a7f9cf82..827b9195 100644
--- a/src/components/common/ui/Loading.jsx
+++ b/src/components/common/ui/Loading.jsx
@@ -17,6 +17,7 @@ along with this program. If not, see .
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useEffect, useMemo, useState } from 'react';
+import i18next from 'i18next';
// 读品牌值:localStorage → window.__WL_BRAND__(index.html 内联脚本写入)→ 空。
// 不用 getSystemName/getLogo —— 它们的终极兜底是 'Weelinking' / '/logo.svg'(老品牌),
@@ -38,6 +39,7 @@ const readBrand = (key, windowKey) => {
// 加载文案根据浏览器语言决定,避免 i18n 还没初始化时硬编码中文。
const getLoadingText = () => {
+ if (i18next.isInitialized) return i18next.t('加载中...');
const lang = ((typeof navigator !== 'undefined' && navigator.language) || 'zh').toLowerCase();
return lang.startsWith('zh') ? '加载中...' : 'Loading...';
};
diff --git a/src/components/creation/CompareSummary.jsx b/src/components/creation/CompareSummary.jsx
new file mode 100644
index 00000000..88b82c77
--- /dev/null
+++ b/src/components/creation/CompareSummary.jsx
@@ -0,0 +1,148 @@
+/*
+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 .
+
+For commercial licensing, please contact support@quantumnous.com
+*/
+
+import React from 'react';
+import { Button, Modal, Spin } from '@douyinfe/semi-ui';
+import { AlertTriangle } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import { compareParamSummary } from '../../hooks/creation/creationCompare';
+import { formatQuoteAmount } from '../../hooks/creation/useCreationQuote';
+import { displayNameOf } from './ModelPicker';
+
+const amountOf = (item) =>
+ item && !item.error
+ ? formatQuoteAmount(item.display_amount, item.currency)
+ : '';
+
+/**
+ * 对比生成提交前摘要(WP C-2,方案 §4.2):逐模型"模型 · 实际参数 · 价格"与合计;
+ * 合计超过系统阈值时显示二次确认提示,确认按钮写明合计金额。
+ */
+const CompareSummary = ({ visible, compare, onCancel, onConfirm }) => {
+ const { t } = useTranslation();
+ const {
+ entries,
+ quote,
+ quoteLoading,
+ quoteFailed,
+ overThreshold,
+ submitting,
+ } = compare;
+ const items = quote?.items || [];
+ const total = quote
+ ? formatQuoteAmount(quote.display_amount, quote.currency)
+ : '';
+ const approximate = Boolean(
+ quote?.approximate || items.some((item) => item?.approximate),
+ );
+ const totalText = total
+ ? approximate
+ ? t('约 {{amount}}', { amount: total })
+ : total
+ : quoteLoading
+ ? t('正在估价...')
+ : t('价格以实际扣费为准');
+
+ return (
+
+
+ {t('取消')}
+
+
+ {total
+ ? t('确认生成(合计 {{amount}})', { amount: totalText })
+ : t('确认生成')}
+
+
+ }
+ >
+
+
+ {t(
+ '将用同一提示词分别提交 {{n}} 个模型,每个模型单独计费,失败自动退还',
+ {
+ n: entries.length,
+ },
+ )}
+
+
+ {entries.map((entry, i) => {
+ const amount = amountOf(items[i]);
+ const params = compareParamSummary(entry.payload);
+ return (
+
+
+ {displayNameOf(entry.model)}
+
+
+ {params || '-'}
+
+
+ {amount ? (
+ items[i]?.approximate ? (
+ t('约 {{amount}}', { amount })
+ ) : (
+ amount
+ )
+ ) : quoteLoading ? (
+
+ ) : (
+ '-'
+ )}
+
+ {entry.adjustments?.length ? (
+
+ {t('部分参数已按该模型调整')}
+
+ ) : null}
+
+ );
+ })}
+
+
+ {t('合计')}
+ {totalText}
+
+ {quoteFailed ? (
+
{t('估价失败,价格以实际扣费为准')}
+ ) : null}
+ {overThreshold ? (
+
+
+
{t('本次合计金额较高,请确认后再生成')}
+
+ ) : null}
+
+
+ );
+};
+
+export default CompareSummary;
diff --git a/src/components/creation/CreationDock.jsx b/src/components/creation/CreationDock.jsx
new file mode 100644
index 00000000..c5d65668
--- /dev/null
+++ b/src/components/creation/CreationDock.jsx
@@ -0,0 +1,1657 @@
+/*
+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 .
+
+For commercial licensing, please contact support@quantumnous.com
+*/
+
+import React, {
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ useSyncExternalStore,
+} from 'react';
+import { flushSync } from 'react-dom';
+import {
+ Button,
+ Dropdown,
+ Popover,
+ SideSheet,
+ Skeleton,
+ TextArea,
+ Tooltip,
+} from '@douyinfe/semi-ui';
+import {
+ AlertCircle,
+ ArrowLeft,
+ Bell,
+ BellOff,
+ ChevronDown,
+ ChevronUp,
+ Clapperboard,
+ History,
+ ImageIcon,
+ ImagePlus,
+ LayoutTemplate,
+ Lock,
+ MoreHorizontal,
+ Settings2,
+ Sparkles,
+ Wand2,
+ Wallet,
+ X,
+} from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import { useNavigate } from 'react-router-dom';
+import { showError, showInfo, showSuccess } from '../../helpers';
+import { StatusContext } from '../../context/Status';
+import { MODEL_CATEGORY } from '../../constants';
+import { templatesOf } from '../../constants/creationTemplates';
+import { ERROR_ACTIONS } from '../../helpers/creationError';
+import { trackCreationEvent } from '../../helpers/creationEvents';
+import { useIsMobile } from '../../hooks/common/useIsMobile';
+import { useModelSelector } from '../../hooks/models/useModelSelector';
+import { useOptimizePrompt } from '../../hooks/playground/useOptimizePrompt';
+import { formatQuoteAmount } from '../../hooks/creation/useCreationQuote';
+import { adapterOf } from '../../hooks/creation/creationForm';
+import { manualSubmitDecision } from '../../hooks/creation/creationCompare';
+import { openBatchConfirm } from './batchConfirm';
+import {
+ maybeRequestNotifyPermission,
+ setNotifyEnabled,
+ useNotifySetting,
+} from '../../hooks/creation/useCreationWatch';
+import {
+ ROLE_FRAMES,
+ backToImage2Video,
+ imageRefToken,
+ insertAt,
+ loadPromptHistory,
+ loadRoleMemory,
+ mappingAfterMove,
+ mappingAfterRemove,
+ missingFrameOf,
+ modeCapacity,
+ acceptsImages,
+ moveItem,
+ planImageUpload,
+ rememberRole,
+ rewriteImageRefs,
+ savePromptHistory,
+ suggestImageModel,
+ usesImageRefs,
+} from '../../hooks/creation/creationDock';
+import {
+ ImageSlot,
+ ParamRenderer,
+ isRandomSeed,
+ optionLabel,
+ optionValue,
+ paramLabel,
+} from './params';
+import ImageSizePicker from '../../pages/ExperienceCenter/components/AICreation/Image/ImageSizePicker';
+import ModelPicker, { displayNameOf } from './ModelPicker';
+import PortraitAssetPicker from '../../pages/ExperienceCenter/components/AICreation/Video/PortraitAssetPicker';
+import CompareSummary from './CompareSummary';
+import { sheetHeight } from './viewport';
+import './creation-dock.css';
+
+// 升级 / 充值入口(会员与充值同在钱包页)
+const TOPUP_PATH = '/console/topup';
+// 查看可用模型(模型超市)
+const MARKET_PATH = '/market';
+
+const IS_MAC =
+ typeof navigator !== 'undefined' &&
+ /Mac|iPhone|iPad/i.test(navigator.platform || navigator.userAgent || '');
+const SHORTCUT_LABEL = IS_MAC ? '⌘↵' : 'Ctrl+Enter';
+const SHORTCUT_ARIA = IS_MAC ? 'Meta+Enter' : 'Control+Enter';
+
+// 移动端(< md)与矮屏桌面(高度 < 800)使用收起 / 展开两态(方案 §4.1)
+const COMPACT_QUERY = '(max-width: 767px), (max-height: 799px)';
+const useCompactDock = () =>
+ useSyncExternalStore(
+ (callback) => {
+ const mql = window.matchMedia(COMPACT_QUERY);
+ mql.addEventListener('change', callback);
+ return () => mql.removeEventListener('change', callback);
+ },
+ () => window.matchMedia(COMPACT_QUERY).matches,
+ () => false,
+ );
+
+// 展开态期间隐藏体验中心的 MobileBottomNav(见 creation-dock.css)
+const BODY_EXPANDED_CLASS = 'cs-dock-expanded';
+
+// 可作为创作台 chip 的参数类型(textarea 等长内容只放在高级设置里)
+const CHIP_TYPES = new Set([
+ 'size',
+ 'ratio',
+ 'chips',
+ 'segmented',
+ 'select',
+ 'switch',
+ 'seed',
+ 'slider',
+]);
+
+// 选完即可收起弹层的单选型控件
+const PICK_AND_CLOSE = new Set(['ratio', 'chips', 'segmented', 'size']);
+
+const getStorage = () => {
+ try {
+ return window.localStorage;
+ } catch (e) {
+ return null;
+ }
+};
+
+// 弹层内点击 Select 下拉等其他 portal 时不关闭弹层
+const isInsideOtherPortal = (e) =>
+ Boolean(e?.target?.closest?.('.semi-portal, .semi-select-option-list'));
+
+/** 估价文案:"预计 ¥x · 约 N 秒 · 失败自动退还";估价失败 → "价格以实际扣费为准"。 */
+export const quoteText = (
+ t,
+ { quote, quoteLoading, quoteFailed, estSeconds },
+) => {
+ 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) return '';
+ parts.push(t('失败自动退还'));
+ return parts.join(' · ');
+};
+
+/** 对比生成的估价文案:"合计 预计 ¥x · N 个模型 · 失败自动退还"。 */
+export const compareQuoteText = (t, compare) => {
+ const q = compare.quote;
+ const amount = q ? formatQuoteAmount(q.display_amount, q.currency) : '';
+ const parts = [];
+ if (compare.quoteFailed || (q && !amount)) {
+ parts.push(t('价格以实际扣费为准'));
+ } else if (amount) {
+ const approximate = Boolean(
+ q.approximate || (q.items || []).some((i) => i?.approximate),
+ );
+ parts.push(
+ approximate
+ ? t('合计约 {{amount}}', { amount })
+ : t('合计 {{amount}}', { amount }),
+ );
+ } else if (compare.quoteLoading) {
+ parts.push(t('正在估价...'));
+ }
+ parts.push(t('{{n}} 个模型', { n: compare.models.length }));
+ parts.push(t('失败自动退还'));
+ return parts.join(' · ');
+};
+
+/** 参数 chip 上显示的取值。 */
+const chipValueText = (t, param, value) => {
+ if (param.type === 'size') {
+ return value ? String(value).replace(/x/i, '×') : t('尺寸');
+ }
+ if (param.type === 'switch') {
+ return `${paramLabel(t, param)} ${value ? t('开') : t('关')}`;
+ }
+ if (param.type === 'seed') {
+ return isRandomSeed(value)
+ ? `${paramLabel(t, param)} ${t('随机')}`
+ : `${paramLabel(t, param)} ${value}`;
+ }
+ if (Array.isArray(param.options) && param.options.length) {
+ const hit = param.options.find(
+ (o) => String(optionValue(o)) === String(value),
+ );
+ if (hit !== undefined) return optionLabel(t, param, hit);
+ }
+ if (value === undefined || value === null || value === '') {
+ return paramLabel(t, param);
+ }
+ return optionLabel(t, param, value);
+};
+
+/**
+ * 弹层:桌面 Popover,< md 底部 SideSheet。trigger 由调用方渲染并负责 onClick 切换。
+ */
+const DockPopover = ({
+ open,
+ onClose,
+ title,
+ isMobile,
+ sheetHeight = 'auto',
+ className = '',
+ children,
+ trigger,
+}) => {
+ if (isMobile) {
+ return (
+ <>
+ {trigger}
+
+ {open ? {children}
: null}
+
+ >
+ );
+ }
+ return (
+ {
+ if (!isInsideOtherPortal(e)) onClose();
+ }}
+ onEscKeyDown={onClose}
+ contentClassName={`cs-popover ${className}`}
+ content={
+ open ? (
+
+ {title ?
{title}
: null}
+ {children}
+
+ ) : null
+ }
+ >
+ {trigger}
+
+ );
+};
+
+/** 单个参数 chip:点击在弹层 / 底部抽屉中打开 ParamRenderer(或尺寸选择器)。 */
+const ParamChip = ({
+ param,
+ params,
+ values,
+ onChange,
+ constraints,
+ isMobile,
+}) => {
+ const { t } = useTranslation();
+ const [open, setOpen] = useState(false);
+ const label = paramLabel(t, param);
+ const value = values?.[param.key];
+ const handleChange = (key, v) => {
+ onChange(key, v);
+ if (PICK_AND_CLOSE.has(param.type)) setOpen(false);
+ };
+ // 只渲染当前参数,其余参数仍传入以便约束说明引用它们的名称
+ const scoped = useMemo(
+ () =>
+ params.map((p) =>
+ p.key === param.key
+ ? { ...p, placement: 'dock' }
+ : { ...p, placement: 'hidden' },
+ ),
+ [params, param.key],
+ );
+ const text = chipValueText(t, param, value);
+ return (
+ setOpen(false)}
+ title={label}
+ isMobile={isMobile}
+ trigger={
+ setOpen((v) => !v)}
+ >
+ {text}
+
+
+ }
+ >
+ {param.type === 'size' ? (
+
+ handleChange('size', v)}
+ />
+
+ ) : (
+
+ )}
+
+ );
+};
+
+/** 模板选择:静态模板,选中后填入提示词并套用推荐参数。 */
+const TemplatePicker = ({ kind, isMobile, onApply }) => {
+ const { t } = useTranslation();
+ const [open, setOpen] = useState(false);
+ const list = useMemo(() => templatesOf(kind), [kind]);
+ const Icon = kind === 'video' ? Clapperboard : ImageIcon;
+ if (!list.length) return null;
+ return (
+ setOpen(false)}
+ title={t('灵感模板')}
+ isMobile={isMobile}
+ sheetHeight={sheetHeight(70)}
+ className='cs-templates-pop'
+ trigger={
+ setOpen((v) => !v)}
+ >
+
+ {t('模板')}
+
+ }
+ >
+
+ {list.map((tpl) => (
+
+ {
+ onApply(tpl);
+ setOpen(false);
+ }}
+ >
+
+
+
+
+ {t(tpl.title)}
+ {tpl.prompt}
+
+
+
+ ))}
+
+
+ );
+};
+
+/**
+ * 底部创作台(WP B-3,方案 §4.1 / §4.3 / §4.4 / §4.6)。
+ *
+ * - 桌面(≥ md 且高度 ≥ 800):常驻完整创作台;
+ * - 移动端与矮屏桌面:收起态(一行提示词 + 模型 chip + 生成,约 56px)/ 展开态(覆盖作品流、
+ * 不挤压;展开期间隐藏 MobileBottomNav;弹层用底部抽屉;键盘弹起时跟随可视视口)。
+ *
+ * @param {{ form: ReturnType }} props
+ */
+const CreationDock = ({ form, compare = null }) => {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const [statusState] = useContext(StatusContext);
+ const notify = useNotifySetting();
+ const [summaryOpen, setSummaryOpen] = useState(false);
+ // 对比生成(WP C-2,仅图像):创作台只显示所选模型的共同参数,生成前展示逐模型摘要
+ const comparing = Boolean(compare?.active);
+ const isMobile = useIsMobile();
+ const promptFocusedRef = useRef(false);
+ const compact = useCompactDock();
+ const [expanded, setExpanded] = useState(false);
+ const [advancedOpen, setAdvancedOpen] = useState(false);
+ const [pending, setPending] = useState(null);
+ const [roleMemory, setRoleMemory] = useState(() =>
+ loadRoleMemory(getStorage(), form.kind),
+ );
+ const [promptHistory, setPromptHistory] = useState(() =>
+ loadPromptHistory(getStorage(), form.kind),
+ );
+ const dockRef = useRef(null);
+ const promptWrapRef = useRef(null);
+ const switchPendingRef = useRef(null);
+
+ const {
+ kind,
+ form: state,
+ creationData,
+ models,
+ modelsLoading,
+ modelsError,
+ reloadModels,
+ selectedModel,
+ selectModel,
+ mode,
+ modeOptions,
+ setMode,
+ prompt,
+ setPrompt,
+ params,
+ visibleParams,
+ setParam,
+ imageSlots,
+ pickImage,
+ removeImage,
+ retryImage,
+ setImages,
+ setImageRef,
+ submitBlock,
+ submitting,
+ submit,
+ budgetShortfall,
+ lastError,
+ clearError,
+ adjustments,
+ clearAdjustments,
+ applyTemplate,
+ allLocked,
+ } = form;
+
+ const { models: textModels } = useModelSelector(
+ MODEL_CATEGORY.TEXT_GENERATION,
+ );
+ const { optimizing, optimize } = useOptimizePrompt();
+
+ const modeLabels = adapterOf(kind).modeLabels;
+ const constraints = selectedModel?.constraints || [];
+ const images = state.images;
+ const refs = images.reference_images || [];
+ const showExpanded = !compact || expanded;
+ // 估价对应当前参数且已返回;参数刚变化(防抖 / 加载中)时旧估价不作数
+ const quoteFresh = form.quoteFresh !== false;
+ // 估价 dry-run 预算不足:个人钱包 → 按钮变"去充值";企业 / 令牌预算 → 说明是哪一级(不阻止提交)
+ // 估价未更新时保持中性状态,不按上一次参数的结果切换按钮
+ const needTopUp =
+ !submitBlock && quoteFresh && budgetShortfall?.personal === true;
+ const orgShortfall =
+ !submitBlock && quoteFresh && budgetShortfall && !budgetShortfall.personal
+ ? budgetShortfall
+ : null;
+ // 内容审核指明了触发的输入时,高亮对应槽位
+ const flaggedInput =
+ lastError?.category === 'moderation' ? lastError.input : null;
+ const priceText = comparing
+ ? compareQuoteText(t, compare)
+ : quoteText(t, form);
+ const blockText = comparing ? compare.blockReason : submitBlock;
+ const refMode = usesImageRefs(mode);
+ const missingFrame = missingFrameOf(kind, selectedModel, mode, images);
+ const canBackToI2V =
+ Boolean(missingFrame) && Boolean(backToImage2Video(selectedModel, images));
+ const modeHasImages = modeCapacity(kind, selectedModel, mode).max > 0;
+ const modelAcceptsImages = acceptsImages(kind, selectedModel);
+ // COS 关闭时视频不能上传本地图片(来自生成结果的引用仍可用,方案 §4.6)
+ const localUploadBlocked =
+ kind === 'video' && creationData?.image_input_enabled === false;
+ const uploadBlockedReason = localUploadBlocked
+ ? t('对象存储(COS)未开启,暂不支持上传图片')
+ : '';
+ const hasUnused = imageSlots.some((s) => s.slot && !s.active);
+
+ // 对比模式:参数取所选模型的交集,取值由对比状态维护,不做单模型约束联动
+ const chipParams = comparing ? compare.shared : visibleParams;
+ const chipValues = comparing ? compare.values : params;
+ const onChipChange = comparing ? compare.setValue : setParam;
+ const chipConstraints = comparing ? [] : constraints;
+ const dockParams = chipParams.filter(
+ (p) => (p.placement || 'dock') === 'dock' && CHIP_TYPES.has(p.type),
+ );
+ const hasAdvanced = chipParams.some((p) => p.placement === 'advanced');
+
+ // ---------------------------------------------------------------------------
+ // 收起 / 展开
+ // ---------------------------------------------------------------------------
+ const focusPrompt = useCallback(() => {
+ const el = promptWrapRef.current?.querySelector('textarea');
+ if (el) {
+ el.focus();
+ const len = el.value.length;
+ try {
+ el.setSelectionRange(len, len);
+ } catch (e) {
+ // 部分浏览器不支持
+ }
+ }
+ }, []);
+
+ const expand = useCallback(() => {
+ // 同步渲染后立即聚焦,保证移动端在同一手势内弹出键盘
+ flushSync(() => setExpanded(true));
+ focusPrompt();
+ }, [focusPrompt]);
+
+ const collapse = useCallback(() => {
+ setExpanded(false);
+ setAdvancedOpen(false);
+ }, []);
+
+ useEffect(() => {
+ if (!compact) setExpanded(false);
+ }, [compact]);
+
+ // 作品流的复用参数 / 编辑此图等操作后:展开创作台并聚焦提示词(WP B-6)
+ const focusTick = form.focusTick || 0;
+ const lastFocusTickRef = useRef(focusTick);
+ useEffect(() => {
+ if (focusTick === lastFocusTickRef.current) return;
+ lastFocusTickRef.current = focusTick;
+ if (compact) {
+ setExpanded(true);
+ requestAnimationFrame(focusPrompt);
+ } else {
+ focusPrompt();
+ }
+ }, [focusTick, compact, focusPrompt]);
+
+ useEffect(() => {
+ if (!(compact && expanded)) return undefined;
+ document.body.classList.add(BODY_EXPANDED_CLASS);
+ return () => document.body.classList.remove(BODY_EXPANDED_CLASS);
+ }, [compact, expanded]);
+
+ // 键盘弹起时可视视口变矮:展开态底部跟随可视视口,创作台与生成按钮保持可见
+ useEffect(() => {
+ if (!(compact && expanded)) return undefined;
+ const vv = window.visualViewport;
+ const el = dockRef.current;
+ if (!vv || !el) return undefined;
+ const update = () => {
+ const offset = Math.max(0, window.innerHeight - vv.height - vv.offsetTop);
+ el.style.setProperty('--cs-kb-offset', `${Math.round(offset)}px`);
+ };
+ update();
+ vv.addEventListener('resize', update);
+ vv.addEventListener('scroll', update);
+ return () => {
+ vv.removeEventListener('resize', update);
+ vv.removeEventListener('scroll', update);
+ };
+ }, [compact, expanded]);
+
+ // ---------------------------------------------------------------------------
+ // 提交
+ // ---------------------------------------------------------------------------
+ const confirmThreshold =
+ statusState?.status?.experience_center_batch_confirm_threshold;
+ const runSubmit = useCallback(async () => {
+ const submitted = prompt;
+ const ok = await submit();
+ if (ok) {
+ setPromptHistory((prev) =>
+ savePromptHistory(getStorage(), kind, prev, submitted),
+ );
+ }
+ if (ok && compact) collapse();
+ }, [submit, prompt, kind, compact, collapse]);
+
+ // 点了生成但估价尚未对应当前参数:等估价返回后再提交(见下方 effect)
+ const pendingSubmitRef = useRef(false);
+ const handleSubmit = useCallback(async () => {
+ if (comparing) {
+ if (compare.blockReason) {
+ showError(compare.blockReason);
+ return;
+ }
+ setSummaryOpen(true);
+ return;
+ }
+ if (needTopUp) {
+ navigate(TOPUP_PATH);
+ return;
+ }
+ // 开启了完成通知:首次提交时在用户手势内请求浏览器通知权限(WP C-4)
+ maybeRequestNotifyPermission();
+ // 多张生成合计超过系统阈值时二次确认(方案 §4.4 / 决策 3)。
+ // 估价仍是上一次参数的结果(如刚把张数从 1 改成 4)时不能据此跳过确认:等估价返回后再决定
+ const n = Number(form.payload?.n) || 1;
+ const quote = form.quote;
+ const decision = manualSubmitDecision({
+ n,
+ threshold: confirmThreshold,
+ quote,
+ quoteFresh,
+ quoteFailed: form.quoteFailed,
+ });
+ if (decision === 'wait') {
+ pendingSubmitRef.current = true;
+ showInfo(t('正在估价...'));
+ return;
+ }
+ pendingSubmitRef.current = false;
+ if (decision === 'confirm') {
+ openBatchConfirm({ t, n, quote, onOk: runSubmit });
+ return;
+ }
+ runSubmit();
+ }, [
+ comparing,
+ compare,
+ needTopUp,
+ navigate,
+ form.payload,
+ form.quote,
+ form.quoteFailed,
+ quoteFresh,
+ confirmThreshold,
+ runSubmit,
+ t,
+ ]);
+
+ // 等估价时点了生成:估价返回(对应当前参数)后按最新估价重新走一遍提交决策
+ useEffect(() => {
+ if (!pendingSubmitRef.current || !quoteFresh) return;
+ pendingSubmitRef.current = false;
+ if (comparing) return;
+ if (blockText) {
+ showError(blockText);
+ return;
+ }
+ handleSubmit();
+ }, [quoteFresh, comparing, blockText, handleSubmit]);
+
+ const confirmCompare = useCallback(async () => {
+ maybeRequestNotifyPermission();
+ const submitted = prompt;
+ const ok = await compare.submit();
+ setSummaryOpen(false);
+ if (ok) {
+ setPromptHistory((prev) =>
+ savePromptHistory(getStorage(), kind, prev, submitted),
+ );
+ if (compact) collapse();
+ }
+ }, [compare, prompt, kind, compact, collapse]);
+
+ const onPromptKeyDown = (e) => {
+ if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
+ e.preventDefault();
+ if (!blockText) handleSubmit();
+ else showError(blockText);
+ }
+ };
+
+ // ---------------------------------------------------------------------------
+ // 图片:先传图的模式推断 / 角色选择 / 不支持图片时建议换模型(方案 §4.4)
+ // ---------------------------------------------------------------------------
+ const placeFiles = useCallback(
+ async (plan, files) => {
+ // 已在图片模式但空槽不够时重新推断的模式:先按新模式重新排布已有图片
+ if (plan.images) setImages(plan.images);
+ if (plan.mode && plan.mode !== mode) setMode(plan.mode);
+ if (plan.truncated > 0) {
+ showInfo(
+ plan.targets.length
+ ? t('当前模式最多再放 {{n}} 张图片,其余 {{m}} 张未添加', {
+ n: plan.targets.length,
+ m: plan.truncated,
+ })
+ : t('当前模式的图片槽已满'),
+ );
+ }
+ for (let i = 0; i < plan.targets.length; i += 1) {
+ const target = plan.targets[i];
+ // eslint-disable-next-line no-await-in-loop
+ await pickImage(target.key, target.index, files[i]);
+ }
+ },
+ [mode, setMode, setImages, pickImage, t],
+ );
+
+ const handleFiles = useCallback(
+ (fileList) => {
+ const files = Array.from(fileList || []).filter(
+ (f) => f && (!f.type || f.type.startsWith('image/')),
+ );
+ if (!files.length || !selectedModel) return;
+ if (localUploadBlocked) {
+ showError(uploadBlockedReason);
+ return;
+ }
+ setPending(null);
+ const plan = planImageUpload({
+ kind,
+ model: selectedModel,
+ mode,
+ images,
+ count: files.length,
+ rememberedRole: roleMemory[selectedModel.model] || '',
+ });
+ if (plan.type === 'place') {
+ placeFiles(plan, files);
+ } else if (plan.type === 'choose') {
+ setPending({ type: 'choose', files, choices: plan.choices });
+ } else {
+ setPending({
+ type: 'unsupported',
+ files,
+ suggestion: suggestImageModel(
+ kind,
+ models,
+ selectedModel,
+ files.length,
+ ),
+ });
+ }
+ },
+ [
+ selectedModel,
+ localUploadBlocked,
+ uploadBlockedReason,
+ kind,
+ mode,
+ images,
+ roleMemory,
+ placeFiles,
+ models,
+ ],
+ );
+ const handleFilesRef = useRef(handleFiles);
+ handleFilesRef.current = handleFiles;
+
+ const chooseRole = (choice) => {
+ if (!pending || !selectedModel) return;
+ const files = pending.files;
+ setRoleMemory((prev) =>
+ rememberRole(getStorage(), kind, prev, selectedModel.model, choice.role),
+ );
+ setPending(null);
+ const plan = planImageUpload({
+ kind,
+ model: selectedModel,
+ mode,
+ images,
+ count: files.length,
+ rememberedRole: choice.role,
+ });
+ if (plan.type === 'place') placeFiles(plan, files);
+ };
+
+ // "切换到 X?":只在用户确认后换模型(换模型会改变价格),换完再放图
+ const acceptSuggestion = () => {
+ const target = pending?.suggestion;
+ if (!target) return;
+ switchPendingRef.current = { model: target.model, files: pending.files };
+ setPending(null);
+ if (!selectModel(target)) switchPendingRef.current = null;
+ };
+
+ useEffect(() => {
+ const p = switchPendingRef.current;
+ if (!p || selectedModel?.model !== p.model) return;
+ switchPendingRef.current = null;
+ handleFilesRef.current(p.files);
+ }, [selectedModel]);
+
+ // 视频真人人像认证素材(asset://)放入首帧槽(保留旧视频页能力,方案 §1.3)
+ const firstFrameRef = String(images.first_frame?.ref || '');
+ const portraitRef = firstFrameRef.startsWith('asset://') ? firstFrameRef : '';
+ const selectPortrait = (asset) => {
+ if (!asset?.id) return;
+ setImageRef('first_frame', undefined, {
+ ref: `asset://${asset.id}`,
+ previewUrl: asset.preview_url || null,
+ source: 'asset',
+ });
+ };
+
+ const handleRemove = (entry) => {
+ if (entry.key === 'reference_images' && refMode) {
+ const next = rewriteImageRefs(
+ prompt,
+ mappingAfterRemove(refs.length, entry.index),
+ );
+ if (next !== prompt) setPrompt(next);
+ }
+ removeImage(entry.key, entry.index);
+ };
+
+ const handleMoveRef = (from, to) => {
+ if (refMode) {
+ const next = rewriteImageRefs(
+ prompt,
+ mappingAfterMove(refs.length, from, to),
+ );
+ if (next !== prompt) setPrompt(next);
+ }
+ setImages({ ...images, reference_images: moveItem(refs, from, to) });
+ };
+
+ const insertRef = (n) => {
+ const el = promptWrapRef.current?.querySelector('textarea');
+ const caret = el ? el.selectionStart : undefined;
+ const r = insertAt(prompt, caret, imageRefToken(n));
+ setPrompt(r.text);
+ requestAnimationFrame(() => {
+ const ta = promptWrapRef.current?.querySelector('textarea');
+ if (!ta) return;
+ ta.focus();
+ try {
+ ta.setSelectionRange(r.caret, r.caret);
+ } catch (e) {
+ // ignore
+ }
+ });
+ };
+
+ const backToI2V = () => {
+ const r = backToImage2Video(selectedModel, images);
+ if (!r) return;
+ setImages(r.images);
+ setMode(r.mode);
+ };
+
+ const onDockDragOver = (e) => {
+ if (e.dataTransfer?.types?.includes?.('Files')) e.preventDefault();
+ };
+ const onDockDrop = (e) => {
+ // 图片槽自己处理过的拖放不再重复放置
+ if (e.defaultPrevented || !e.dataTransfer?.files?.length) return;
+ e.preventDefault();
+ handleFiles(e.dataTransfer.files);
+ };
+ const onPromptPaste = (e) => {
+ const files = Array.from(e.clipboardData?.files || []).filter((f) =>
+ f.type.startsWith('image/'),
+ );
+ if (!files.length) return;
+ e.preventDefault();
+ handleFiles(files);
+ };
+
+ const addInputRef = useRef(null);
+
+ // ---------------------------------------------------------------------------
+ // 模板 / 优化提示词
+ // ---------------------------------------------------------------------------
+ const handleTemplate = (tpl) => {
+ if (applyTemplate(tpl)) {
+ showSuccess(t('已套用模板:{{title}}', { title: t(tpl.title) }));
+ }
+ };
+
+ const onPromptFocus = () => {
+ // 每次进入创作页只记一次
+ if (promptFocusedRef.current) return;
+ promptFocusedRef.current = true;
+ trackCreationEvent('prompt_focus', { kind });
+ };
+
+ // 错误行的下一步动作
+ const runErrorAction = (action) => {
+ if (action === ERROR_ACTIONS.TOPUP) {
+ navigate(TOPUP_PATH);
+ return;
+ }
+ if (action === ERROR_ACTIONS.RETRY) {
+ handleSubmit();
+ return;
+ }
+ if (action === ERROR_ACTIONS.REPLACE_IMAGE) {
+ const el = dockRef.current?.querySelector(
+ '.cs-slot.is-flagged, .cp-slot.is-expired, .cs-slot',
+ );
+ if (el) {
+ el.focus();
+ return;
+ }
+ }
+ focusPrompt();
+ };
+
+ const handleOptimize = async () => {
+ if (optimizing) return;
+ if (!prompt.trim()) {
+ showInfo(t('请先输入提示词'));
+ return;
+ }
+ const modelName = textModels?.[0]?.model_name;
+ if (!modelName) {
+ showInfo(t('未配置文本模型,无法 AI 优化。请联系管理员开通文本模型权限'));
+ return;
+ }
+ const result = await optimize(prompt, modelName);
+ if (result?.content) {
+ setPrompt(result.content);
+ showSuccess(t('已优化提示词'));
+ } else if (result?.error) {
+ showError(result.error);
+ }
+ };
+
+ // ---------------------------------------------------------------------------
+ // 渲染
+ // ---------------------------------------------------------------------------
+ if (modelsLoading && !models.length) {
+ return (
+
+ }
+ />
+
+ );
+ }
+ if (modelsError && !models.length) {
+ return (
+
+ {t('模型列表加载失败')}
+ reloadModels()}>
+ {t('重试')}
+
+
+ );
+ }
+ if (!models.length) {
+ return (
+
+ {t('当前分组暂无可用模型,请联系管理员开通')}
+ navigate(MARKET_PATH)}>
+ {t('查看可用模型')}
+
+
+ );
+ }
+
+ const modelPicker = (
+ selectModel(m)}
+ params={params}
+ mode={mode}
+ loading={modelsLoading}
+ error={modelsError}
+ onRetry={reloadModels}
+ compare={compare?.supported ? compare : null}
+ />
+ );
+
+ const generateButton = (collapsedBar) => {
+ if (allLocked) {
+ return (
+ }
+ onClick={() => navigate(TOPUP_PATH)}
+ >
+ {t('升级')}
+
+ );
+ }
+ if (needTopUp && !comparing) {
+ return (
+ }
+ onClick={() => navigate(TOPUP_PATH)}
+ >
+ {t('去充值')}
+
+ );
+ }
+ // 收起态下被阻断时点击展开,让用户看到原因
+ const blocked = Boolean(blockText);
+ const button = (
+ }
+ disabled={blocked && !collapsedBar}
+ aria-disabled={blocked || undefined}
+ loading={comparing ? compare.submitting : submitting}
+ data-guide='generate'
+ onClick={() => {
+ if (blocked) {
+ if (collapsedBar) expand();
+ return;
+ }
+ handleSubmit();
+ }}
+ aria-keyshortcuts={SHORTCUT_ARIA}
+ >
+ {comparing ? t('对比生成') : t('生成')}
+ {!collapsedBar ? (
+
+ {SHORTCUT_LABEL}
+
+ ) : null}
+
+ );
+ return blocked && !collapsedBar ? (
+
+ {button}
+
+ ) : (
+ button
+ );
+ };
+
+ const compareSummary = comparing ? (
+ {
+ if (!compare.submitting) setSummaryOpen(false);
+ }}
+ onConfirm={confirmCompare}
+ />
+ ) : null;
+
+ // 收起态:一行提示词 + 模型 chip + 生成
+ if (!showExpanded) {
+ return (
+
+
+
+ {prompt ||
+ (kind === 'image'
+ ? t('描述你想要的画面…')
+ : t('描述你想要的视频画面与运动…'))}
+
+
+
+
{modelPicker}
+ {generateButton(true)}
+ {compareSummary}
+
+ );
+ }
+
+ const slotLabel = (entry) =>
+ entry.labelIndex ? `${t(entry.label)} ${entry.labelIndex}` : t(entry.label);
+
+ const modeChip =
+ modeOptions.length > 1 ? (
+
+ {modeOptions.map((o) => (
+ {
+ if (!o.disabled) setMode(o.mode);
+ }}
+ >
+
+ {t(modeLabels[o.mode] || o.mode)}
+ {o.disabled && o.reason ? (
+ {t(o.reason)}
+ ) : null}
+
+
+ ))}
+
+ }
+ >
+
+ {t(modeLabels[mode] || mode)}
+
+
+
+ ) : modeOptions.length === 1 ? (
+
+ {t(modeLabels[mode] || mode)}
+
+ ) : null;
+
+ const pendingBox = pending ? (
+
+ {pending.type === 'choose' ? (
+ <>
+
+ {t('已选 {{n}} 张图片,用作:', { n: pending.files.length })}
+
+ {pending.choices.map((c) => (
+ chooseRole(c)}
+ >
+ {c.role === ROLE_FRAMES
+ ? c.mode === 'image2video'
+ ? t('作为首帧')
+ : t('作为首尾帧')
+ : t('作为参考图')}
+
+ ))}
+ >
+ ) : (
+ <>
+
+ {pending.suggestion
+ ? t('该模型不支持图片输入,切换到 {{name}}?', {
+ name: displayNameOf(pending.suggestion),
+ })
+ : t('该模型不支持图片输入,请先选择支持图片的模型')}
+
+ {pending.suggestion ? (
+
+ {t('切换')}
+
+ ) : null}
+ >
+ )}
+ setPending(null)}
+ >
+ {t('取消')}
+
+
+ ) : null;
+
+ const showInputsRow =
+ modeChip || imageSlots.length || modelAcceptsImages || pending;
+
+ return (
+ <>
+ {compact ? (
+ <>
+
+
+ >
+ ) : null}
+ {
+ if (compact && e.key === 'Escape' && !e.defaultPrevented) {
+ collapse();
+ }
+ }}
+ >
+ {compact ? (
+
+ {t('创作')}
+
+
+
+
+ ) : null}
+
+ {showInputsRow ? (
+
+ {modeChip}
+ {imageSlots.length ? (
+
+ {imageSlots.map((entry) => {
+ const slot = entry.slot;
+ const value = slot
+ ? {
+ previewUrl: slot.previewUrl,
+ status: entry.active
+ ? slot.status || 'ready'
+ : 'unused',
+ error: slot.error,
+ }
+ : null;
+ const isMissing = !slot && entry.key === missingFrame;
+ const isFlagged = Boolean(
+ slot &&
+ flaggedInput &&
+ entry.key === flaggedInput.key &&
+ (flaggedInput.index === undefined ||
+ entry.index === flaggedInput.index),
+ );
+ const movable =
+ entry.key === 'reference_images' && slot && entry.index > 0;
+ return (
+
+
+ pickImage(entry.key, entry.index, file)
+ }
+ onRemove={() => handleRemove(entry)}
+ onRetry={() => retryImage(entry.key, entry.index, slot)}
+ />
+ {movable ? (
+
+ handleMoveRef(entry.index, entry.index - 1)
+ }
+ aria-label={t('将{{label}}前移', {
+ label: slotLabel(entry),
+ })}
+ title={t('前移')}
+ >
+
+
+ ) : null}
+
+ );
+ })}
+
+ ) : null}
+ {kind === 'video' &&
+ imageSlots.some((s) => s.key === 'first_frame' && s.active) ? (
+
+
{
+ if (portraitRef) removeImage('first_frame');
+ }}
+ />
+
+ ) : null}
+ {modelAcceptsImages && !modeHasImages ? (
+ <>
+
addInputRef.current?.click()}
+ >
+
+ {t('添加图片')}
+
+
{
+ handleFiles(e.target.files);
+ e.target.value = '';
+ }}
+ />
+ >
+ ) : null}
+ {pendingBox}
+ {missingFrame ? (
+
+ {missingFrame === 'last_frame' ? t('缺少尾帧') : t('缺少首帧')}
+ {canBackToI2V ? (
+
+ {t('改用图生视频')}
+
+ ) : null}
+
+ ) : null}
+ {hasUnused ? (
+
+ {t('置灰的图片当前不会提交,切回支持的模型或模式后自动恢复')}
+
+ ) : null}
+
+ ) : null}
+
+ {refMode && refs.length ? (
+
+ {t('在提示词中引用:')}
+ {refs.map((r, i) => (
+ insertRef(i + 1)}
+ >
+ {imageRefToken(i + 1)}
+
+ ))}
+
+ ) : null}
+
+
+
+
+
+
+ {modelPicker}
+ {dockParams.map((p) => (
+
+ ))}
+ {hasAdvanced ? (
+
setAdvancedOpen(false)}
+ title={t('高级设置')}
+ isMobile={isMobile}
+ sheetHeight={sheetHeight(70)}
+ className='cs-advanced-pop'
+ trigger={
+ setAdvancedOpen((v) => !v)}
+ >
+
+ {t('高级')}
+
+ }
+ >
+
+
+ ) : null}
+
+ {promptHistory.length ? (
+
+ {t('最近使用的提示词')}
+ {promptHistory.map((item) => (
+ {
+ setPrompt(item);
+ requestAnimationFrame(focusPrompt);
+ }}
+ >
+
+ {item}
+
+
+ ))}
+
+ }
+ >
+
+
+ {t('历史')}
+
+
+ ) : null}
+
+
+
+ {optimizing ? t('优化中...') : t('优化')}
+
+ {notify.supported ? (
+
+
+ ) : (
+
+ )
+ }
+ onClick={() => {
+ const next = !notify.enabled;
+ setNotifyEnabled(next);
+ if (next && notify.permission === 'denied') {
+ showInfo(
+ t('浏览器已禁止本站通知,请在浏览器设置中允许后再试'),
+ );
+ } else if (next) {
+ showSuccess(
+ t(
+ '已开启:生成完成后发送浏览器通知(需保持标签页打开)',
+ ),
+ );
+ }
+ }}
+ >
+ {notify.enabled ? t('关闭完成通知') : t('完成后浏览器通知')}
+
+
+ }
+ >
+
+
+ {notify.enabled ? (
+
+ ) : null}
+
+
+ ) : null}
+
+
+ {allLocked ? (
+
+
+
+ {t('当前等级暂无可用模型,升级后即可使用')}
+
+
+ ) : null}
+
+ {orgShortfall ? (
+
+
+
+ {t('{{budget}},提交可能失败,请联系企业管理员', {
+ budget: t(orgShortfall.labelKey),
+ })}
+
+
+ ) : null}
+
+ {adjustments?.length ? (
+
+
+ {t('已按当前模型调整:{{list}}', {
+ list: adjustments.join(';'),
+ })}
+
+
+
+
+
+ ) : null}
+
+ {lastError ? (
+
+
+
+ {lastError.title}
+ {lastError.detail ? {lastError.detail} : null}
+
+ {lastError.actionLabel ? (
+
runErrorAction(lastError.action)}
+ >
+ {lastError.actionLabel}
+
+ ) : null}
+
+
+
+
+ ) : null}
+
+
+
+ {blockText ? (
+ {blockText}
+ ) : (
+ priceText
+ )}
+
+ {generateButton(false)}
+
+
+ {compareSummary}
+ >
+ );
+};
+
+export default CreationDock;
diff --git a/src/components/creation/CreationGuide.jsx b/src/components/creation/CreationGuide.jsx
new file mode 100644
index 00000000..64ca524a
--- /dev/null
+++ b/src/components/creation/CreationGuide.jsx
@@ -0,0 +1,178 @@
+/*
+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 .
+
+For commercial licensing, please contact support@quantumnous.com
+*/
+
+import React, { useEffect, useMemo, useState } from 'react';
+import Joyride, { EVENTS, STATUS } from 'react-joyride';
+import { useTranslation } from 'react-i18next';
+
+// 首次引导(WP C-4,方案 §4.4):3 步轻引导(写描述 → 选模型 → 生成),复用秘钥管理页
+// 已有的新手引导能力(react-joyride)。每种创作页只展示一次(localStorage)。
+export const guideStorageKeyOf = (kind) => `creation.${kind}.guide.v1`;
+
+const readSeen = (kind) => {
+ try {
+ return window.localStorage.getItem(guideStorageKeyOf(kind)) === '1';
+ } catch (e) {
+ // 存储不可用时不展示,避免每次进入都弹
+ return true;
+ }
+};
+
+const writeSeen = (kind) => {
+ try {
+ window.localStorage.setItem(guideStorageKeyOf(kind), '1');
+ } catch (e) {
+ // ignore
+ }
+};
+
+// 引导目标:收起态 / 展开态都带 data-guide;模型选择器为创作台内的触发 chip
+const TARGETS = {
+ prompt: '.cs-dock-wrap [data-guide="prompt"]',
+ model: '.cs-dock-wrap .mp-trigger',
+ generate: '.cs-dock-wrap [data-guide="generate"]',
+};
+
+const StepBody = ({ index, title, text }) => (
+
+
+
+ {index}
+
+ {title}
+
+
{text}
+
+);
+
+/**
+ * @param {{ kind: 'image'|'video', ready: boolean }} props
+ * ready:模型列表已加载、创作台已渲染(引导目标存在)时才开始
+ */
+const CreationGuide = ({ kind, ready }) => {
+ const { t } = useTranslation();
+ const [run, setRun] = useState(false);
+
+ useEffect(() => {
+ if (!ready || readSeen(kind)) return undefined;
+ // 等创作台布局稳定(展开 / 收起态判定、字体加载)后再开始
+ const timer = setTimeout(() => setRun(true), 800);
+ return () => clearTimeout(timer);
+ }, [ready, kind]);
+
+ const steps = useMemo(
+ () => [
+ {
+ target: TARGETS.prompt,
+ disableBeacon: true,
+ placement: 'top',
+ content: (
+
+ ),
+ },
+ {
+ target: TARGETS.model,
+ placement: 'top',
+ content: (
+
+ ),
+ },
+ {
+ target: TARGETS.generate,
+ placement: 'top',
+ content: (
+
+ ),
+ },
+ ],
+ [kind, t],
+ );
+
+ const handleCallback = ({ status, type }) => {
+ if (
+ status === STATUS.FINISHED ||
+ status === STATUS.SKIPPED ||
+ type === EVENTS.TOUR_END
+ ) {
+ writeSeen(kind);
+ setRun(false);
+ }
+ // 目标不存在(如移动端收起态布局变化):直接结束,不再打扰
+ if (type === EVENTS.TARGET_NOT_FOUND) {
+ writeSeen(kind);
+ setRun(false);
+ }
+ };
+
+ if (!run) return null;
+ return (
+
+ );
+};
+
+export default CreationGuide;
diff --git a/src/components/creation/CreationStudio.jsx b/src/components/creation/CreationStudio.jsx
new file mode 100644
index 00000000..821fefa1
--- /dev/null
+++ b/src/components/creation/CreationStudio.jsx
@@ -0,0 +1,225 @@
+/*
+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 .
+
+For commercial licensing, please contact support@quantumnous.com
+*/
+
+import React, {
+ useCallback,
+ useContext,
+ useEffect,
+ useRef,
+ useState,
+} from 'react';
+import { useTranslation } from 'react-i18next';
+import { useLocation, useNavigate } from 'react-router-dom';
+import { UserContext } from '../../context/User';
+import { renderQuota, showError } from '../../helpers';
+import {
+ flushCreationEvents,
+ trackCreationEvent,
+} from '../../helpers/creationEvents';
+import { useCreationForm } from '../../hooks/creation/useCreationForm';
+import { useCreationTasks } from '../../hooks/creation/useCreationTasks';
+import { useCreationCompare } from '../../hooks/creation/useCreationCompare';
+import { useStudioWatch } from '../../hooks/creation/useCreationWatch';
+import { isModeEnabled } from '../../hooks/video/videoCreation';
+import { useExperienceModules } from '../../pages/ExperienceCenter/useExperienceModules';
+import CreationDock from './CreationDock';
+import CreationGuide from './CreationGuide';
+import WorkFeed from './WorkFeed/WorkFeed';
+import FilterBar from './WorkFeed/FilterBar';
+import './creation.css';
+
+const TITLES = { image: '图像生成', video: '视频生成' };
+const VIDEO_STUDIO_PATH = '/experience-center/video-generation';
+
+/**
+ * 跨页带图(WP C-3,方案 §4.4):图像页"用作视频首帧"经路由 state 带来 task:// 引用,
+ * 模型列表就绪后放入视频创作台的首帧槽并切到图生视频,不覆盖草稿中已有的提示词;
+ * 当前模型不支持图生视频时换到第一个支持的模型。处理完清掉路由 state(刷新不重复放入)。
+ */
+const useIncomingFirstFrame = (kind, form) => {
+ const { t } = useTranslation();
+ const location = useLocation();
+ const navigate = useNavigate();
+ const pendingRef = useRef(
+ kind === 'video' && location.state?.firstFrameRef
+ ? {
+ ref: String(location.state.firstFrameRef),
+ previewUrl: location.state.firstFramePreview || null,
+ }
+ : null,
+ );
+ const { modelsLoading, selectedModel, models, prefill } = form;
+ useEffect(() => {
+ const incoming = pendingRef.current;
+ if (!incoming || modelsLoading || !selectedModel) return;
+ pendingRef.current = null;
+ navigate(`${location.pathname}${location.search}`, {
+ replace: true,
+ state: null,
+ });
+ const target = isModeEnabled(selectedModel, 'image2video')
+ ? selectedModel
+ : models.find((m) => !m.level_locked && isModeEnabled(m, 'image2video'));
+ if (!target) {
+ showError(t('当前没有可用的图生视频模型'));
+ return;
+ }
+ const same = target.model === selectedModel.model;
+ prefill(
+ {
+ modelName: target.model,
+ mode: 'image2video',
+ // 同一模型保留当前参数;换模型时按该模型的记忆(缺省项由 schema 默认值补齐)
+ params: same
+ ? form.params
+ : { ...(form.form.paramMemory?.[target.model] || {}) },
+ images: {
+ ...form.form.images,
+ first_frame: {
+ id: `slot-in-${Date.now().toString(36)}`,
+ status: 'ready',
+ ref: incoming.ref,
+ previewUrl: incoming.previewUrl,
+ source: 'task',
+ identityType: 'aigc',
+ },
+ },
+ },
+ {
+ notice: same
+ ? t('已放入首帧,提示词保持不变')
+ : t('已放入首帧,并切换到支持图生视频的模型 {{name}}', {
+ name: target.display_name || target.model,
+ }),
+ },
+ );
+ // 只在模型就绪时执行一次
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [modelsLoading, selectedModel]);
+};
+
+/** 外壳布局:头部(标题 + 筛选栏 + 余额)/ 全宽作品流 / 底部创作台。 */
+const StudioLayout = ({ kind, filterBar, feed, dock, guide }) => {
+ const { t } = useTranslation();
+ const [userState] = useContext(UserContext);
+ const quota = userState?.user?.quota;
+ return (
+
+ );
+};
+
+/**
+ * 新创作台外壳(WP B-2)+ 创作台 CreationDock(WP B-3)+ 作品流 WorkFeed(WP B-6)。
+ * 任务列表与轮询只由 useCreationTasks 负责(不再挂载旧的 useImageTaskManagement / useVideoGeneration)。
+ * @param {{ kind: 'image'|'video' }} props
+ */
+const CreationStudio = ({ kind = 'image' }) => {
+ const tasksApi = useCreationTasks(kind);
+ const { addSubmitted } = tasksApi;
+ const onSubmitted = useCallback(
+ (result, payload) => addSubmitted(result, payload),
+ [addSubmitted],
+ );
+ const form = useCreationForm(kind, {
+ onSubmitted,
+ localRunning: tasksApi.runningCount,
+ });
+ // 图像对比生成(WP C-2):同一 batch_id 的多个任务逐个乐观插入作品流
+ const compare = useCreationCompare(form, { onSubmitted });
+ const [selecting, setSelecting] = useState(false);
+ const navigate = useNavigate();
+ const { isAvailable } = useExperienceModules();
+
+ // 完成提醒(WP C-4):本页挂载期间后台轮询跳过该 kind,进入 / 离开时清空侧边栏未读
+ useStudioWatch(kind);
+ useIncomingFirstFrame(kind, form);
+
+ // 图像"用作视频首帧":带 task:// 引用跳到视频创作台(视频模块关闭时不显示)
+ const sendToVideoFirstFrame = useCallback(
+ (task, ref, previewUrl) =>
+ navigate(VIDEO_STUDIO_PATH, {
+ state: { firstFrameRef: ref, firstFramePreview: previewUrl || null },
+ }),
+ [navigate],
+ );
+ const canUseVideo = kind === 'image' && isAvailable('videoGeneration');
+
+ // 埋点:进入创作页记 studio_view,离开时立即发送队列中的事件
+ useEffect(() => {
+ trackCreationEvent('studio_view', { kind });
+ return () => flushCreationEvents();
+ }, [kind]);
+
+ return (
+ setSelecting((v) => !v) : undefined
+ }
+ />
+ }
+ feed={
+
+ }
+ dock={ }
+ guide={
+ 0}
+ />
+ }
+ />
+ );
+};
+
+export default CreationStudio;
diff --git a/src/components/creation/ModelPicker/ModelPicker.jsx b/src/components/creation/ModelPicker/ModelPicker.jsx
new file mode 100644
index 00000000..f2c71559
--- /dev/null
+++ b/src/components/creation/ModelPicker/ModelPicker.jsx
@@ -0,0 +1,184 @@
+/*
+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 .
+
+For commercial licensing, please contact support@quantumnous.com
+*/
+
+import React, { useCallback, useEffect, useRef, useState } from 'react';
+import { Popover, SideSheet } from '@douyinfe/semi-ui';
+import { ChevronDown, Lock } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import { useIsMobile } from '../../../hooks/common/useIsMobile';
+import ModelPickerPanel from './ModelPickerPanel';
+import { displayNameOf, loadRecent, pushRecent } from './modelPickerUtils';
+import { sheetHeight } from '../viewport';
+import './model-picker.css';
+
+const getStorage = () => {
+ try {
+ return window.localStorage;
+ } catch (e) {
+ return null;
+ }
+};
+
+/**
+ * 模型选择器(WP B-4):触发 chip + 桌面弹层 / 移动端(< md)底部抽屉。
+ *
+ * props:
+ * kind 'image' | 'video'
+ * models schema.models[]
+ * value 当前模型名
+ * onChange(model) 选中可调用的模型(等级锁定的模型不会回调,改为显示升级入口)
+ * params 当前参数取值(用于显示对应档位单价)
+ * mode 当前模式(用于判定不兼容模型)
+ * loading / error / onRetry schema 加载状态
+ * disabled
+ * compare 对比生成(WP C-2,仅图像):{ active, names, blockOf(model), toggleModel(model),
+ * setEnabled(on) }。开启后卡片变为多选(2~4 个),点击勾选而不关闭弹层
+ */
+const ModelPicker = ({
+ kind = 'video',
+ models = [],
+ value = '',
+ onChange,
+ params = {},
+ mode = '',
+ loading = false,
+ error = null,
+ onRetry,
+ disabled = false,
+ className = '',
+ compare = null,
+}) => {
+ const { t } = useTranslation();
+ const isMobile = useIsMobile();
+ const [open, setOpen] = useState(false);
+ const [recent, setRecent] = useState(() => loadRecent(getStorage(), kind));
+ const triggerRef = useRef(null);
+
+ useEffect(() => {
+ setRecent(loadRecent(getStorage(), kind));
+ }, [kind]);
+
+ const selected = models.find((m) => m.model === value) || null;
+
+ const close = useCallback(() => {
+ setOpen(false);
+ // 关闭后焦点回到触发按钮
+ requestAnimationFrame(() => triggerRef.current?.focus?.());
+ }, []);
+
+ const comparing = Boolean(compare?.active);
+ const handleSelect = useCallback(
+ (model) => {
+ if (!model || model.level_locked) return;
+ if (comparing) {
+ compare.toggleModel(model);
+ return;
+ }
+ setRecent((prev) => pushRecent(getStorage(), kind, model.model, prev));
+ if (onChange) onChange(model);
+ close();
+ },
+ [kind, onChange, close, comparing, compare],
+ );
+
+ const panel = (
+
+ );
+
+ const label = comparing
+ ? t('对比 {{n}} 个模型', { n: compare.names.length })
+ : selected
+ ? displayNameOf(selected)
+ : loading
+ ? t('模型列表加载中')
+ : t('选择模型');
+
+ const trigger = (
+ setOpen((v) => !v)}
+ >
+ {selected?.level_locked ? : null}
+ {label}
+
+
+ );
+
+ if (isMobile) {
+ return (
+ <>
+ {trigger}
+
+ {open ? panel : null}
+
+ >
+ );
+ }
+
+ return (
+ setOpen(false)}
+ onEscKeyDown={close}
+ content={open ? panel : null}
+ contentClassName='mp-popover'
+ >
+ {trigger}
+
+ );
+};
+
+export default ModelPicker;
diff --git a/src/components/creation/ModelPicker/ModelPickerPanel.jsx b/src/components/creation/ModelPicker/ModelPickerPanel.jsx
new file mode 100644
index 00000000..3dfe6597
--- /dev/null
+++ b/src/components/creation/ModelPicker/ModelPickerPanel.jsx
@@ -0,0 +1,437 @@
+/*
+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 .
+
+For commercial licensing, please contact support@quantumnous.com
+*/
+
+import React, { useEffect, useId, useMemo, useRef, useState } from 'react';
+import { Button, Skeleton, Switch } from '@douyinfe/semi-ui';
+import { Check, Clock, Columns2, Lock, Search, Square } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import { useNavigate } from 'react-router-dom';
+import { formatQuoteAmount } from '../../../hooks/creation/useCreationQuote';
+import {
+ OTHER_GROUP,
+ RECENT_GROUP,
+ badgesOf,
+ capabilityTags,
+ displayNameOf,
+ flattenOptions,
+ groupModels,
+ incompatibilityOf,
+ moveActive,
+ unitPriceOf,
+} from './modelPickerUtils';
+
+// 等级不足时的升级入口(会员与充值同在钱包页)
+const UPGRADE_PATH = '/console/topup';
+
+const ModelCard = ({
+ kind,
+ model,
+ option,
+ active,
+ selected,
+ params,
+ mode,
+ onPick,
+ onHover,
+ compare = null,
+}) => {
+ const { t } = useTranslation();
+ const locked = Boolean(model.level_locked);
+ const comparing = Boolean(compare?.active);
+ // 对比模式:只有支持当前模式与已上传图片的模型可勾选
+ const compareBlock = comparing && !locked ? compare.blockOf(model) : null;
+ const incompatible = locked
+ ? null
+ : comparing
+ ? compareBlock
+ : incompatibilityOf(kind, model, { mode });
+ const tags = capabilityTags(kind, model);
+ const badges = badgesOf(model);
+ const price = unitPriceOf(model, params);
+ const amount = price ? formatQuoteAmount(price.amount, price.currency) : '';
+ const p50 = Number(model.est_seconds?.p50) || 0;
+
+ const cls = [
+ 'mp-card',
+ active ? 'is-active' : '',
+ selected ? 'is-selected' : '',
+ locked ? 'is-locked' : '',
+ incompatible ? 'is-incompatible' : '',
+ ]
+ .filter(Boolean)
+ .join(' ');
+
+ return (
+ e.preventDefault()}
+ onClick={() => onPick(model)}
+ onMouseMove={onHover}
+ >
+
+
+ {displayNameOf(model)}
+
+ {badges.map((b) => (
+
+ {t(b.label)}
+
+ ))}
+ {locked ? (
+
+
+ {t('需升级')}
+
+ ) : null}
+ {comparing ? (
+
+ {selected ? : }
+
+ ) : selected ? (
+
+ ) : null}
+
+ {model.description ? (
+
+ {model.description}
+
+ ) : null}
+ {tags.length ? (
+
+ {tags.map((tag) => (
+
+ {t(tag.label, tag.values)}
+
+ ))}
+
+ ) : null}
+ {amount || p50 > 0 || incompatible ? (
+
+ {amount ? (
+
+ {price.unitLabel
+ ? t('{{amount}}/{{unit}}', {
+ amount,
+ unit: t(price.unitLabel),
+ })
+ : amount}
+ {price.tier ? ` · ${price.tier}` : ''}
+
+ ) : null}
+ {p50 > 0 ? (
+
+
+ {t('约 {{n}} 秒', { n: p50 })}
+
+ ) : null}
+ {incompatible ? (
+
+ {comparing
+ ? t(incompatible.key, incompatible.values)
+ : t(incompatible.key, {
+ mode: t(incompatible.values.mode),
+ })}
+
+ ) : null}
+
+ ) : null}
+
+ );
+};
+
+/**
+ * 模型列表面板(组合框模式):焦点留在搜索框,上下键移动 aria-activedescendant,回车选中,Esc 关闭。
+ */
+const ModelPickerPanel = ({
+ kind,
+ models,
+ value,
+ params,
+ mode,
+ recent,
+ loading,
+ error,
+ onRetry,
+ onSelect,
+ onClose,
+ compact = false,
+ compare = null,
+}) => {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const comparing = Boolean(compare?.active);
+ const uid = useId().replace(/[^\w-]/g, '');
+ const listId = `mp-list-${uid}`;
+ const inputRef = useRef(null);
+ const listRef = useRef(null);
+ const [query, setQuery] = useState('');
+ const [lockedNotice, setLockedNotice] = useState(null);
+
+ const groups = useMemo(
+ () => groupModels(models, { recent, query }),
+ [models, recent, query],
+ );
+ const options = useMemo(
+ () => flattenOptions(groups, `mp-${uid}`),
+ [groups, uid],
+ );
+
+ // 初始高亮:当前模型(优先系列分组中的那一项,避免停在"最近使用")
+ const initialIndex = useMemo(() => {
+ const inSeries = options.findIndex(
+ (o) => o.model.model === value && o.group !== RECENT_GROUP,
+ );
+ if (inSeries >= 0) return inSeries;
+ return options.length ? 0 : -1;
+ }, [options, value]);
+ const [active, setActive] = useState(initialIndex);
+ useEffect(() => setActive(initialIndex), [initialIndex]);
+
+ useEffect(() => {
+ const id = requestAnimationFrame(() => inputRef.current?.focus());
+ return () => cancelAnimationFrame(id);
+ }, []);
+
+ // 高亮项滚入可见区
+ useEffect(() => {
+ const opt = options[active];
+ if (!opt || !listRef.current) return;
+ const el = listRef.current.querySelector(`#${CSS.escape(opt.id)}`);
+ el?.scrollIntoView?.({ block: 'nearest' });
+ }, [active, options]);
+
+ const pick = (model) => {
+ if (!model) return;
+ if (model.level_locked) {
+ setLockedNotice(model);
+ return;
+ }
+ setLockedNotice(null);
+ onSelect(model);
+ };
+ const isSelected = (m) =>
+ comparing ? compare.names.includes(m.model) : m.model === value;
+
+ const onKeyDown = (e) => {
+ switch (e.key) {
+ case 'ArrowDown':
+ e.preventDefault();
+ setActive((i) => moveActive(options.length, i, 1));
+ break;
+ case 'ArrowUp':
+ e.preventDefault();
+ setActive((i) => moveActive(options.length, i, -1));
+ break;
+ case 'Home':
+ if (options.length) {
+ e.preventDefault();
+ setActive(0);
+ }
+ break;
+ case 'End':
+ if (options.length) {
+ e.preventDefault();
+ setActive(options.length - 1);
+ }
+ break;
+ case 'Enter':
+ if (options[active]) {
+ e.preventDefault();
+ pick(options[active].model);
+ }
+ break;
+ case 'Escape':
+ e.preventDefault();
+ e.stopPropagation();
+ onClose();
+ break;
+ default:
+ }
+ };
+
+ const groupLabel = (g) => {
+ if (g.key === RECENT_GROUP) return t('最近使用');
+ if (g.key === OTHER_GROUP) return t('其他');
+ return g.label;
+ };
+
+ let body;
+ if (loading && !models.length) {
+ body = (
+
+ }
+ />
+
+ );
+ } else if (error && !models.length) {
+ body = (
+
+ {t('模型列表加载失败')}
+ {onRetry ? (
+ onRetry()}>
+ {t('重试')}
+
+ ) : null}
+
+ );
+ } else if (!models.length) {
+ body = (
+
+ {t('当前分组暂无可用模型,请联系管理员开通')}
+
+ );
+ } else if (!options.length) {
+ body = {t('没有匹配的模型')}
;
+ } else {
+ let cursor = -1;
+ body = groups.map((g) => {
+ const headId = `${listId}-${g.key === RECENT_GROUP ? 'recent' : String(g.key).replace(/[^\w-]/g, '_')}`;
+ return (
+
+
+ {groupLabel(g)}
+
+
+ {g.models.map((m) => {
+ cursor += 1;
+ const index = cursor;
+ const option = options[index];
+ return (
+ index !== active && setActive(index)}
+ />
+ );
+ })}
+
+
+ );
+ });
+ }
+
+ const activeId = options[active]?.id;
+
+ return (
+ e.key === 'Escape' && onKeyDown(e)}
+ >
+ {compare?.supported ? (
+
+
+
+ {t('对比生成')}
+
+ {t('同一提示词选择 2~4 个模型同时生成,对比效果')}
+
+
+ compare.setEnabled(on)}
+ aria-label={t('对比生成')}
+ />
+
+ ) : null}
+
+
+ setQuery(e.target.value)}
+ onKeyDown={onKeyDown}
+ role='combobox'
+ aria-expanded='true'
+ aria-controls={listId}
+ aria-autocomplete='list'
+ aria-activedescendant={activeId}
+ aria-label={t('搜索模型')}
+ />
+
+
+ {body}
+
+ {comparing ? (
+
+
+ {t('已选 {{n}} / {{max}} 个模型', {
+ n: compare.names.length,
+ max: 4,
+ })}
+
+
+ {t('完成')}
+
+
+ ) : null}
+ {lockedNotice ? (
+
+
+
+ {t('{{name}} 需要更高的会员等级', {
+ name: displayNameOf(lockedNotice),
+ })}
+
+ {
+ onClose();
+ navigate(UPGRADE_PATH);
+ }}
+ >
+ {t('升级')}
+
+
+ ) : null}
+
+ );
+};
+
+export default ModelPickerPanel;
diff --git a/src/components/creation/ModelPicker/index.js b/src/components/creation/ModelPicker/index.js
new file mode 100644
index 00000000..b07cd40c
--- /dev/null
+++ b/src/components/creation/ModelPicker/index.js
@@ -0,0 +1,23 @@
+/*
+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 .
+
+For commercial licensing, please contact support@quantumnous.com
+*/
+
+export { default } from './ModelPicker';
+export { default as ModelPicker } from './ModelPicker';
+export { default as ModelPickerPanel } from './ModelPickerPanel';
+export * from './modelPickerUtils';
diff --git a/src/components/creation/ModelPicker/model-picker.css b/src/components/creation/ModelPicker/model-picker.css
new file mode 100644
index 00000000..ba80aade
--- /dev/null
+++ b/src/components/creation/ModelPicker/model-picker.css
@@ -0,0 +1,405 @@
+/*
+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 .
+
+For commercial licensing, please contact support@quantumnous.com
+*/
+
+/* 模型选择器(WP B-4):配色全部从主题 token 派生。 */
+.mp-trigger,
+.mp-panel {
+ --mp-ink: var(--text-primary);
+ --mp-muted: var(--text-secondary);
+ --mp-line: var(--border-subtle);
+ --mp-accent: var(--semi-color-primary);
+ --mp-tint: color-mix(in srgb, var(--semi-color-primary) 10%, transparent);
+ --mp-card: var(--surface-card);
+ --mp-card-hover: color-mix(
+ in srgb,
+ var(--semi-color-primary) 6%,
+ var(--surface-card)
+ );
+ --mp-ring: color-mix(in srgb, var(--semi-color-primary) 55%, transparent);
+ --mp-warning: var(--semi-color-warning);
+ --mp-dur: var(--motion-fast, 150ms);
+}
+
+/* ---------- 触发 chip ---------- */
+.mp-trigger {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ max-width: 100%;
+ height: 32px;
+ padding: 0 10px 0 12px;
+ border: 1px solid var(--mp-line);
+ border-radius: 999px;
+ background: var(--mp-card);
+ color: var(--mp-ink);
+ font-size: 13px;
+ font-weight: 600;
+ cursor: pointer;
+ transition:
+ border-color var(--mp-dur),
+ background-color var(--mp-dur);
+}
+
+.mp-trigger:hover:not(:disabled) {
+ border-color: color-mix(in srgb, var(--semi-color-primary) 45%, transparent);
+ background: var(--mp-card-hover);
+}
+
+.mp-trigger:disabled {
+ cursor: not-allowed;
+ opacity: 0.6;
+}
+
+.mp-trigger:focus-visible {
+ outline: 2px solid var(--mp-ring);
+ outline-offset: 2px;
+}
+
+.mp-trigger-name {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.mp-trigger-caret {
+ flex-shrink: 0;
+ color: var(--mp-muted);
+}
+
+/* ---------- 面板 ---------- */
+.mp-popover {
+ padding: 0 !important;
+ border-radius: 14px !important;
+ overflow: hidden;
+}
+
+.mp-panel {
+ display: flex;
+ flex-direction: column;
+ width: min(640px, calc(100vw - 32px));
+ max-height: min(560px, 70vh);
+ background: var(--mp-card);
+ color: var(--mp-ink);
+}
+
+.mp-panel--compact {
+ width: 100%;
+ max-height: none;
+ height: 100%;
+}
+
+.mp-search {
+ position: relative;
+ flex-shrink: 0;
+ padding: 12px 12px 8px;
+ border-bottom: 1px solid var(--mp-line);
+}
+
+.mp-search-icon {
+ position: absolute;
+ top: 50%;
+ left: 24px;
+ margin-top: 2px;
+ transform: translateY(-50%);
+ color: var(--mp-muted);
+ pointer-events: none;
+}
+
+.mp-search-input {
+ width: 100%;
+ height: 34px;
+ padding: 0 12px 0 32px;
+ border: 1px solid var(--mp-line);
+ border-radius: 10px;
+ background: transparent;
+ color: var(--mp-ink);
+ font-size: 13px;
+ outline: none;
+}
+
+.mp-search-input:focus-visible {
+ border-color: var(--mp-accent);
+ box-shadow: 0 0 0 2px var(--mp-tint);
+}
+
+.mp-list {
+ flex: 1;
+ min-height: 0;
+ overflow-y: auto;
+ padding: 4px 12px 12px;
+}
+
+.mp-group-title {
+ position: sticky;
+ top: 0;
+ z-index: 1;
+ padding: 10px 2px 6px;
+ background: var(--mp-card);
+ color: var(--mp-muted);
+ font-size: 11px;
+ font-weight: 600;
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+}
+
+.mp-group-grid {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 8px;
+}
+
+.mp-panel--compact .mp-group-grid {
+ grid-template-columns: minmax(0, 1fr);
+}
+
+/* ---------- 卡片 ---------- */
+.mp-card {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ min-width: 0;
+ padding: 10px 12px;
+ border: 1px solid var(--mp-line);
+ border-radius: 12px;
+ background: var(--mp-card);
+ cursor: pointer;
+ transition:
+ border-color var(--mp-dur),
+ background-color var(--mp-dur);
+}
+
+.mp-card.is-active {
+ border-color: color-mix(in srgb, var(--semi-color-primary) 45%, transparent);
+ background: var(--mp-card-hover);
+ box-shadow: 0 0 0 2px var(--mp-tint);
+}
+
+.mp-card.is-selected {
+ border-color: var(--mp-accent);
+}
+
+.mp-card.is-incompatible,
+.mp-card.is-locked {
+ opacity: 0.6;
+}
+
+.mp-card.is-locked {
+ cursor: not-allowed;
+}
+
+.mp-card-head {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ min-width: 0;
+}
+
+.mp-card-name {
+ min-width: 0;
+ overflow: hidden;
+ font-size: 13px;
+ font-weight: 600;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.mp-card-check {
+ flex-shrink: 0;
+ margin-left: auto;
+ color: var(--mp-accent);
+}
+
+.mp-card-desc {
+ overflow: hidden;
+ color: var(--mp-muted);
+ font-size: 12px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.mp-card-tags {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px;
+}
+
+.mp-tag {
+ padding: 0 6px;
+ border-radius: 6px;
+ background: color-mix(in srgb, var(--text-primary) 6%, transparent);
+ color: var(--mp-muted);
+ font-size: 11px;
+ line-height: 18px;
+}
+
+.mp-badge {
+ display: inline-flex;
+ flex-shrink: 0;
+ align-items: center;
+ gap: 2px;
+ padding: 0 6px;
+ border-radius: 999px;
+ background: var(--mp-tint);
+ color: var(--mp-accent);
+ font-size: 10px;
+ font-weight: 600;
+ line-height: 16px;
+}
+
+.mp-badge--locked {
+ background: color-mix(in srgb, var(--semi-color-warning) 14%, transparent);
+ color: var(--mp-warning);
+}
+
+.mp-card-meta {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 4px 10px;
+ color: var(--mp-muted);
+ font-size: 11px;
+}
+
+.mp-num {
+ display: inline-flex;
+ align-items: center;
+ gap: 3px;
+ font-variant-numeric: tabular-nums;
+}
+
+.mp-card-reason {
+ color: var(--mp-warning);
+}
+
+/* ---------- 状态与升级入口 ---------- */
+.mp-state {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 10px;
+ padding: 28px 12px;
+ color: var(--mp-muted);
+ font-size: 13px;
+ text-align: center;
+}
+
+.mp-upgrade {
+ display: flex;
+ flex-shrink: 0;
+ align-items: center;
+ gap: 8px;
+ padding: 10px 12px;
+ border-top: 1px solid var(--mp-line);
+ background: color-mix(in srgb, var(--semi-color-warning) 8%, var(--mp-card));
+ color: var(--mp-ink);
+ font-size: 12px;
+}
+
+.mp-upgrade-text {
+ flex: 1;
+ min-width: 0;
+}
+
+.mp-panel button:focus-visible {
+ outline: 2px solid var(--mp-ring);
+ outline-offset: 2px;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .mp-trigger,
+ .mp-card {
+ transition: none;
+ }
+}
+
+/* ---------- 对比生成(WP C-2,仅图像) ---------- */
+.mp-trigger.is-compare {
+ border-color: color-mix(in srgb, var(--semi-color-primary) 45%, transparent);
+ background: var(--mp-tint);
+}
+
+.mp-compare {
+ display: flex;
+ flex-shrink: 0;
+ align-items: center;
+ gap: 10px;
+ padding: 10px 12px;
+ border-bottom: 1px solid var(--mp-line);
+ background: color-mix(in srgb, var(--semi-color-primary) 4%, var(--mp-card));
+}
+
+.mp-compare-icon {
+ flex-shrink: 0;
+ color: var(--mp-accent);
+}
+
+.mp-compare-text {
+ display: flex;
+ flex: 1;
+ flex-direction: column;
+ min-width: 0;
+}
+
+.mp-compare-title {
+ color: var(--mp-ink);
+ font-size: 13px;
+ font-weight: 600;
+}
+
+.mp-compare-desc {
+ overflow: hidden;
+ color: var(--mp-muted);
+ font-size: 12px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.mp-card-box {
+ display: inline-flex;
+ flex-shrink: 0;
+ align-items: center;
+ justify-content: center;
+ width: 18px;
+ height: 18px;
+ margin-left: auto;
+ border: 1px solid var(--mp-line);
+ border-radius: 5px;
+ color: transparent;
+}
+
+.mp-card-box.is-on {
+ border-color: var(--mp-accent);
+ background: var(--mp-accent);
+ color: var(--surface-card);
+}
+
+.mp-compare-foot {
+ display: flex;
+ flex-shrink: 0;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ padding: 10px 12px;
+ border-top: 1px solid var(--mp-line);
+ color: var(--mp-ink);
+ font-size: 12px;
+ font-variant-numeric: tabular-nums;
+}
diff --git a/src/components/creation/ModelPicker/modelPickerUtils.js b/src/components/creation/ModelPicker/modelPickerUtils.js
new file mode 100644
index 00000000..7f06da43
--- /dev/null
+++ b/src/components/creation/ModelPicker/modelPickerUtils.js
@@ -0,0 +1,269 @@
+/*
+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 .
+
+For commercial licensing, please contact support@quantumnous.com
+*/
+
+// 模型选择器(WP B-4)的纯函数:分组、搜索、能力标签、单价、不兼容原因、最近使用。
+// 无 React / i18n 依赖(文案以 i18n key + 插值返回),可直接 node --test。
+
+import { getParamDefault, optionValue } from '../params/constraints.js';
+
+export const RECENT_GROUP = '__recent__';
+export const OTHER_GROUP = '__other__';
+export const RECENT_LIMIT = 4;
+
+const TEXT_MODES = { video: 'text2video', image: 'text2image' };
+
+const MODE_LABEL_KEYS = {
+ text2video: '文生视频',
+ image2video: '图生视频',
+ first_last_frame: '首尾帧',
+ reference2video: '参考图生视频',
+ text2image: '文生图',
+ edit: '图生图',
+};
+
+export const modelKeyOf = (m) => (m && m.model) || '';
+
+/** 展示名:运营覆盖层 display_name,缺省为模型名。 */
+export const displayNameOf = (m) => (m && (m.display_name || m.model)) || '';
+
+/** 分组 key:schema series → vendor → 其他。 */
+export const seriesOf = (m) => {
+ const s = (m && (m.series || m.vendor)) || '';
+ return String(s).trim() || OTHER_GROUP;
+};
+
+/** 搜索:模型名 / 展示名 / 系列 / 介绍,大小写不敏感,空格分隔的词全部命中。 */
+export const matchesQuery = (m, query) => {
+ const words = String(query || '')
+ .toLowerCase()
+ .split(/\s+/)
+ .filter(Boolean);
+ if (!words.length) return true;
+ const hay = [m?.model, m?.display_name, m?.series, m?.vendor, m?.description]
+ .filter(Boolean)
+ .join(' ')
+ .toLowerCase();
+ return words.every((w) => hay.includes(w));
+};
+
+/**
+ * 分组:无搜索词时"最近使用"置顶(模型同时保留在所属系列中),其后按系列首次出现的顺序,
+ * "其他"放最后。有搜索词时不显示"最近使用"。
+ *
+ * @returns {Array<{ key: string, label: string, models: object[] }>}
+ * label 为系列原名;RECENT_GROUP / OTHER_GROUP 由界面翻译。
+ */
+export const groupModels = (models, { recent = [], query = '' } = {}) => {
+ const list = (Array.isArray(models) ? models : []).filter(
+ (m) => m && m.model && matchesQuery(m, query),
+ );
+ const groups = [];
+ if (!String(query || '').trim() && recent.length) {
+ const byName = new Map(list.map((m) => [m.model, m]));
+ const recentModels = recent.map((n) => byName.get(n)).filter(Boolean);
+ if (recentModels.length) {
+ groups.push({ key: RECENT_GROUP, label: '', models: recentModels });
+ }
+ }
+ const order = [];
+ const bySeries = new Map();
+ list.forEach((m) => {
+ const key = seriesOf(m);
+ if (!bySeries.has(key)) {
+ bySeries.set(key, []);
+ order.push(key);
+ }
+ bySeries.get(key).push(m);
+ });
+ order
+ .filter((k) => k !== OTHER_GROUP)
+ .forEach((k) => groups.push({ key: k, label: k, models: bySeries.get(k) }));
+ if (bySeries.has(OTHER_GROUP)) {
+ groups.push({
+ key: OTHER_GROUP,
+ label: '',
+ models: bySeries.get(OTHER_GROUP),
+ });
+ }
+ return groups;
+};
+
+/** 键盘导航用的扁平选项列表:[{ id, model, group }],id 在同一模型出现于多个分组时仍唯一。 */
+export const flattenOptions = (groups, idPrefix = 'mp') =>
+ (groups || []).flatMap((g) =>
+ g.models.map((m) => ({
+ id: `${idPrefix}-${g.key === RECENT_GROUP ? 'r' : 's'}-${String(m.model).replace(/[^\w-]/g, '_')}`,
+ model: m,
+ group: g.key,
+ })),
+ );
+
+/** 上下移动后的下标(循环);列表为空返回 -1。 */
+export const moveActive = (length, current, delta) => {
+ if (!length) return -1;
+ if (current < 0 || current >= length) return delta < 0 ? length - 1 : 0;
+ return (current + delta + length) % length;
+};
+
+const numericOptions = (param) =>
+ ((param && param.options) || [])
+ .map((o) => Number(optionValue(o)))
+ .filter((n) => Number.isFinite(n) && n > 0);
+
+const findParam = (m, key) =>
+ ((m && m.params) || []).find((p) => p && p.key === key) || null;
+
+const enabledModes = (m) => new Set((m && m.modes) || []);
+
+/**
+ * 能力标签(i18n key + 插值):图生 / 首尾帧 / 参考图 / 编辑 / 音频 / 最长时长。
+ * 只看可用模式与参数;因系统配置禁用的模式不计入。
+ *
+ * @returns {Array<{ key: string, label: string, values?: object }>}
+ */
+export const capabilityTags = (kind, m) => {
+ if (!m) return [];
+ const modes = enabledModes(m);
+ const tags = [];
+ if (kind === 'image') {
+ if (modes.has('edit')) {
+ tags.push({ key: 'edit', label: '编辑' });
+ const max = Number(m.inputs?.reference_images?.max);
+ if (Number.isFinite(max) && max > 1) {
+ tags.push({
+ key: 'reference',
+ label: '参考图 ×{{n}}',
+ values: { n: max },
+ });
+ }
+ }
+ return tags;
+ }
+ if (modes.has('image2video')) tags.push({ key: 'i2v', label: '图生' });
+ if (modes.has('first_last_frame')) {
+ tags.push({ key: 'flf', label: '首尾帧' });
+ }
+ if (modes.has('reference2video')) {
+ tags.push({ key: 'reference', label: '参考图' });
+ }
+ if (findParam(m, 'generate_audio') || (m.badges || []).includes('audio')) {
+ tags.push({ key: 'audio', label: '音频' });
+ }
+ const durations = numericOptions(findParam(m, 'duration'));
+ if (durations.length) {
+ tags.push({
+ key: 'max_duration',
+ label: '最长 {{n}} 秒',
+ values: { n: Math.max(...durations) },
+ });
+ }
+ return tags;
+};
+
+const BADGE_LABELS = { recommended: '推荐', new: '新' };
+
+/** 展示徽标(推荐 / 新);其余 badge(如 audio)已体现在能力标签中。 */
+export const badgesOf = (m) =>
+ ((m && m.badges) || [])
+ .filter((b) => BADGE_LABELS[b])
+ .map((b) => ({ key: b, label: BADGE_LABELS[b] }));
+
+const UNIT_LABELS = { second: '秒', task: '次', image: '张' };
+
+/**
+ * 与当前参数对应的单价(取自 schema pricing,不调用估价接口)。
+ * 分档(by=resolution 等)时按当前取值(缺省为该参数默认值)取档位价,档位缺失退回默认价。
+ *
+ * @returns {{ amount: number, currency: string, unit: string, unitLabel: string, tier: string } | null}
+ */
+export const unitPriceOf = (m, params = {}) => {
+ const p = m && m.pricing;
+ if (!p) return null;
+ let amount = Number(p.price);
+ let tier = '';
+ if (p.by && p.prices && typeof p.prices === 'object') {
+ let current = params ? params[p.by] : undefined;
+ if (current === undefined || current === null || current === '') {
+ current = getParamDefault(findParam(m, p.by));
+ }
+ if (current !== undefined && current !== null && current !== '') {
+ const want = String(current).toLowerCase();
+ const hit = Object.keys(p.prices).find((k) => k.toLowerCase() === want);
+ if (hit && Number.isFinite(Number(p.prices[hit]))) {
+ amount = Number(p.prices[hit]);
+ tier = hit;
+ }
+ }
+ }
+ if (!Number.isFinite(amount) || amount <= 0) return null;
+ return {
+ amount,
+ currency: p.currency || '',
+ unit: p.unit || '',
+ unitLabel: UNIT_LABELS[p.unit] || '',
+ tier,
+ };
+};
+
+/**
+ * 与当前输入不兼容的原因(i18n key + 插值),兼容返回 null。
+ * 当前为非文生模式(用户已选图生 / 首尾帧 / 参考图 / 编辑)时,不支持该模式的模型不兼容。
+ * 等级锁定由调用方单独处理,不在此判断。
+ *
+ * @returns {{ key: string, values: { mode: string } } | null} values.mode 为模式名的 i18n key
+ */
+export const incompatibilityOf = (kind, m, { mode } = {}) => {
+ if (!m || !mode || mode === TEXT_MODES[kind]) return null;
+ if (enabledModes(m).has(mode)) return null;
+ return {
+ key: '不支持{{mode}}',
+ values: { mode: MODE_LABEL_KEYS[mode] || mode },
+ };
+};
+
+// ---------------------------------------------------------------------------
+// 最近使用(localStorage creation..recent,读写全部 try/catch)
+// ---------------------------------------------------------------------------
+
+export const recentKeyOf = (kind) => `creation.${kind}.recent`;
+
+export const loadRecent = (storage, kind) => {
+ try {
+ const raw = storage ? storage.getItem(recentKeyOf(kind)) : null;
+ const list = raw ? JSON.parse(raw) : [];
+ return Array.isArray(list)
+ ? list.filter((n) => typeof n === 'string' && n).slice(0, RECENT_LIMIT)
+ : [];
+ } catch (e) {
+ return [];
+ }
+};
+
+/** 把模型放到最近使用首位并保存;返回新列表。 */
+export const pushRecent = (storage, kind, name, current) => {
+ const base = Array.isArray(current) ? current : loadRecent(storage, kind);
+ if (!name) return base;
+ const next = [name, ...base.filter((n) => n !== name)].slice(0, RECENT_LIMIT);
+ try {
+ if (storage) storage.setItem(recentKeyOf(kind), JSON.stringify(next));
+ } catch (e) {
+ // 存储不可用时只在内存中生效
+ }
+ return next;
+};
diff --git a/src/components/creation/ModelPicker/modelPickerUtils.test.js b/src/components/creation/ModelPicker/modelPickerUtils.test.js
new file mode 100644
index 00000000..8b7d4c12
--- /dev/null
+++ b/src/components/creation/ModelPicker/modelPickerUtils.test.js
@@ -0,0 +1,260 @@
+/*
+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 .
+
+For commercial licensing, please contact support@quantumnous.com
+*/
+
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import {
+ OTHER_GROUP,
+ RECENT_GROUP,
+ RECENT_LIMIT,
+ badgesOf,
+ capabilityTags,
+ flattenOptions,
+ groupModels,
+ incompatibilityOf,
+ loadRecent,
+ matchesQuery,
+ moveActive,
+ pushRecent,
+ recentKeyOf,
+ unitPriceOf,
+} from './modelPickerUtils.js';
+
+const seedance = {
+ model: 'doubao-seedance-1-5-pro',
+ display_name: 'Seedance 1.5 Pro',
+ series: 'seedance',
+ badges: ['recommended', 'audio'],
+ description: '电影级运镜',
+ modes: ['text2video', 'image2video', 'first_last_frame'],
+ params: [
+ {
+ key: 'resolution',
+ type: 'chips',
+ options: ['480P', '720P', '1080P'],
+ default: '720P',
+ },
+ {
+ key: 'duration',
+ type: 'segmented',
+ options: [{ value: 5 }, { value: 10 }],
+ default: 5,
+ },
+ { key: 'generate_audio', type: 'switch' },
+ ],
+ pricing: {
+ unit: 'second',
+ by: 'resolution',
+ price: 0.05,
+ prices: { '480P': 0.02, '720P': 0.05, '1080P': 0.1 },
+ currency: 'CNY',
+ },
+};
+const kling = {
+ model: 'kling-v2',
+ series: 'kling',
+ modes: ['text2video', 'image2video'],
+ params: [{ key: 'duration', type: 'segmented', options: [5] }],
+};
+const wan = {
+ model: 'wan2.5',
+ series: 'seedance',
+ modes: ['text2video', 'reference2video'],
+ params: [],
+ badges: ['new'],
+};
+const misc = { model: 'misc-video', modes: ['text2video'], params: [] };
+
+const memoryStorage = () => {
+ const data = {};
+ return {
+ data,
+ getItem: (k) => (k in data ? data[k] : null),
+ setItem: (k, v) => {
+ data[k] = String(v);
+ },
+ };
+};
+
+test('分组:按系列首次出现顺序,"其他"在最后,最近使用置顶', () => {
+ const groups = groupModels([misc, seedance, kling, wan], {
+ recent: ['kling-v2', 'gone-model'],
+ });
+ assert.deepEqual(
+ groups.map((g) => g.key),
+ [RECENT_GROUP, 'seedance', 'kling', OTHER_GROUP],
+ );
+ assert.deepEqual(
+ groups[0].models.map((m) => m.model),
+ ['kling-v2'],
+ );
+ assert.deepEqual(
+ groups[1].models.map((m) => m.model),
+ ['doubao-seedance-1-5-pro', 'wan2.5'],
+ );
+ // vendor 作为系列缺失时的回退
+ const byVendor = groupModels([{ model: 'x', vendor: 'OpenAI' }]);
+ assert.equal(byVendor[0].key, 'OpenAI');
+});
+
+test('搜索:多词匹配名称 / 展示名 / 介绍,搜索时不显示最近使用', () => {
+ assert.equal(matchesQuery(seedance, 'seedance pro'), true);
+ assert.equal(matchesQuery(seedance, '运镜'), true);
+ assert.equal(matchesQuery(seedance, 'kling'), false);
+ const groups = groupModels([seedance, kling], {
+ recent: ['kling-v2'],
+ query: 'kling',
+ });
+ assert.deepEqual(
+ groups.map((g) => g.key),
+ ['kling'],
+ );
+});
+
+test('扁平选项 id 唯一(最近使用与系列中重复出现的模型)', () => {
+ const groups = groupModels([seedance, kling], { recent: ['kling-v2'] });
+ const opts = flattenOptions(groups, 'p');
+ assert.equal(opts.length, 3);
+ assert.equal(new Set(opts.map((o) => o.id)).size, 3);
+ assert.ok(opts.every((o) => /^[\w-]+$/.test(o.id)));
+});
+
+test('键盘移动循环', () => {
+ assert.equal(moveActive(3, 2, 1), 0);
+ assert.equal(moveActive(3, 0, -1), 2);
+ assert.equal(moveActive(3, -1, 1), 0);
+ assert.equal(moveActive(3, -1, -1), 2);
+ assert.equal(moveActive(0, 0, 1), -1);
+});
+
+test('能力标签:视频由模式 / 参数推导,含最长时长', () => {
+ assert.deepEqual(
+ capabilityTags('video', seedance).map((t) => t.key),
+ ['i2v', 'flf', 'audio', 'max_duration'],
+ );
+ assert.deepEqual(
+ capabilityTags('video', seedance).find((t) => t.key === 'max_duration')
+ .values,
+ { n: 10 },
+ );
+ assert.deepEqual(
+ capabilityTags('video', wan).map((t) => t.key),
+ ['reference'],
+ );
+ // 因系统配置禁用的模式不计入
+ assert.deepEqual(
+ capabilityTags('video', {
+ modes: ['text2video'],
+ disabled_modes: [{ mode: 'image2video' }],
+ }),
+ [],
+ );
+});
+
+test('能力标签:图像编辑与多图参考', () => {
+ const img = {
+ modes: ['text2image', 'edit'],
+ inputs: { reference_images: { modes: ['edit'], max: 4 } },
+ };
+ assert.deepEqual(
+ capabilityTags('image', img).map((t) => [t.key, t.values?.n]),
+ [
+ ['edit', undefined],
+ ['reference', 4],
+ ],
+ );
+ assert.deepEqual(capabilityTags('image', { modes: ['text2image'] }), []);
+});
+
+test('徽标只显示推荐 / 新', () => {
+ assert.deepEqual(
+ badgesOf(seedance).map((b) => b.label),
+ ['推荐'],
+ );
+ assert.deepEqual(
+ badgesOf(wan).map((b) => b.label),
+ ['新'],
+ );
+});
+
+test('单价:按当前参数取档位,缺省取参数默认档,无定价返回 null', () => {
+ assert.deepEqual(unitPriceOf(seedance, { resolution: '1080p' }), {
+ amount: 0.1,
+ currency: 'CNY',
+ unit: 'second',
+ unitLabel: '秒',
+ tier: '1080P',
+ });
+ assert.equal(unitPriceOf(seedance, {}).tier, '720P');
+ // 档位缺失:退回默认价,不显示档位
+ const r = unitPriceOf(seedance, { resolution: '4K' });
+ assert.equal(r.amount, 0.05);
+ assert.equal(r.tier, '');
+ assert.equal(unitPriceOf(kling, {}), null);
+ assert.equal(
+ unitPriceOf({ pricing: { unit: 'task', price: 0, currency: 'CNY' } }),
+ null,
+ );
+ assert.equal(
+ unitPriceOf({ pricing: { unit: 'image', price: 0.2, currency: 'USD' } })
+ .unitLabel,
+ '张',
+ );
+});
+
+test('不兼容原因:非文生模式下不支持该模式的模型置灰并说明', () => {
+ assert.equal(incompatibilityOf('video', kling, { mode: 'text2video' }), null);
+ assert.equal(
+ incompatibilityOf('video', seedance, { mode: 'first_last_frame' }),
+ null,
+ );
+ assert.deepEqual(
+ incompatibilityOf('video', kling, { mode: 'first_last_frame' }),
+ { key: '不支持{{mode}}', values: { mode: '首尾帧' } },
+ );
+ assert.deepEqual(
+ incompatibilityOf('image', { modes: ['text2image'] }, { mode: 'edit' })
+ .values,
+ { mode: '图生图' },
+ );
+});
+
+test('最近使用:置顶去重、限长,存储异常不抛错', () => {
+ const storage = memoryStorage();
+ let list = [];
+ ['a', 'b', 'c', 'd', 'e', 'b'].forEach((n) => {
+ list = pushRecent(storage, 'video', n, list);
+ });
+ assert.equal(list.length, RECENT_LIMIT);
+ assert.deepEqual(list, ['b', 'e', 'd', 'c']);
+ assert.deepEqual(loadRecent(storage, 'video'), list);
+ assert.deepEqual(loadRecent(storage, 'image'), []);
+ storage.data[recentKeyOf('image')] = 'not json';
+ assert.deepEqual(loadRecent(storage, 'image'), []);
+ const throwing = {
+ getItem: () => {
+ throw new Error('x');
+ },
+ setItem: () => {
+ throw new Error('x');
+ },
+ };
+ assert.deepEqual(loadRecent(throwing, 'video'), []);
+ assert.deepEqual(pushRecent(throwing, 'video', 'a', []), ['a']);
+});
diff --git a/src/components/creation/WorkFeed/ApiCodePanel.jsx b/src/components/creation/WorkFeed/ApiCodePanel.jsx
new file mode 100644
index 00000000..4c81f995
--- /dev/null
+++ b/src/components/creation/WorkFeed/ApiCodePanel.jsx
@@ -0,0 +1,170 @@
+/*
+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 .
+
+For commercial licensing, please contact support@quantumnous.com
+*/
+
+import React, { useContext, useMemo, useState } from 'react';
+import { Button } from '@douyinfe/semi-ui';
+import { ChevronDown, Code2, Copy, KeyRound } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import { useNavigate } from 'react-router-dom';
+import { StatusContext } from '../../../context/Status';
+import { copy, showSuccess } from '../../../helpers';
+import { trackCreationEvent } from '../../../helpers/creationEvents';
+import {
+ API_CODE_LANGS,
+ apiBaseUrlOf,
+ buildApiCall,
+ renderApiCode,
+} from '../../../hooks/creation/creationApiCode';
+
+/** 秘钥管理模块;from=creation_studio 用于记录 key_created_from_studio(WP C-1)。 */
+export const KEY_MANAGEMENT_FROM_STUDIO =
+ '/key-management?from=creation_studio';
+
+const LANG_LABELS = {
+ curl: 'cURL',
+ python: 'Python',
+ javascript: 'JavaScript',
+};
+
+const currentOrigin = () => {
+ try {
+ return window.location.origin;
+ } catch (e) {
+ return '';
+ }
+};
+
+/**
+ * 获取 API 代码(WP C-1,方案 §4.4):详情抽屉内的折叠面板,由参数快照生成等价的
+ * /v1/images|video/generations 调用(curl / Python / JavaScript),标注"API 同价",
+ * "创建密钥"直达秘钥管理。首次展开记 api_code_open。
+ */
+const ApiCodePanel = ({ task }) => {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const [statusState] = useContext(StatusContext);
+ const [open, setOpen] = useState(false);
+ const [lang, setLang] = useState('curl');
+ const [tracked, setTracked] = useState(false);
+
+ const baseUrl = apiBaseUrlOf(statusState?.status, currentOrigin());
+ const call = useMemo(() => buildApiCall(task, { baseUrl }), [task, baseUrl]);
+ const code = useMemo(() => renderApiCode(call, lang), [call, lang]);
+ const panelId = `wf-api-${task?.id || 'x'}`;
+
+ const toggle = () => {
+ const next = !open;
+ setOpen(next);
+ if (next && !tracked) {
+ setTracked(true);
+ trackCreationEvent('api_code_open', {
+ kind: task?.kind || '',
+ model: call.body.model || '',
+ });
+ }
+ };
+
+ return (
+
+
+
+ {t('获取 API 代码')}
+ {t('API 同价')}
+
+
+ {open ? (
+
+
+ {t('用同样的参数通过 API 调用,价格与体验中心一致')}
+
+
+
+ {API_CODE_LANGS.map((key) => (
+ setLang(key)}
+ >
+ {LANG_LABELS[key]}
+
+ ))}
+
+
}
+ onClick={async () => {
+ if (await copy(code)) showSuccess(t('已复制'));
+ }}
+ >
+ {t('复制')}
+
+
+
+ {code}
+
+ {call.notes.length ? (
+
+ {call.notes.map((note) => (
+ {t(note, { path: call.path })}
+ ))}
+
+ ) : null}
+
+
+ {t('把 sk-xxx 替换为你的 API 密钥')}
+
+ }
+ onClick={() => navigate(KEY_MANAGEMENT_FROM_STUDIO)}
+ >
+ {t('创建密钥')}
+
+
+
+ ) : null}
+
+ );
+};
+
+export default ApiCodePanel;
diff --git a/src/components/creation/WorkFeed/FilterBar.jsx b/src/components/creation/WorkFeed/FilterBar.jsx
new file mode 100644
index 00000000..472813d5
--- /dev/null
+++ b/src/components/creation/WorkFeed/FilterBar.jsx
@@ -0,0 +1,284 @@
+/*
+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 .
+
+For commercial licensing, please contact support@quantumnous.com
+*/
+
+import React, {
+ useEffect,
+ useMemo,
+ useState,
+ useSyncExternalStore,
+} from 'react';
+import {
+ Badge,
+ Button,
+ Input,
+ Popover,
+ Select,
+ SideSheet,
+} from '@douyinfe/semi-ui';
+import { Filter, GitCompare, Search, Star } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import { useIsMobile } from '../../../hooks/common/useIsMobile';
+import {
+ activeFilterCount,
+ facetsOf,
+} from '../../../hooks/creation/creationTasks';
+import './work-feed.css';
+
+// 移动端与矮屏桌面:筛选栏折叠为一个"筛选"图标(与 CreationDock 的收起判定一致)
+const COMPACT_QUERY = '(max-width: 767px), (max-height: 799px)';
+
+const useCompactFilters = () =>
+ useSyncExternalStore(
+ (callback) => {
+ const mql = window.matchMedia(COMPACT_QUERY);
+ mql.addEventListener('change', callback);
+ return () => mql.removeEventListener('change', callback);
+ },
+ () => window.matchMedia(COMPACT_QUERY).matches,
+ () => false,
+ );
+
+const STATUS_OPTIONS = [
+ { value: 'all', label: '全部状态' },
+ { value: 'active', label: '进行中' },
+ { value: 'success', label: '已完成' },
+ { value: 'failed', label: '失败' },
+];
+
+/** 关键词输入:本地即时响应,250ms 防抖后写入筛选条件。 */
+const useDebouncedKeyword = (keyword, setFilters) => {
+ const [input, setInput] = useState(keyword || '');
+ useEffect(() => {
+ setInput(keyword || '');
+ }, [keyword]);
+ useEffect(() => {
+ if (input === (keyword || '')) return undefined;
+ const timer = setTimeout(() => setFilters({ keyword: input }), 250);
+ return () => clearTimeout(timer);
+ }, [input, keyword, setFilters]);
+ return [input, setInput];
+};
+
+const Controls = ({ kind, api, facets, vertical, input, setInput }) => {
+ const { t } = useTranslation();
+ const { filters, setFilters } = api;
+ const label = (text) =>
+ vertical ? {text}
: null;
+ const wrap = (node, text) =>
+ vertical ? (
+
+ {label(text)}
+ {node}
+
+ ) : (
+ node
+ );
+
+ const modelOptions = [
+ { value: 'all', label: t('全部模型') },
+ ...facets.models.map((m) => ({ value: m, label: m })),
+ ];
+ const sizeOptions = [
+ { value: 'all', label: t('全部尺寸') },
+ ...facets.sizes.map((s) => ({ value: s, label: s.replace('x', '×') })),
+ ];
+
+ return (
+ <>
+ {wrap(
+ }
+ placeholder={t('搜索提示词或模型')}
+ aria-label={t('搜索提示词或模型')}
+ value={input}
+ onChange={setInput}
+ showClear
+ />,
+ t('搜索'),
+ )}
+ {wrap(
+ setFilters({ status: v })}
+ optionList={STATUS_OPTIONS.map((o) => ({
+ value: o.value,
+ label: t(o.label),
+ }))}
+ />,
+ t('状态'),
+ )}
+ {wrap(
+ setFilters({ model: v })}
+ optionList={modelOptions}
+ filter
+ />,
+ t('模型'),
+ )}
+ {kind === 'image'
+ ? wrap(
+ setFilters({ size: v })}
+ optionList={sizeOptions}
+ />,
+ t('尺寸'),
+ )
+ : null}
+ }
+ aria-pressed={filters.favoritesOnly}
+ onClick={() => setFilters({ favoritesOnly: !filters.favoritesOnly })}
+ >
+ {t('只看收藏')}
+
+ >
+ );
+};
+
+/**
+ * 作品流筛选栏(WP B-6):状态 / 模型 / 尺寸(图像)/ 只看收藏 / 关键词;图像页带"多选对比"开关。
+ * 移动端与矮屏桌面折叠为一个"筛选"图标(移动端底部抽屉,矮屏桌面弹层)。
+ *
+ * props: kind, api = useCreationTasks(kind), selecting, onToggleSelecting
+ */
+const FilterBar = ({ kind, api, selecting, onToggleSelecting }) => {
+ const { t } = useTranslation();
+ const compact = useCompactFilters();
+ const isMobile = useIsMobile();
+ const [open, setOpen] = useState(false);
+ const facets = useMemo(() => facetsOf(api.tasks), [api.tasks]);
+ const [input, setInput] = useDebouncedKeyword(
+ api.filters.keyword,
+ api.setFilters,
+ );
+ const count = activeFilterCount(api.filters);
+
+ const compareButton =
+ kind === 'image' && onToggleSelecting ? (
+ }
+ aria-pressed={selecting}
+ aria-label={t('多选对比')}
+ title={t('多选对比')}
+ onClick={onToggleSelecting}
+ >
+ {compact ? null : t('多选对比')}
+
+ ) : null;
+
+ if (!compact) {
+ return (
+
+
+ {compareButton}
+
+ );
+ }
+
+ const panel = (
+
+
+
+ {
+ setInput('');
+ api.resetFilters();
+ }}
+ >
+ {t('清除筛选')}
+
+ setOpen(false)}>
+ {t('完成')}
+
+
+
+ );
+
+ const trigger = (
+
+ }
+ aria-label={t('筛选')}
+ aria-expanded={open}
+ onClick={() => setOpen((v) => !v)}
+ />
+
+ );
+
+ return (
+
+ {compareButton}
+ {isMobile ? (
+ <>
+ {trigger}
+
setOpen(false)}
+ >
+ {panel}
+
+ >
+ ) : (
+
setOpen(false)}
+ onEscKeyDown={() => setOpen(false)}
+ content={{panel}
}
+ >
+ {trigger}
+
+ )}
+
+ );
+};
+
+export default FilterBar;
diff --git a/src/components/creation/WorkFeed/WorkCard.jsx b/src/components/creation/WorkFeed/WorkCard.jsx
new file mode 100644
index 00000000..cac1865d
--- /dev/null
+++ b/src/components/creation/WorkFeed/WorkCard.jsx
@@ -0,0 +1,488 @@
+/*
+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 .
+
+For commercial licensing, please contact support@quantumnous.com
+*/
+
+import React, { memo, useEffect, useRef, useState } from 'react';
+import { Button, Dropdown } from '@douyinfe/semi-ui';
+import {
+ AlertCircle,
+ Check,
+ Clapperboard,
+ Image as ImageIcon,
+ LayoutGrid,
+ MoreHorizontal,
+ RefreshCw,
+ Star,
+} from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import { renderQuota } from '../../../helpers';
+import {
+ classifyCreationError,
+ describeCreationError,
+} from '../../../helpers/creationError';
+import {
+ aspectRatioOf,
+ elapsedSeconds,
+ formatSeconds,
+ isActiveTask,
+ isSlowTask,
+} from '../../../hooks/creation/creationTasks';
+
+const matches = (query) => {
+ try {
+ return window.matchMedia(query).matches;
+ } catch (e) {
+ return false;
+ }
+};
+const prefersReducedMotion = () => matches('(prefers-reduced-motion: reduce)');
+const canHover = () => matches('(hover: hover) and (pointer: fine)');
+
+/** 作品默认 alt:提示词前 60 字(方案 §4.7)。 */
+export const altOf = (task, t) =>
+ (task?.prompt || '').slice(0, 60) || t('生成的作品');
+
+/**
+ * 单张结果图:地址失效(COS 预签名过期)时自动刷新一次,仍失败显示占位 + 手动刷新。
+ */
+export const ResultImage = ({ task, index, onRefresh, className, alt }) => {
+ const { t } = useTranslation();
+ const image = task.images?.[index] || {};
+ const [failed, setFailed] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const triedRef = useRef('');
+
+ useEffect(() => {
+ setFailed(false);
+ }, [image.url]);
+
+ const refresh = async () => {
+ if (busy) return;
+ setBusy(true);
+ const url = await onRefresh(task, index);
+ setBusy(false);
+ if (!url) setFailed(true);
+ };
+
+ const onError = () => {
+ if (triedRef.current === image.url) {
+ setFailed(true);
+ return;
+ }
+ triedRef.current = image.url;
+ refresh();
+ };
+
+ if (!image.url || failed) {
+ const canRefresh = Boolean(image.url) || (image.hasB64 && index === 0);
+ return (
+
+
+ {t('图片暂不可用')}
+ {canRefresh ? (
+ }
+ loading={busy}
+ onClick={(e) => {
+ e.stopPropagation();
+ refresh();
+ }}
+ >
+ {t('刷新链接')}
+
+ ) : null}
+
+ );
+ }
+ return (
+
+ );
+};
+
+/**
+ * 视频封面:静音;桌面悬停自动播放,触屏设备进入视口播放;prefers-reduced-motion 时不自动播放。
+ * 地址失效时经 ids= 刷新一次。
+ */
+const VideoThumb = ({ task, onRefresh, alt }) => {
+ const { t } = useTranslation();
+ const ref = useRef(null);
+ const triedRef = useRef('');
+ const [failed, setFailed] = useState(false);
+ const url = task.videoUrl;
+
+ useEffect(() => {
+ setFailed(false);
+ }, [url]);
+
+ // 触屏:进入视口(≥ 60%)静音播放,离开暂停
+ useEffect(() => {
+ const el = ref.current;
+ if (!el || !url || canHover() || prefersReducedMotion()) return undefined;
+ if (typeof IntersectionObserver === 'undefined') return undefined;
+ const io = new IntersectionObserver(
+ ([entry]) => {
+ if (entry.isIntersecting) el.play?.().catch(() => {});
+ else el.pause?.();
+ },
+ { threshold: 0.6 },
+ );
+ io.observe(el);
+ return () => io.disconnect();
+ }, [url]);
+
+ if (!url || failed) {
+ return (
+
+
+ {failed ? {t('视频暂不可用')} : null}
+
+ );
+ }
+
+ const onEnter = () => {
+ if (!canHover() || prefersReducedMotion()) return;
+ ref.current?.play?.().catch(() => {});
+ };
+ const onLeave = () => {
+ const el = ref.current;
+ if (!el || !canHover()) return;
+ el.pause?.();
+ try {
+ el.currentTime = 0;
+ } catch (e) {
+ // 元数据未加载时不可设置
+ }
+ };
+ const onError = async () => {
+ if (triedRef.current === url) {
+ setFailed(true);
+ return;
+ }
+ triedRef.current = url;
+ const next = await onRefresh(task);
+ if (!next || next === url) setFailed(true);
+ };
+
+ return (
+
+ );
+};
+
+const ActiveOverlay = ({ task, estSeconds, p90 = 0, now }) => {
+ const { t } = useTranslation();
+ const elapsed = elapsedSeconds(task, now);
+ const slow = isSlowTask(task, p90, now);
+ return (
+
+
+ {task.status === 'queued' ? t('排队中') : t('生成中')}
+
+
+ {estSeconds > 0
+ ? t('已用时 {{elapsed}} / 预计 {{est}}', {
+ elapsed: formatSeconds(elapsed),
+ est: formatSeconds(estSeconds),
+ })
+ : t('已用时 {{elapsed}}', { elapsed: formatSeconds(elapsed) })}
+
+ {task.progress > 0 ? (
+
+
+
+ ) : null}
+ {slow ? (
+
+ {t('比平时慢,可以切到其他页面,完成后会提醒你')}
+
+ ) : null}
+
+ );
+};
+
+export const RefundNote = ({ task }) => {
+ const { t } = useTranslation();
+ if (!(task.refundedQuota > 0)) return null;
+ return (
+
+ {t('已退还 {{amount}}', { amount: renderQuota(task.refundedQuota) })}
+
+ );
+};
+
+/** 失败原因 → 统一错误映射({ info, title, detail, actionLabel });没有原因时为 null。 */
+export const failureOf = (t, task) => {
+ if (!task?.failReason) return null;
+ const info = classifyCreationError(task.failReason);
+ return { info, ...describeCreationError(t, info) };
+};
+
+const FailedOverlay = ({ task }) => {
+ const { t } = useTranslation();
+ const failure = failureOf(t, task);
+ // 映射为通用"生成失败"时直接展示原始原因;否则展示可读文案,原始原因放在 title 里
+ const reason = failure
+ ? failure.info.category === 'unknown'
+ ? task.failReason
+ : failure.title
+ : '';
+ return (
+
+
+
+ {t('生成失败')}
+
+ {reason ? (
+
+ {reason}
+
+ ) : null}
+
+
+ );
+};
+
+const ImageMedia = ({ task, onRefreshImage, alt }) => {
+ const { t } = useTranslation();
+ const count = task.images.length;
+ if (count > 1) {
+ return (
+ <>
+
+ {task.images.slice(0, 4).map((_, i) => (
+
+ ))}
+
+
+
+ {t('{{n}} 张', { n: count })}
+
+ >
+ );
+ }
+ return (
+
+ );
+};
+
+/**
+ * 作品卡片(图像 / 视频)。
+ * props:
+ * task, estSeconds, p90(预计耗时 p90,超过时显示慢任务提示), now,
+ * getActions: (task) => [{ key, label, icon, onClick, danger }](更多菜单)
+ * onOpen, onFavorite, onCancel, onRefreshImage, onRefreshVideo,
+ * selecting, selected, selectable, onToggleSelect
+ */
+const WorkCard = ({
+ task,
+ estSeconds = 0,
+ p90 = 0,
+ now,
+ getActions,
+ onOpen,
+ onFavorite,
+ onCancel,
+ onRefreshImage,
+ onRefreshVideo,
+ selecting = false,
+ selected = false,
+ selectable = false,
+ onToggleSelect,
+}) => {
+ const { t } = useTranslation();
+ const active = isActiveTask(task);
+ const failed = task.status === 'failed';
+ const alt = altOf(task, t);
+ const ratio = aspectRatioOf(task);
+ const actions = getActions ? getActions(task) : [];
+
+ const handleMediaClick = () => {
+ if (selecting) {
+ if (selectable) onToggleSelect?.(task);
+ return;
+ }
+ onOpen?.(task);
+ };
+
+ let mediaLabel = alt;
+ if (selecting) {
+ mediaLabel = selectable
+ ? `${selected ? t('取消选择') : t('选择')}:${alt}`
+ : t('仅已完成的图片可参与对比');
+ } else if (active) {
+ mediaLabel = `${task.status === 'queued' ? t('排队中') : t('生成中')}:${alt}`;
+ } else if (failed) {
+ mediaLabel = `${t('生成失败')}:${alt}`;
+ }
+
+ return (
+
+
+ {task.status === 'success' ? (
+ task.kind === 'video' ? (
+
+ ) : (
+
+ )
+ ) : null}
+ {active ? (
+
+ ) : null}
+ {failed ? : null}
+ {task.kind === 'video' && task.duration > 0 && !active ? (
+
+ {formatSeconds(task.duration)}
+
+ ) : null}
+ {selecting && selectable ? (
+
+ {selected ? : null}
+
+ ) : null}
+
+
+ {!selecting ? (
+
+ {active && task.cancelable ? (
+ onCancel?.(task)}
+ >
+ {t('取消')}
+
+ ) : null}
+ {!active ? (
+ onFavorite?.(task)}
+ >
+
+
+ ) : null}
+ {actions.length ? (
+
+ {actions.map((action) => (
+ action.onClick(task)}
+ >
+ {action.label}
+
+ ))}
+
+ }
+ >
+
+
+
+
+ ) : null}
+
+ ) : null}
+
+
+
+ {task.prompt || t('(无提示词)')}
+
+
+ {task.model || t('未知模型')}
+ {task.kind === 'image' && task.size ? (
+ {task.size.replace('x', '×')}
+ ) : null}
+ {task.kind === 'video' && task.resolution ? (
+ {task.resolution}
+ ) : null}
+
+
+
+ );
+};
+
+export default memo(WorkCard);
diff --git a/src/components/creation/WorkFeed/WorkDetailDrawer.jsx b/src/components/creation/WorkFeed/WorkDetailDrawer.jsx
new file mode 100644
index 00000000..6cca8b17
--- /dev/null
+++ b/src/components/creation/WorkFeed/WorkDetailDrawer.jsx
@@ -0,0 +1,367 @@
+/*
+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 .
+
+For commercial licensing, please contact support@quantumnous.com
+*/
+
+import React, { useEffect, useRef, useState } from 'react';
+import { Button, SideSheet, Spin } from '@douyinfe/semi-ui';
+import { Copy, Star } from 'lucide-react';
+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 (
+
+ {failed ? t('视频暂不可用') : }
+
+ );
+ }
+ return (
+ {
+ 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' ? (
+
+ ) : (
+
+ );
+ } else if (active) {
+ media = (
+
+
+ {task.status === 'queued' ? t('排队中') : t('生成中')}
+
+ {estSeconds > 0
+ ? t('已用时 {{elapsed}} / 预计 {{est}}', {
+ elapsed: formatSeconds(elapsed),
+ est: formatSeconds(estSeconds),
+ })
+ : t('已用时 {{elapsed}}', { elapsed: formatSeconds(elapsed) })}
+
+ {isSlowTask(task, p90, now) ? (
+
+ {t('比平时慢,可以切到其他页面,完成后会提醒你')}
+
+ ) : null}
+
+ );
+ } else {
+ media = {t('生成失败')}
;
+ }
+
+ return (
+
+
+
{media}
+
+ {task.kind === 'image' && images.length > 1 ? (
+
+ {images.map((img, i) => (
+
setIndex(i)}
+ >
+ {img.url ? : null}
+
+ ))}
+
+ ) : null}
+
+ {task.status === 'failed' ? (
+
+ {failure ? (
+ <>
+
{failure.title}
+ {failure.detail ?
{failure.detail}
: null}
+ {failure.info.category !== 'unknown' &&
+ failure.title !== task.failReason ? (
+
{task.failReason}
+ ) : null}
+ >
+ ) : (
+
{t('生成失败')}
+ )}
+
+ {failureAction ? (
+
+ {failure.actionLabel}
+
+ ) : null}
+
+ ) : null}
+
+
+ {!active ? (
+
+ }
+ type={task.favorited ? 'warning' : 'tertiary'}
+ aria-pressed={task.favorited}
+ onClick={() => onFavorite(task)}
+ >
+ {task.favorited ? t('已收藏') : t('收藏')}
+
+ ) : null}
+ {active && task.cancelable ? (
+ onCancel(task)}>
+ {t('取消任务')}
+
+ ) : null}
+ {actions.map((action) => (
+ action.onClick(task)}
+ >
+ {action.label}
+
+ ))}
+
+
+
+
+
{t('提示词')}
+ {task.prompt ? (
+ }
+ onClick={async () => {
+ if (await copy(task.prompt)) showSuccess(t('已复制'));
+ }}
+ >
+ {t('复制')}
+
+ ) : null}
+
+ {task.prompt || t('(无提示词)')}
+
+
+
+
+ {t('参数')}
+ {loadingDetail ? (
+
+ ) : null}
+
+
+ {params.map(([label, value]) => (
+
+
{label}
+ {value}
+
+ ))}
+
+
+
+ {!active ?
: null}
+
+
+ );
+};
+
+export default WorkDetailDrawer;
diff --git a/src/components/creation/WorkFeed/WorkFeed.jsx b/src/components/creation/WorkFeed/WorkFeed.jsx
new file mode 100644
index 00000000..f319d263
--- /dev/null
+++ b/src/components/creation/WorkFeed/WorkFeed.jsx
@@ -0,0 +1,988 @@
+/*
+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 .
+
+For commercial licensing, please contact support@quantumnous.com
+*/
+
+import React, {
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from 'react';
+import { Button, Modal, Spin } from '@douyinfe/semi-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 (
+
+
+
{t('灵感模板')}
+
+ {kind === 'video'
+ ? t('从一个模板开始你的第一个视频')
+ : t('从一个模板开始你的第一张作品')}
+
+
+ {t('点击模板会填好提示词与推荐参数,可在下方创作台继续修改')}
+
+
+ {groups.map((group) => (
+
+ {group.group ? (
+
+ {t(group.group)}
+ {group.items.length}
+
+ ) : null}
+
+ {group.items.map((tpl) => {
+ const summary = templateParamsSummary(tpl);
+ return (
+ onApply(tpl)}
+ aria-label={t('使用模板:{{title}}', { title: t(tpl.title) })}
+ >
+
+
+
+
+ {t(tpl.title)}
+ {summary ? (
+ {summary}
+ ) : null}
+
+ {tpl.prompt}
+
+ );
+ })}
+
+
+ ))}
+
+ {t('自己写提示词')}
+
+
+ );
+};
+
+/**
+ * 作品流(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: { type: 'danger' },
+ 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: ,
+ onClick: () => reuse(task),
+ });
+ list.push({
+ key: 'regenerate',
+ label: t('再生成'),
+ icon: ,
+ onClick: () => regenerate(task),
+ });
+ }
+ if (done && seedParamOf(task.model)) {
+ list.push({
+ key: 'variation',
+ label: t('换种子再来'),
+ icon: ,
+ onClick: () => variation(task),
+ });
+ }
+ if (kind === 'image' && done && task.images?.[index]?.url) {
+ list.push({
+ key: 'reference',
+ label: t('用作参考图'),
+ icon: ,
+ onClick: () => applyAsReference(task, index),
+ });
+ list.push({
+ key: 'edit',
+ label: t('编辑此图'),
+ icon: ,
+ onClick: () => editImage(task, index),
+ });
+ // 只有服务端判定可复用(reusable_as_input)的结果才能以 task:// 带到视频页
+ if (onUseAsVideoFirstFrame && task.images[index].reusable) {
+ list.push({
+ key: 'video-first-frame',
+ label: t('用作视频首帧'),
+ icon: ,
+ 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: ,
+ onClick: () => handleContinueVideo(task),
+ });
+ }
+ if (done) {
+ list.push({
+ key: 'download',
+ label: t('下载'),
+ icon: ,
+ onClick: () => download(task, index),
+ });
+ }
+ if (!active) {
+ list.push({
+ key: 'delete',
+ label: t('删除'),
+ icon: ,
+ 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 (
+
+ );
+ };
+ const liveRegion = (
+
+ {announcement}
+
+ );
+
+ if (loading && tasks.length === 0) {
+ return (
+
+ {liveRegion}
+
+ {Array.from({ length: 8 }, (_, i) => (
+
+ ))}
+
+
+ );
+ }
+
+ if (error && tasks.length === 0) {
+ return (
+
+ {liveRegion}
+
+
{t('作品加载失败')}
+
{t('请检查网络后重试')}
+
{t('重试')}
+
+
+ );
+ }
+
+ if (tasks.length === 0 && !filtered) {
+ return (
+
+ {liveRegion}
+ {
+ if (form.applyTemplate(tpl)) {
+ showSuccess(t('已套用模板:{{title}}', { title: t(tpl.title) }));
+ }
+ }}
+ onStart={form.requestFocus}
+ />
+
+ );
+ }
+
+ return (
+
+ {liveRegion}
+
+ {selecting ? (
+
+
+ {t('已选 {{n}} / {{max}} 张,选择 2~4 张已完成的图片进行对比', {
+ n: selectedIds.length,
+ max: COMPARE_MAX,
+ })}
+
+ setCompareOpen(true)}
+ >
+ {t('对比')}
+
+ onSelectingChange?.(false)}>
+ {t('取消')}
+
+
+ ) : null}
+
+ {visibleTasks.length === 0 ? (
+
+
{t('没有符合条件的作品')}
+ {hasMore && autoLoad ? (
+
{t('正在继续查找更早的作品…')}
+ ) : null}
+ {hasMore && !autoLoad ? (
+
{t('已加载的作品中没有匹配项,可继续加载更早的作品')}
+ ) : null}
+
+ {hasMore && !autoLoad ? (
+
+ {t('加载更多')}
+
+ ) : null}
+ {t('清除筛选')}
+
+
+ ) : (
+ groups.map((group) => (
+
+
+ {t(GROUP_LABEL_KEYS[group.key])}
+ {group.tasks.length}
+
+
+ {groupBatchRows(group.tasks).map((row) =>
+ row.type === 'batch' ? (
+
+
+
+
+ {t('对比生成 · {{n}} 个模型', {
+ n: row.tasks.length,
+ })}
+
+ {kind === 'image' && !selecting ? (
+ openBatchCompare(row.tasks)}
+ >
+ {t('对比视图')}
+
+ ) : null}
+
+
+ {row.tasks.map((task) => renderCard(task))}
+
+
+ ) : (
+ renderCard(row.task)
+ ),
+ )}
+
+
+ ))
+ )}
+
+
+ {loadingMore ? : null}
+ {!loadingMore && error ? (
+
+ {t('加载失败,点击重试')}
+
+ ) : null}
+ {!loadingMore &&
+ !error &&
+ hasMore &&
+ !autoLoad &&
+ visibleTasks.length > 0 ? (
+
+ {t('加载更多')}
+
+ ) : null}
+ {!loadingMore && !error && !hasMore && tasks.length > PAGE_SIZE ? (
+ {t('没有更多了')}
+ ) : null}
+
+
+
+
+ {kind === 'image' ? (
+
{
+ setCompareOpen(false);
+ setBatchCompare(null);
+ }}
+ />
+ ) : null}
+
+ );
+};
+
+export default WorkFeed;
diff --git a/src/components/creation/WorkFeed/work-feed.css b/src/components/creation/WorkFeed/work-feed.css
new file mode 100644
index 00000000..8b3a9aa1
--- /dev/null
+++ b/src/components/creation/WorkFeed/work-feed.css
@@ -0,0 +1,962 @@
+/*
+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 .
+
+For commercial licensing, please contact support@quantumnous.com
+*/
+
+/*
+ * 作品流(WP B-6,方案 §4.1 / §4.4 / §4.5)。
+ * 配色全部从 --studio-*(creation.css)与语义 token 派生;不画整页背景。
+ */
+.wf {
+ --wf-radius: 12px;
+ --wf-media-bg: color-mix(in srgb, var(--text-primary) 5%, transparent);
+ --wf-overlay: color-mix(in srgb, var(--surface-card) 82%, transparent);
+ --wf-scrim: color-mix(in srgb, var(--text-primary) 55%, transparent);
+ --wf-on-scrim: var(--surface-card);
+ --wf-success: var(--semi-color-success);
+ --wf-warning: var(--semi-color-warning);
+
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+ padding-top: 4px;
+}
+
+.wf-sr-only {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ overflow: hidden;
+ clip: rect(0 0 0 0);
+ white-space: nowrap;
+}
+
+/* ---------- 分组 ---------- */
+.wf-group-title {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin: 0 0 8px;
+ color: var(--studio-muted);
+ font-size: 12px;
+ font-weight: 600;
+ letter-spacing: 0.04em;
+}
+
+.wf-group-count {
+ font-variant-numeric: tabular-nums;
+ font-weight: 500;
+ opacity: 0.8;
+}
+
+.wf-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
+ align-items: start;
+ gap: 12px;
+}
+
+/* ---------- 卡片 ---------- */
+.wf-card {
+ position: relative;
+ min-width: 0;
+ overflow: hidden;
+ border: 1px solid var(--studio-line);
+ border-radius: var(--wf-radius);
+ background: var(--studio-card);
+ transition:
+ transform var(--studio-dur),
+ box-shadow var(--studio-dur),
+ border-color var(--studio-dur);
+}
+
+.wf-card:hover {
+ border-color: color-mix(in srgb, var(--semi-color-primary) 30%, transparent);
+ box-shadow: 0 6px 20px color-mix(in srgb, var(--text-primary) 8%, transparent);
+ transform: translateY(-1px);
+}
+
+.wf-card.is-selected {
+ border-color: var(--studio-accent);
+ box-shadow: 0 0 0 2px var(--studio-tint);
+}
+
+.wf-media {
+ position: relative;
+ display: block;
+ width: 100%;
+ overflow: hidden;
+ padding: 0;
+ border: 0;
+ background: var(--wf-media-bg);
+ color: inherit;
+ cursor: pointer;
+}
+
+.wf-media img,
+.wf-media video {
+ display: block;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+}
+
+.wf-media:focus-visible {
+ outline: 2px solid var(--studio-ring);
+ outline-offset: -2px;
+}
+
+.wf-grid4 {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ grid-template-rows: 1fr 1fr;
+ gap: 2px;
+ width: 100%;
+ height: 100%;
+}
+
+.wf-grid4 > * {
+ min-width: 0;
+ min-height: 0;
+ overflow: hidden;
+}
+
+.wf-placeholder {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ width: 100%;
+ height: 100%;
+ padding: 12px;
+ color: var(--studio-muted);
+ font-size: 12px;
+ text-align: center;
+}
+
+.wf-badge {
+ position: absolute;
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ padding: 2px 8px;
+ border-radius: 999px;
+ background: var(--wf-scrim);
+ color: var(--wf-on-scrim);
+ font-size: 11px;
+ font-variant-numeric: tabular-nums;
+ pointer-events: none;
+}
+
+.wf-badge--br {
+ right: 8px;
+ bottom: 8px;
+}
+
+.wf-badge--bl {
+ left: 8px;
+ bottom: 8px;
+}
+
+/* 悬停操作:收藏 + 更多(触屏常显) */
+.wf-tools {
+ position: absolute;
+ top: 8px;
+ right: 8px;
+ display: flex;
+ gap: 6px;
+ opacity: 0;
+ transition: opacity var(--studio-dur);
+}
+
+.wf-card:hover .wf-tools,
+.wf-card:focus-within .wf-tools,
+.wf-tools.is-pinned {
+ opacity: 1;
+}
+
+@media (hover: none) {
+ .wf-tools {
+ opacity: 1;
+ }
+}
+
+.wf-icon-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 30px;
+ height: 30px;
+ padding: 0;
+ border: 1px solid var(--studio-line);
+ border-radius: 8px;
+ background: var(--wf-overlay);
+ color: var(--studio-ink);
+ cursor: pointer;
+ backdrop-filter: blur(8px);
+}
+
+.wf-icon-btn:hover {
+ border-color: color-mix(in srgb, var(--semi-color-primary) 45%, transparent);
+ color: var(--studio-accent);
+}
+
+.wf-icon-btn.is-on {
+ color: var(--wf-warning);
+}
+
+.wf-check {
+ position: absolute;
+ top: 8px;
+ left: 8px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 22px;
+ height: 22px;
+ border: 2px solid var(--wf-on-scrim);
+ border-radius: 6px;
+ background: var(--wf-scrim);
+ color: var(--wf-on-scrim);
+ pointer-events: none;
+}
+
+.wf-card.is-selected .wf-check {
+ border-color: var(--studio-accent);
+ background: var(--studio-accent);
+}
+
+.wf-body {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ padding: 8px 10px 10px;
+ min-width: 0;
+}
+
+.wf-prompt {
+ overflow: hidden;
+ margin: 0;
+ color: var(--studio-ink);
+ font-size: 12px;
+ line-height: 1.5;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.wf-meta {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ min-width: 0;
+ color: var(--studio-muted);
+ font-size: 11px;
+}
+
+.wf-meta > span {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.wf-num {
+ font-variant-numeric: tabular-nums;
+}
+
+/* ---------- 进行中 ---------- */
+.wf-active {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ padding: 12px;
+ background: linear-gradient(
+ 110deg,
+ var(--wf-media-bg) 30%,
+ color-mix(in srgb, var(--semi-color-primary) 10%, transparent) 50%,
+ var(--wf-media-bg) 70%
+ );
+ background-size: 200% 100%;
+ animation: wf-shimmer 1.8s linear infinite;
+ color: var(--studio-muted);
+ font-size: 12px;
+ text-align: center;
+}
+
+.wf-active-label {
+ color: var(--studio-ink);
+ font-weight: 600;
+}
+
+.wf-progress {
+ width: 70%;
+ height: 4px;
+ overflow: hidden;
+ border-radius: 999px;
+ background: color-mix(in srgb, var(--semi-color-primary) 15%, transparent);
+}
+
+.wf-progress > span {
+ display: block;
+ height: 100%;
+ background: var(--studio-accent);
+ transition: width 0.2s;
+}
+
+@keyframes wf-shimmer {
+ to {
+ background-position: -200% 0;
+ }
+}
+
+/* ---------- 失败 ---------- */
+.wf-failed {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ padding: 12px;
+ color: var(--studio-muted);
+ font-size: 12px;
+ text-align: center;
+}
+
+.wf-failed-title {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ color: var(--studio-danger);
+ font-weight: 600;
+}
+
+.wf-failed-reason {
+ display: -webkit-box;
+ overflow: hidden;
+ -webkit-box-orient: vertical;
+ -webkit-line-clamp: 3;
+ word-break: break-word;
+}
+
+.wf-refund {
+ color: var(--wf-success);
+ font-variant-numeric: tabular-nums;
+}
+
+/* ---------- 状态区 ---------- */
+.wf-state {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 10px;
+ min-height: 240px;
+ padding: 24px 16px;
+ color: var(--studio-muted);
+ font-size: 13px;
+ text-align: center;
+}
+
+.wf-state-title {
+ margin: 0;
+ color: var(--studio-ink);
+ font-size: 15px;
+ font-weight: 600;
+}
+
+.wf-skeleton {
+ border-radius: var(--wf-radius);
+ background: linear-gradient(
+ 110deg,
+ var(--wf-media-bg) 30%,
+ color-mix(in srgb, var(--text-primary) 9%, transparent) 50%,
+ var(--wf-media-bg) 70%
+ );
+ background-size: 200% 100%;
+ animation: wf-shimmer 1.8s linear infinite;
+ aspect-ratio: 1;
+}
+
+.wf-more {
+ display: flex;
+ justify-content: center;
+ min-height: 40px;
+ padding: 8px 0 4px;
+ color: var(--studio-muted);
+ font-size: 12px;
+}
+
+/* 多选对比操作条 */
+.wf-selectbar {
+ position: sticky;
+ top: 0;
+ z-index: 2;
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 8px;
+ padding: 8px 12px;
+ border: 1px solid
+ color-mix(in srgb, var(--semi-color-primary) 25%, transparent);
+ border-radius: var(--wf-radius);
+ background: color-mix(
+ in srgb,
+ var(--semi-color-primary) 6%,
+ var(--surface-card)
+ );
+ font-size: 13px;
+}
+
+.wf-selectbar-text {
+ flex: 1;
+ min-width: 0;
+}
+
+/* ---------- 筛选栏 ---------- */
+.wf-filters {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ justify-content: flex-end;
+ gap: 8px;
+ min-width: 0;
+}
+
+.wf-filters .semi-select {
+ min-width: 112px;
+ max-width: 180px;
+}
+
+.wf-filters-search {
+ width: 200px;
+ max-width: 100%;
+}
+
+.wf-filter-panel {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ width: 280px;
+ max-width: 100%;
+ padding: 4px;
+}
+
+.wf-filter-panel .semi-select,
+.wf-filter-panel .semi-input-wrapper {
+ width: 100%;
+}
+
+.wf-filter-panel-label {
+ margin-bottom: 4px;
+ color: var(--text-secondary);
+ font-size: 12px;
+}
+
+.wf-filter-panel-actions {
+ display: flex;
+ justify-content: space-between;
+ gap: 8px;
+}
+
+.wf-filter-sheet .wf-filter-panel {
+ width: 100%;
+ padding: 0 0 calc(8px + env(safe-area-inset-bottom, 0px));
+}
+
+/* ---------- 详情抽屉 ---------- */
+.wf-detail {
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+ color: var(--studio-ink, var(--text-primary));
+}
+
+.wf-detail-media {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ overflow: hidden;
+ border-radius: var(--wf-radius);
+ background: color-mix(in srgb, var(--text-primary) 5%, transparent);
+ min-height: 200px;
+}
+
+.wf-detail-media img,
+.wf-detail-media video {
+ display: block;
+ max-width: 100%;
+ max-height: 62vh;
+ object-fit: contain;
+}
+
+.wf-thumbs {
+ display: flex;
+ gap: 8px;
+ overflow-x: auto;
+}
+
+.wf-thumb {
+ flex-shrink: 0;
+ width: 64px;
+ height: 64px;
+ overflow: hidden;
+ padding: 0;
+ border: 2px solid transparent;
+ border-radius: 8px;
+ background: color-mix(in srgb, var(--text-primary) 5%, transparent);
+ cursor: pointer;
+}
+
+.wf-thumb img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+}
+
+.wf-thumb.is-active {
+ border-color: var(--semi-color-primary);
+}
+
+.wf-detail-section-title {
+ margin: 0 0 6px;
+ color: var(--text-secondary);
+ font-size: 12px;
+ font-weight: 600;
+ letter-spacing: 0.04em;
+}
+
+.wf-detail-prompt {
+ margin: 0;
+ max-height: 180px;
+ overflow-y: auto;
+ padding: 10px 12px;
+ border: 1px solid var(--border-subtle);
+ border-radius: 10px;
+ font-size: 13px;
+ line-height: 1.6;
+ white-space: pre-wrap;
+ word-break: break-word;
+}
+
+.wf-params {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
+ gap: 8px 16px;
+ margin: 0;
+}
+
+.wf-params dt {
+ color: var(--text-secondary);
+ font-size: 12px;
+}
+
+.wf-params dd {
+ margin: 2px 0 0;
+ overflow: hidden;
+ font-size: 13px;
+ font-variant-numeric: tabular-nums;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.wf-detail-actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+}
+
+.wf-detail-alert {
+ padding: 10px 12px;
+ border: 1px solid
+ color-mix(in srgb, var(--semi-color-danger) 30%, transparent);
+ border-radius: 10px;
+ background: color-mix(in srgb, var(--semi-color-danger) 6%, transparent);
+ font-size: 13px;
+ word-break: break-word;
+}
+
+.wf button:focus-visible,
+.wf-detail button:focus-visible,
+.wf-filters button:focus-visible {
+ outline: 2px solid
+ color-mix(in srgb, var(--semi-color-primary) 55%, transparent);
+ outline-offset: 2px;
+}
+
+@media (max-width: 767px) {
+ .wf-grid {
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 8px;
+ }
+
+ .wf-body {
+ padding: 6px 8px 8px;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .wf-card,
+ .wf-tools,
+ .wf-progress > span {
+ transition: none;
+ }
+
+ .wf-card:hover {
+ transform: none;
+ }
+
+ .wf-active,
+ .wf-skeleton {
+ animation: none;
+ }
+}
+
+/* ---------- 空状态:灵感模板墙(WP B-7) ---------- */
+.wf-wall {
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+ max-width: 1080px;
+ margin: 0 auto;
+ padding: 8px 0 16px;
+ width: 100%;
+}
+
+.wf-wall-eyebrow {
+ margin: 0 0 4px;
+ color: var(--studio-accent, var(--semi-color-primary));
+ font-size: 11px;
+ font-weight: 600;
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+}
+
+.wf-wall-title {
+ margin: 0;
+ color: var(--studio-ink, var(--text-primary));
+ font-size: 18px;
+ font-weight: 700;
+ letter-spacing: -0.01em;
+}
+
+.wf-wall-desc {
+ margin: 4px 0 0;
+ color: var(--studio-muted, var(--text-secondary));
+ font-size: 13px;
+}
+
+.wf-wall-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
+ gap: 10px;
+}
+
+.wf-tpl {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ min-width: 0;
+ padding: 12px;
+ border: 1px solid var(--studio-line, var(--border-subtle));
+ border-radius: var(--wf-radius);
+ background: var(--studio-card, var(--surface-card));
+ color: var(--studio-ink, var(--text-primary));
+ text-align: left;
+ cursor: pointer;
+ transition:
+ border-color var(--studio-dur, 150ms),
+ transform var(--studio-dur, 150ms),
+ background-color var(--studio-dur, 150ms);
+}
+
+.wf-tpl:hover {
+ border-color: color-mix(in srgb, var(--semi-color-primary) 45%, transparent);
+ background: color-mix(
+ in srgb,
+ var(--semi-color-primary) 4%,
+ var(--surface-card)
+ );
+ transform: translateY(-1px);
+}
+
+.wf-tpl-head {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-width: 0;
+}
+
+.wf-tpl-icon {
+ display: inline-flex;
+ flex-shrink: 0;
+ align-items: center;
+ justify-content: center;
+ width: 28px;
+ height: 28px;
+ border-radius: 8px;
+ background: color-mix(in srgb, var(--semi-color-primary) 10%, transparent);
+ color: var(--semi-color-primary);
+}
+
+.wf-tpl-title {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ font-size: 13px;
+ font-weight: 600;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.wf-tpl-meta {
+ flex-shrink: 0;
+ color: var(--studio-muted, var(--text-secondary));
+ font-size: 11px;
+ font-variant-numeric: tabular-nums;
+}
+
+.wf-tpl-prompt {
+ display: -webkit-box;
+ overflow: hidden;
+ color: var(--studio-muted, var(--text-secondary));
+ font-size: 12px;
+ line-height: 1.5;
+ -webkit-box-orient: vertical;
+ -webkit-line-clamp: 2;
+ overflow-wrap: anywhere;
+}
+
+.wf-tpl:focus-visible {
+ outline: 2px solid
+ color-mix(in srgb, var(--semi-color-primary) 55%, transparent);
+ outline-offset: 2px;
+}
+
+.wf-wall-foot {
+ display: flex;
+ justify-content: center;
+}
+
+.wf-state-actions {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: center;
+ gap: 8px;
+}
+
+.wf-detail-alert {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 4px;
+}
+
+.wf-detail-raw {
+ color: var(--text-secondary);
+ font-size: 12px;
+}
+
+@media (max-width: 767px) {
+ .wf-wall-grid {
+ grid-template-columns: minmax(0, 1fr);
+ }
+
+ .wf-wall-title {
+ font-size: 16px;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .wf-tpl {
+ transition: none;
+ }
+
+ .wf-tpl:hover {
+ transform: none;
+ }
+}
+
+/* ---------- 获取 API 代码(WP C-1):详情抽屉在 portal 中,直接用语义 token ---------- */
+.wf-api {
+ border: 1px solid var(--border-subtle);
+ border-radius: 12px;
+ overflow: hidden;
+}
+
+.wf-api-toggle {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ width: 100%;
+ padding: 10px 12px;
+ border: 0;
+ background: transparent;
+ color: var(--text-primary);
+ font-size: 13px;
+ font-weight: 600;
+ text-align: left;
+ cursor: pointer;
+}
+
+.wf-api-toggle:hover {
+ background: color-mix(in srgb, var(--semi-color-primary) 5%, transparent);
+}
+
+.wf-api-toggle:focus-visible,
+.wf-api-tab:focus-visible,
+.wf-api-code:focus-visible {
+ outline: 2px solid
+ color-mix(in srgb, var(--semi-color-primary) 55%, transparent);
+ outline-offset: 2px;
+}
+
+.wf-api-title {
+ flex: 1;
+ min-width: 0;
+}
+
+.wf-api-badge {
+ padding: 1px 8px;
+ border-radius: 999px;
+ background: color-mix(in srgb, var(--semi-color-success) 12%, transparent);
+ color: var(--semi-color-success);
+ font-size: 11px;
+ font-weight: 600;
+}
+
+.wf-api-caret {
+ color: var(--text-secondary);
+ transition: transform 150ms ease;
+}
+
+.wf-api-caret.is-open {
+ transform: rotate(180deg);
+}
+
+.wf-api-body {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ padding: 0 12px 12px;
+}
+
+.wf-api-desc,
+.wf-api-hint {
+ margin: 0;
+ color: var(--text-secondary);
+ font-size: 12px;
+}
+
+.wf-api-bar,
+.wf-api-foot {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+}
+
+.wf-api-tabs {
+ display: inline-flex;
+ padding: 2px;
+ border-radius: 8px;
+ background: color-mix(in srgb, var(--text-primary) 6%, transparent);
+}
+
+.wf-api-tab {
+ padding: 3px 10px;
+ border: 0;
+ border-radius: 6px;
+ background: transparent;
+ color: var(--text-secondary);
+ font-size: 12px;
+ cursor: pointer;
+}
+
+.wf-api-tab.is-active {
+ background: var(--surface-card);
+ color: var(--text-primary);
+ font-weight: 600;
+}
+
+.wf-api-code {
+ max-height: 320px;
+ margin: 0;
+ overflow: auto;
+ padding: 10px 12px;
+ border: 1px solid var(--border-subtle);
+ border-radius: 8px;
+ background: color-mix(in srgb, var(--text-primary) 4%, var(--surface-card));
+ color: var(--text-primary);
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
+ font-size: 12px;
+ line-height: 1.55;
+ white-space: pre;
+}
+
+.wf-api-notes {
+ margin: 0;
+ padding-left: 18px;
+ color: var(--text-secondary);
+ font-size: 12px;
+ line-height: 1.6;
+ word-break: break-word;
+}
+
+/* ---------- 对比生成成组(WP C-2) ---------- */
+.wf-batch {
+ grid-column: 1 / -1;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ padding: 10px;
+ border: 1px solid
+ color-mix(in srgb, var(--semi-color-primary) 25%, transparent);
+ border-radius: 14px;
+ background: color-mix(in srgb, var(--semi-color-primary) 4%, transparent);
+}
+
+.wf-batch-head {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 8px;
+ color: var(--text-secondary);
+ font-size: 12px;
+ font-weight: 600;
+}
+
+.wf-batch-title {
+ flex: 1;
+ min-width: 0;
+ color: var(--text-primary);
+}
+
+/* ---------- 慢任务提示(WP C-4) ---------- */
+.wf-slow {
+ max-width: 92%;
+ color: var(--wf-warning, var(--semi-color-warning));
+ font-size: 11px;
+ line-height: 1.4;
+ text-align: center;
+}
diff --git a/src/components/creation/batchConfirm.js b/src/components/creation/batchConfirm.js
new file mode 100644
index 00000000..781acca7
--- /dev/null
+++ b/src/components/creation/batchConfirm.js
@@ -0,0 +1,39 @@
+/*
+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 .
+
+For commercial licensing, please contact support@quantumnous.com
+*/
+
+import { Modal } from '@douyinfe/semi-ui';
+import { formatQuoteAmount } from '../../hooks/creation/useCreationQuote';
+
+/**
+ * 多张生成合计超过系统阈值时的二次确认弹窗(方案 §4.4 / 决策 3)。
+ * 手动提交(CreationDock)与自动提交(再生成 / 换种子再来,useCreationForm)共用。
+ */
+export const openBatchConfirm = ({ t, n, quote, onOk, onCancel }) => {
+ const amount = formatQuoteAmount(quote?.display_amount, quote?.currency);
+ Modal.confirm({
+ title: t('确认生成 {{n}} 张图片?', { n }),
+ content: amount
+ ? t('本次预计消耗 {{amount}},金额较高,请确认后再生成', { amount })
+ : t('本次合计金额较高,请确认后再生成'),
+ okText: t('确认生成'),
+ cancelText: t('取消'),
+ onOk: () => onOk(),
+ onCancel: () => onCancel && onCancel(),
+ });
+};
diff --git a/src/components/creation/creation-dock.css b/src/components/creation/creation-dock.css
new file mode 100644
index 00000000..f9a0f670
--- /dev/null
+++ b/src/components/creation/creation-dock.css
@@ -0,0 +1,599 @@
+/*
+ * 创作台 CreationDock(WP B-3,方案 §4.1 / §4.4)。
+ * 基础卡片样式(.cs-dock / .cs-chip / .cs-slots …)在 creation.css,这里只补创作台专有部分。
+ * 配色全部从 token 派生(--studio-* 定义在 .creation-studio 上)。
+ */
+
+/* 展开态隐藏体验中心的移动端底部导航(body class 由 CreationDock 在展开期间添加) */
+body.cs-dock-expanded .exp-mobile-bottom-nav {
+ display: none;
+}
+
+.cs-dock-spacer {
+ flex: 1;
+ min-width: 4px;
+}
+
+.cs-tool {
+ color: var(--studio-muted);
+}
+
+.cs-chip-text {
+ max-width: 140px;
+ overflow: hidden;
+ white-space: nowrap;
+ text-overflow: ellipsis;
+ font-variant-numeric: tabular-nums;
+}
+
+.cs-mode-chip {
+ font-weight: 600;
+ border-color: color-mix(in srgb, var(--semi-color-primary) 35%, transparent);
+ color: var(--studio-accent);
+}
+
+.cs-mode-chip.is-static {
+ cursor: default;
+}
+
+.cs-mode-item {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+}
+
+.cs-mode-reason {
+ color: var(--studio-muted);
+ font-size: 11px;
+}
+
+/* ---------- 图片槽 ---------- */
+.cs-slot-cell {
+ position: relative;
+}
+
+.cs-slot.is-missing {
+ border-color: var(--semi-color-warning);
+ box-shadow: 0 0 0 2px
+ color-mix(in srgb, var(--semi-color-warning) 25%, transparent);
+}
+
+.cs-slot-move {
+ position: absolute;
+ bottom: 22px;
+ left: 4px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 20px;
+ height: 20px;
+ border: 0;
+ border-radius: 999px;
+ background: color-mix(in srgb, var(--surface-card) 85%, transparent);
+ color: var(--studio-ink);
+ cursor: pointer;
+}
+
+.cs-hidden-input {
+ display: none;
+}
+
+.cs-pending {
+ display: inline-flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 6px;
+ padding: 4px 8px;
+ border: 1px solid
+ color-mix(in srgb, var(--semi-color-primary) 25%, transparent);
+ border-radius: 12px;
+ background: color-mix(
+ in srgb,
+ var(--semi-color-primary) 5%,
+ var(--surface-card)
+ );
+ font-size: 12px;
+}
+
+.cs-pending-text {
+ color: var(--studio-ink);
+}
+
+.cs-note.is-warn {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ color: var(--semi-color-warning);
+ font-size: 12px;
+}
+
+.cs-link {
+ padding: 0;
+ border: 0;
+ background: none;
+ color: var(--studio-accent);
+ font-size: 12px;
+ text-decoration: underline;
+ cursor: pointer;
+}
+
+/* ---------- 「图N」引用 ---------- */
+.cs-refs {
+ gap: 6px;
+}
+
+.cs-ref-token {
+ height: 24px;
+ padding: 0 8px;
+ border: 1px dashed
+ color-mix(in srgb, var(--semi-color-primary) 40%, transparent);
+ border-radius: 8px;
+ background: var(--studio-tint);
+ color: var(--studio-accent);
+ font-size: 12px;
+ cursor: pointer;
+}
+
+.cs-generate-wrap {
+ display: inline-flex;
+}
+
+.cs-pulse {
+ animation: cs-pulse 1.2s ease-in-out infinite;
+}
+
+@keyframes cs-pulse {
+ 50% {
+ opacity: 0.4;
+ }
+}
+
+/* ---------- 弹层 ---------- */
+.cs-popover {
+ max-width: min(420px, calc(100vw - 32px));
+}
+
+.cs-pop-body {
+ padding: 12px;
+}
+
+.cs-pop-title {
+ margin-bottom: 8px;
+ color: var(--text-secondary);
+ font-size: 12px;
+ font-weight: 600;
+}
+
+.cs-advanced-pop .cs-pop-body {
+ width: min(400px, calc(100vw - 32px));
+ max-height: 60vh;
+ overflow-y: auto;
+}
+
+.cs-templates {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 8px;
+ max-height: 360px;
+ margin: 0;
+ padding: 0;
+ overflow-y: auto;
+ list-style: none;
+}
+
+.cs-templates-pop .cs-pop-body {
+ width: min(400px, calc(100vw - 32px));
+}
+
+.cs-template {
+ display: flex;
+ gap: 8px;
+ width: 100%;
+ padding: 8px;
+ border: 1px solid var(--border-subtle);
+ border-radius: 12px;
+ background: transparent;
+ color: var(--text-primary);
+ text-align: left;
+ cursor: pointer;
+ transition:
+ border-color 150ms,
+ background-color 150ms;
+}
+
+.cs-template:hover {
+ border-color: color-mix(in srgb, var(--semi-color-primary) 45%, transparent);
+ background: color-mix(in srgb, var(--semi-color-primary) 5%, transparent);
+}
+
+.cs-template-icon {
+ display: inline-flex;
+ flex-shrink: 0;
+ align-items: center;
+ justify-content: center;
+ width: 32px;
+ height: 32px;
+ border-radius: 8px;
+ background: color-mix(in srgb, var(--semi-color-primary) 10%, transparent);
+ color: var(--semi-color-primary);
+}
+
+.cs-template-main {
+ display: flex;
+ flex-direction: column;
+ min-width: 0;
+ gap: 2px;
+}
+
+.cs-template-title {
+ font-size: 13px;
+ font-weight: 600;
+}
+
+.cs-template-prompt {
+ display: -webkit-box;
+ overflow: hidden;
+ color: var(--text-secondary);
+ font-size: 11px;
+ -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical;
+}
+
+.cs-pop-body button:focus-visible,
+.cs-template:focus-visible {
+ outline: 2px solid
+ color-mix(in srgb, var(--semi-color-primary) 55%, transparent);
+ outline-offset: 2px;
+}
+
+/* ---------- 收起态(移动端 / 矮屏桌面) ---------- */
+.cs-dock--collapsed {
+ flex-direction: row;
+ align-items: center;
+ gap: 8px;
+ height: 56px;
+ padding: 8px;
+}
+
+.cs-collapsed-prompt {
+ display: flex;
+ flex: 1;
+ align-items: center;
+ gap: 6px;
+ min-width: 0;
+ height: 38px;
+ padding: 0 12px;
+ border: 1px solid var(--studio-line);
+ border-radius: 10px;
+ background: transparent;
+ color: var(--studio-ink);
+ font-size: 14px;
+ text-align: left;
+ cursor: text;
+}
+
+.cs-collapsed-prompt.is-placeholder {
+ color: var(--studio-muted);
+}
+
+.cs-collapsed-text {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ white-space: nowrap;
+ text-overflow: ellipsis;
+}
+
+.cs-collapsed-model {
+ flex-shrink: 1;
+ min-width: 0;
+ max-width: 34%;
+}
+
+.cs-collapsed-model .mp-trigger {
+ max-width: 100%;
+}
+
+/* ---------- 展开态:覆盖作品流,不挤压 ---------- */
+.cs-dock-placeholder {
+ height: 56px;
+}
+
+.cs-dock-scrim {
+ position: absolute;
+ z-index: 20;
+ inset: 0;
+ background: var(--semi-color-overlay-bg);
+ opacity: 0.35;
+}
+
+.cs-dock.is-expanded {
+ position: absolute;
+ z-index: 30;
+ right: 16px;
+ bottom: calc(12px + env(safe-area-inset-bottom, 0px));
+ left: 16px;
+ max-height: calc(100% - 24px);
+ overflow-y: auto;
+}
+
+.cs-dock-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+}
+
+.cs-dock-head-title {
+ font-size: 13px;
+ font-weight: 600;
+}
+
+.cs-icon-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 28px;
+ height: 28px;
+ border: 0;
+ border-radius: 8px;
+ background: transparent;
+ color: var(--studio-muted);
+ cursor: pointer;
+}
+
+/* 矮屏桌面也用一行横向滚动的参数 chip */
+@media (max-height: 799px) {
+ .cs-dock.is-expanded .cs-dock-controls {
+ flex-wrap: nowrap;
+ overflow-x: auto;
+ scrollbar-width: none;
+ }
+
+ .cs-dock.is-expanded .cs-dock-controls > * {
+ flex-shrink: 0;
+ }
+}
+
+@media (max-width: 767px) {
+ /* 移动端:展开态贴视口底部(底部导航已隐藏),键盘弹起时跟随可视视口 */
+ .cs-dock-scrim {
+ position: fixed;
+ z-index: 55;
+ }
+
+ .cs-dock.is-expanded {
+ position: fixed;
+ z-index: 60;
+ right: 0;
+ bottom: var(--cs-kb-offset, 0px);
+ left: 0;
+ max-height: calc(100dvh - 120px - var(--cs-kb-offset, 0px));
+ padding-bottom: calc(10px + env(safe-area-inset-bottom, 0px));
+ border-radius: 14px 14px 0 0;
+ }
+
+ .cs-templates {
+ grid-template-columns: minmax(0, 1fr);
+ max-height: none;
+ }
+
+ .cs-collapsed-model .mp-trigger-name {
+ max-width: 88px;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .cs-pulse {
+ animation: none;
+ }
+
+ .cs-template {
+ transition: none;
+ }
+}
+
+/* 提示词历史(WP B-6) */
+.cs-history-item {
+ display: block;
+ max-width: min(320px, 70vw);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+/* 真人人像素材入口(视频首帧,WP B-6) */
+.cs-portrait {
+ display: flex;
+ align-items: center;
+}
+
+/* ---------- 状态提示行(WP B-7:错误映射 / 预算不足 / 等级锁定 / 参数调整) ---------- */
+.cs-alert {
+ flex-wrap: nowrap;
+ align-items: flex-start;
+ gap: 8px;
+ padding: 8px 10px;
+ border: 1px solid var(--studio-line);
+ border-radius: 12px;
+ background: color-mix(in srgb, var(--semi-color-primary) 4%, transparent);
+ color: var(--studio-ink);
+ font-size: 12px;
+}
+
+.cs-alert > svg {
+ flex-shrink: 0;
+ margin-top: 2px;
+}
+
+.cs-alert.is-warn {
+ border-color: color-mix(in srgb, var(--semi-color-warning) 35%, transparent);
+ background: color-mix(in srgb, var(--semi-color-warning) 6%, transparent);
+}
+
+.cs-alert.is-warn > svg {
+ color: var(--semi-color-warning);
+}
+
+.cs-alert.is-error {
+ border-color: color-mix(in srgb, var(--semi-color-danger) 35%, transparent);
+ background: color-mix(in srgb, var(--semi-color-danger) 6%, transparent);
+}
+
+.cs-alert.is-error > svg {
+ color: var(--semi-color-danger);
+}
+
+.cs-alert-text {
+ display: flex;
+ flex: 1;
+ flex-direction: column;
+ gap: 2px;
+ min-width: 0;
+ overflow-wrap: anywhere;
+}
+
+.cs-alert-text strong {
+ font-weight: 600;
+}
+
+.cs-alert-text span {
+ color: var(--studio-muted);
+}
+
+.cs-alert .cs-icon-btn {
+ flex-shrink: 0;
+ width: 22px;
+ height: 22px;
+}
+
+/* 内容审核指明的触发图片 */
+.cs-slot.is-flagged {
+ border-color: var(--semi-color-danger);
+ box-shadow: 0 0 0 2px
+ color-mix(in srgb, var(--semi-color-danger) 25%, transparent);
+}
+
+/* 底部抽屉内容让出 iOS / 微信 H5 底部安全区 */
+.cs-sheet .cs-pop-body {
+ padding-bottom: calc(12px + env(safe-area-inset-bottom, 0px));
+}
+
+.cs-dock--state {
+ flex-wrap: wrap;
+ gap: 8px;
+ text-align: center;
+}
+
+/* ---------- 更多菜单(完成通知开关,WP C-4) ---------- */
+.cs-icon-chip {
+ position: relative;
+ padding: 0 8px;
+}
+
+.cs-dot {
+ position: absolute;
+ top: 4px;
+ right: 4px;
+ width: 6px;
+ height: 6px;
+ border-radius: 999px;
+ background: var(--semi-color-primary);
+}
+
+/* ---------- 对比生成提交前摘要(WP C-2):Modal 在 portal 中,直接用语义 token ---------- */
+.cs-summary {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ color: var(--text-primary);
+}
+
+.cs-summary-desc {
+ margin: 0;
+ color: var(--text-secondary);
+ font-size: 12px;
+}
+
+.cs-summary-list {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+
+.cs-summary-row {
+ display: grid;
+ grid-template-columns: minmax(0, 1.2fr) minmax(0, 1.4fr) auto;
+ align-items: center;
+ gap: 4px 12px;
+ padding: 8px 10px;
+ border: 1px solid var(--border-subtle);
+ border-radius: 10px;
+ font-size: 13px;
+}
+
+.cs-summary-model {
+ overflow: hidden;
+ font-weight: 600;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.cs-summary-params {
+ overflow: hidden;
+ color: var(--text-secondary);
+ font-size: 12px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.cs-summary-price,
+.cs-summary-total .cs-num {
+ font-variant-numeric: tabular-nums;
+ font-weight: 600;
+}
+
+.cs-summary-note {
+ grid-column: 1 / -1;
+ color: var(--semi-color-warning);
+ font-size: 11px;
+}
+
+.cs-summary-total {
+ display: flex;
+ justify-content: space-between;
+ padding: 8px 10px 0;
+ border-top: 1px dashed var(--border-subtle);
+ font-size: 13px;
+}
+
+.cs-summary-warn {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 8px 10px;
+ border-radius: 8px;
+ background: color-mix(in srgb, var(--semi-color-warning) 12%, transparent);
+ color: var(--semi-color-warning);
+ font-size: 12px;
+}
+
+.cs-summary-foot {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: flex-end;
+ gap: 8px;
+}
+
+@media (max-width: 639px) {
+ .cs-summary-row {
+ grid-template-columns: minmax(0, 1fr) auto;
+ }
+
+ .cs-summary-params {
+ grid-column: 1 / -1;
+ grid-row: 2;
+ }
+}
diff --git a/src/components/creation/creation.css b/src/components/creation/creation.css
new file mode 100644
index 00000000..87c42eb5
--- /dev/null
+++ b/src/components/creation/creation.css
@@ -0,0 +1,347 @@
+/*
+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 .
+
+For commercial licensing, please contact support@quantumnous.com
+*/
+
+/*
+ * 新创作台外壳(WP B-2,方案 §4.1):头部 / 全宽作品流 / 底部创作台。
+ * - 整页背景由父级 ExperienceCenter 的 提供,这里不画背景。
+ * - 顶栏与跑马灯的让位由 ExperienceCenter 根元素的 hasMarquee 动态 padding 负责,这里不重复计算。
+ * - 配色全部从 token 派生(--studio-*)。
+ */
+.creation-studio {
+ --studio-ink: var(--text-primary);
+ --studio-muted: var(--text-secondary);
+ --studio-line: var(--border-subtle);
+ --studio-accent: var(--semi-color-primary);
+ --studio-tint: color-mix(in srgb, var(--semi-color-primary) 10%, transparent);
+ --studio-card: color-mix(in srgb, var(--surface-card) 92%, transparent);
+ --studio-ring: color-mix(in srgb, var(--semi-color-primary) 55%, transparent);
+ --studio-danger: var(--semi-color-danger);
+ --studio-dur: var(--motion-fast, 150ms);
+
+ /* 创作台展开态(absolute)与遮罩以外壳为定位参照 */
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ min-height: 0;
+ color: var(--studio-ink);
+}
+
+/* ---------- 头部 ---------- */
+.cs-header {
+ display: flex;
+ flex-shrink: 0;
+ align-items: center;
+ gap: 12px;
+ min-width: 0;
+ padding: 12px 16px 8px;
+}
+
+.cs-title {
+ flex-shrink: 0;
+ margin: 0;
+ font-size: 20px;
+ font-weight: 700;
+ letter-spacing: -0.01em;
+}
+
+.cs-filter-slot {
+ flex: 1;
+ min-width: 0;
+}
+
+.cs-balance {
+ display: inline-flex;
+ flex-shrink: 0;
+ align-items: baseline;
+ gap: 6px;
+ font-size: 13px;
+}
+
+.cs-balance-label {
+ color: var(--studio-muted);
+}
+
+.cs-num {
+ font-variant-numeric: tabular-nums;
+ font-weight: 600;
+}
+
+/* ---------- 作品流 ---------- */
+.cs-feed {
+ flex: 1;
+ min-height: 0;
+ overflow-y: auto;
+ padding: 0 16px 12px;
+}
+
+.cs-feed:focus {
+ outline: none;
+}
+
+.cs-feed-hint {
+ margin: 4px 0 0;
+ color: var(--studio-muted);
+ font-size: 12px;
+}
+
+/* ---------- 创作台 ---------- */
+.cs-dock-wrap {
+ flex-shrink: 0;
+ padding: 0 16px calc(12px + env(safe-area-inset-bottom, 0px));
+}
+
+.cs-dock {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ max-width: 1080px;
+ margin: 0 auto;
+ padding: 12px;
+ border: 1px solid var(--studio-line);
+ border-radius: 14px;
+ background: var(--studio-card);
+ box-shadow: 0 8px 28px color-mix(in srgb, var(--text-primary) 8%, transparent);
+ backdrop-filter: blur(16px);
+}
+
+.cs-dock--state {
+ flex-direction: row;
+ align-items: center;
+ justify-content: center;
+ color: var(--studio-muted);
+ font-size: 13px;
+}
+
+.cs-dock-row {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 8px;
+ min-width: 0;
+}
+
+.cs-modes {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+}
+
+.cs-chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ height: 30px;
+ padding: 0 12px;
+ border: 1px solid var(--studio-line);
+ border-radius: 999px;
+ background: transparent;
+ color: var(--studio-ink);
+ font-size: 12px;
+ cursor: pointer;
+ transition:
+ border-color var(--studio-dur),
+ background-color var(--studio-dur);
+}
+
+.cs-chip:hover:not(:disabled) {
+ border-color: color-mix(in srgb, var(--semi-color-primary) 45%, transparent);
+}
+
+.cs-chip.is-active {
+ border-color: var(--studio-accent);
+ background: var(--studio-tint);
+ color: var(--studio-accent);
+}
+
+.cs-chip:disabled {
+ cursor: not-allowed;
+ opacity: 0.5;
+}
+
+.cs-slots {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+}
+
+.cs-slot {
+ width: 88px;
+}
+
+.cs-note {
+ color: var(--studio-muted);
+ font-size: 11px;
+}
+
+.cs-prompt textarea {
+ font-size: 14px;
+}
+
+.cs-advanced {
+ padding: 10px;
+ border: 1px dashed var(--studio-line);
+ border-radius: 12px;
+}
+
+.cs-dock-controls {
+ row-gap: 6px;
+}
+
+.cs-size {
+ min-width: 0;
+ max-width: 100%;
+}
+
+/* 创作台中的常用参数横排、不显示标签 */
+.cs-dock-params.cp-renderer {
+ flex-direction: row;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 8px;
+}
+
+.cs-dock-submit {
+ justify-content: flex-end;
+}
+
+.cs-price {
+ flex: 1;
+ min-width: 0;
+ color: var(--studio-muted);
+ font-size: 12px;
+ font-variant-numeric: tabular-nums;
+}
+
+.cs-block {
+ color: var(--studio-danger);
+}
+
+.cs-kbd {
+ margin-left: 6px;
+ opacity: 0.7;
+ font-size: 11px;
+}
+
+.creation-studio button:focus-visible {
+ outline: 2px solid var(--studio-ring);
+ outline-offset: 2px;
+}
+
+@media (max-width: 767px) {
+ .cs-header {
+ padding: 8px 12px 6px;
+ }
+
+ .cs-title {
+ font-size: 17px;
+ }
+
+ .cs-feed {
+ padding: 0 12px 8px;
+ }
+
+ /* 父级 main 已为底部导航留 64px(导航 56px + 安全区),这里补足安全区超出的部分 */
+ .cs-dock-wrap {
+ padding: 0 8px max(8px, env(safe-area-inset-bottom, 0px));
+ }
+
+ .cs-dock {
+ padding: 10px;
+ }
+
+ /* 移动端参数 chip 一行横向滚动(方案 §4.1) */
+ .cs-dock-controls {
+ flex-wrap: nowrap;
+ overflow-x: auto;
+ scrollbar-width: none;
+ }
+
+ .cs-dock-controls > * {
+ flex-shrink: 0;
+ }
+
+ .cs-dock-params.cp-renderer {
+ flex-wrap: nowrap;
+ }
+
+ .cs-kbd {
+ display: none;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .cs-chip {
+ transition: none;
+ }
+}
+
+/* ---------- 首次引导(WP C-4,react-joyride 浮层在 portal 中) ---------- */
+.cs-guide-step {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ max-width: 280px;
+}
+
+.cs-guide-title {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ color: var(--text-primary);
+ font-size: 14px;
+ font-weight: 700;
+}
+
+.cs-guide-index {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 20px;
+ height: 20px;
+ border-radius: 999px;
+ background: color-mix(in srgb, var(--semi-color-primary) 14%, transparent);
+ color: var(--semi-color-primary);
+ font-size: 12px;
+ font-variant-numeric: tabular-nums;
+}
+
+.cs-guide-text {
+ color: var(--text-secondary);
+ font-size: 13px;
+ line-height: 1.6;
+}
+
+/* ---------- 体验中心侧边栏 / 底部导航未读角标(WP C-4) ---------- */
+.exp-unread-badge {
+ display: inline-flex;
+ flex-shrink: 0;
+ align-items: center;
+ justify-content: center;
+ min-width: 16px;
+ height: 16px;
+ padding: 0 4px;
+ border-radius: 999px;
+ background: var(--semi-color-danger);
+ color: var(--semi-color-white, var(--surface-card));
+ font-size: 10px;
+ font-weight: 700;
+ font-variant-numeric: tabular-nums;
+ line-height: 1;
+}
diff --git a/src/components/creation/params/ChipGroup.jsx b/src/components/creation/params/ChipGroup.jsx
new file mode 100644
index 00000000..52b6ce98
--- /dev/null
+++ b/src/components/creation/params/ChipGroup.jsx
@@ -0,0 +1,53 @@
+/*
+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 .
+
+For commercial licensing, please contact support@quantumnous.com
+*/
+
+import React from 'react';
+import { useTranslation } from 'react-i18next';
+import OptionGroup from './OptionGroup';
+import { optionLabel, paramLabel } from './labels';
+
+/**
+ * 胶囊单选(schema type = 'chips'),如分辨率、画质。
+ * props: { param, value, onChange(value), optionDisabledReasons?, disabledReason? }
+ */
+const ChipGroup = ({
+ param,
+ value,
+ onChange,
+ optionDisabledReasons,
+ disabledReason,
+}) => {
+ const { t } = useTranslation();
+ return (
+ (
+ {optionLabel(t, param, opt)}
+ )}
+ />
+ );
+};
+
+export default ChipGroup;
diff --git a/src/components/creation/params/DurationSegmented.jsx b/src/components/creation/params/DurationSegmented.jsx
new file mode 100644
index 00000000..176e8597
--- /dev/null
+++ b/src/components/creation/params/DurationSegmented.jsx
@@ -0,0 +1,58 @@
+/*
+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 .
+
+For commercial licensing, please contact support@quantumnous.com
+*/
+
+import React from 'react';
+import { useTranslation } from 'react-i18next';
+import OptionGroup from './OptionGroup';
+import { optionValue } from './constraints';
+import { optionLabel, paramLabel } from './labels';
+
+/**
+ * 分段选择(schema type = 'segmented'),主要用于时长,按 unit 显示"5s"。
+ * props: { param, value, onChange(value), optionDisabledReasons?, disabledReason? }
+ */
+const DurationSegmented = ({
+ param,
+ value,
+ onChange,
+ optionDisabledReasons,
+ disabledReason,
+}) => {
+ const { t } = useTranslation();
+ const unitWord = param?.unit === 's' ? t('秒') : param?.unit || '';
+ return (
+ `${optionValue(opt)} ${unitWord}`.trim()}
+ renderOption={(opt) => (
+
+ {optionLabel(t, param, opt)}
+
+ )}
+ />
+ );
+};
+
+export default DurationSegmented;
diff --git a/src/components/creation/params/ImageSlot.jsx b/src/components/creation/params/ImageSlot.jsx
new file mode 100644
index 00000000..08643aff
--- /dev/null
+++ b/src/components/creation/params/ImageSlot.jsx
@@ -0,0 +1,252 @@
+/*
+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 .
+
+For commercial licensing, please contact support@quantumnous.com
+*/
+
+import React, { useRef, useState } from 'react';
+import { Spin, Tooltip } from '@douyinfe/semi-ui';
+import { ImagePlus, RotateCcw, X } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import './creation-params.css';
+
+const pickImageFile = (files, accept) => {
+ const list = Array.from(files || []);
+ if (!accept || accept === '*') return list[0] || null;
+ const wantsImage = accept.includes('image/');
+ return (
+ list.find((f) => (wantsImage ? f.type.startsWith('image/') : true)) || null
+ );
+};
+
+/**
+ * 带标签的单张图片槽(首帧 / 尾帧 / 参考图)。纯展示:上传逻辑由父组件在 onPick 中完成,
+ * 并通过 value.status 回传状态。
+ *
+ * props:
+ * label 槽位名称(已翻译或 i18n key,均会过 t())
+ * value { previewUrl?, status: 'uploading'|'ready'|'error'|'expired'|'unused', error? } | null
+ * onPick(file) 选择 / 拖入 / 粘贴图片
+ * onRemove() 移除
+ * onRetry() 上传失败后重试
+ * disabledReason 非空时整个槽位禁用,并以 Tooltip 说明原因
+ * accept 默认 'image/*'
+ * hint 空态下的辅助说明
+ */
+const ImageSlot = ({
+ label,
+ value,
+ onPick,
+ onRemove,
+ onRetry,
+ disabledReason = '',
+ accept = 'image/*',
+ hint,
+ className = '',
+}) => {
+ const { t } = useTranslation();
+ const inputRef = useRef(null);
+ const [dragOver, setDragOver] = useState(false);
+
+ const status = value ? value.status || 'ready' : 'empty';
+ const disabled = Boolean(disabledReason);
+ const labelText = label ? t(label) : t('图片');
+ // 可以(重新)选择图片的状态
+ const canPick =
+ !disabled &&
+ (status === 'empty' || status === 'expired' || status === 'error');
+ const canDrop = !disabled && status !== 'uploading' && status !== 'unused';
+
+ const openPicker = () => {
+ if (canPick && inputRef.current) inputRef.current.click();
+ };
+
+ const handleFile = (file) => {
+ if (file && onPick) onPick(file);
+ };
+
+ const onInputChange = (e) => {
+ handleFile(pickImageFile(e.target.files, accept));
+ e.target.value = '';
+ };
+
+ const onDragOver = (e) => {
+ if (!canDrop) return;
+ e.preventDefault();
+ e.dataTransfer.dropEffect = 'copy';
+ if (!dragOver) setDragOver(true);
+ };
+
+ const onDragLeave = (e) => {
+ if (e.currentTarget.contains(e.relatedTarget)) return;
+ setDragOver(false);
+ };
+
+ const onDrop = (e) => {
+ setDragOver(false);
+ if (!canDrop) return;
+ e.preventDefault();
+ handleFile(pickImageFile(e.dataTransfer.files, accept));
+ };
+
+ const onPaste = (e) => {
+ if (!canDrop) return;
+ const file = pickImageFile(
+ e.clipboardData && e.clipboardData.files,
+ accept,
+ );
+ if (file) {
+ e.preventDefault();
+ handleFile(file);
+ }
+ };
+
+ const onKeyDown = (e) => {
+ if (e.target !== e.currentTarget) return;
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ openPicker();
+ }
+ };
+
+ const statusText = {
+ empty: t('点击、拖入或粘贴图片'),
+ uploading: t('上传中'),
+ ready: '',
+ error: (value && value.error) || t('上传失败'),
+ expired: t('原图已失效'),
+ unused: t('当前模型不使用'),
+ }[status];
+
+ const preview =
+ value && value.previewUrl && status !== 'expired' ? (
+
+ ) : null;
+
+ const ariaLabel = [
+ labelText,
+ disabled ? disabledReason : statusText,
+ canPick ? t('按回车选择图片') : '',
+ ]
+ .filter(Boolean)
+ .join(',');
+
+ const slot = (
+
+
+
+ {preview}
+
+ {status === 'empty' || status === 'expired' ? (
+
+
+ {statusText}
+ {status === 'empty' && hint ? (
+ {t(hint)}
+ ) : null}
+ {status === 'expired' ? (
+ {t('请重新上传')}
+ ) : null}
+
+ ) : null}
+
+ {status === 'uploading' ? (
+
+
+ {statusText}
+
+ ) : null}
+
+ {status === 'error' ? (
+
+ {statusText}
+ {onRetry ? (
+ {
+ e.stopPropagation();
+ onRetry();
+ }}
+ >
+
+ {t('重试')}
+
+ ) : null}
+
+ ) : null}
+
+ {status === 'unused' ? (
+
{statusText}
+ ) : null}
+
+ {status !== 'empty' && onRemove && !disabled ? (
+
{
+ e.stopPropagation();
+ onRemove();
+ }}
+ >
+
+
+ ) : null}
+
+
{labelText}
+
+ );
+
+ return disabled ? (
+
+ {slot}
+
+ ) : (
+ slot
+ );
+};
+
+export default ImageSlot;
diff --git a/src/components/creation/params/OptionGroup.jsx b/src/components/creation/params/OptionGroup.jsx
new file mode 100644
index 00000000..dacd4b78
--- /dev/null
+++ b/src/components/creation/params/OptionGroup.jsx
@@ -0,0 +1,155 @@
+/*
+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 .
+
+For commercial licensing, please contact support@quantumnous.com
+*/
+
+import React, { useRef } from 'react';
+import { Tooltip } from '@douyinfe/semi-ui';
+import { optionKey, optionValue } from './constraints';
+import './creation-params.css';
+
+/**
+ * 通用单选按钮组(radiogroup 语义 + roving tabindex),供 RatioPicker /
+ * ChipGroup / DurationSegmented 复用。
+ *
+ * - 方向键在可用选项间移动并选中,Home / End 跳到首尾;
+ * - 被禁用的选项用 aria-disabled(而非 disabled),以便悬停 / 聚焦时仍能看到原因 Tooltip;
+ * - 整组禁用(disabledReason)时所有选项不可选,原因挂在组外层 Tooltip 上。
+ */
+const OptionGroup = ({
+ options = [],
+ value,
+ onChange,
+ ariaLabel,
+ optionDisabledReasons = {},
+ disabledReason = '',
+ renderOption,
+ getOptionAriaLabel,
+ variant = 'chips',
+ className = '',
+}) => {
+ const refs = useRef([]);
+ const groupDisabled = Boolean(disabledReason);
+ const selectedKey =
+ value === undefined || value === null ? null : optionKey(value);
+
+ const isDisabled = (opt) =>
+ groupDisabled || Boolean(optionDisabledReasons[optionKey(opt)]);
+
+ const selectedIndex = options.findIndex((o) => optionKey(o) === selectedKey);
+ const firstEnabled = options.findIndex((o) => !isDisabled(o));
+ const tabStop =
+ selectedIndex >= 0 ? selectedIndex : firstEnabled >= 0 ? firstEnabled : 0;
+
+ const select = (opt) => {
+ if (isDisabled(opt)) return;
+ if (optionKey(opt) === selectedKey) return;
+ onChange && onChange(optionValue(opt));
+ };
+
+ const moveTo = (from, step) => {
+ const n = options.length;
+ for (let i = 1; i <= n; i += 1) {
+ const idx = (from + step * i + n * n) % n;
+ if (!isDisabled(options[idx])) {
+ refs.current[idx] && refs.current[idx].focus();
+ select(options[idx]);
+ return;
+ }
+ }
+ };
+
+ const onKeyDown = (e, idx) => {
+ switch (e.key) {
+ case 'ArrowRight':
+ case 'ArrowDown':
+ e.preventDefault();
+ moveTo(idx, 1);
+ break;
+ case 'ArrowLeft':
+ case 'ArrowUp':
+ e.preventDefault();
+ moveTo(idx, -1);
+ break;
+ case 'Home':
+ e.preventDefault();
+ moveTo(-1, 1);
+ break;
+ case 'End':
+ e.preventDefault();
+ moveTo(options.length, -1);
+ break;
+ default:
+ }
+ };
+
+ const group = (
+
+ {options.map((opt, idx) => {
+ const key = optionKey(opt);
+ const selected = key === selectedKey;
+ const reason = groupDisabled ? '' : optionDisabledReasons[key] || '';
+ const disabled = isDisabled(opt);
+ const btn = (
+ {
+ refs.current[idx] = el;
+ }}
+ type='button'
+ role='radio'
+ aria-checked={selected}
+ aria-disabled={disabled || undefined}
+ aria-label={
+ getOptionAriaLabel ? getOptionAriaLabel(opt) : undefined
+ }
+ tabIndex={idx === tabStop ? 0 : -1}
+ className={`cp-option${selected ? ' is-selected' : ''}${
+ disabled ? ' is-disabled' : ''
+ }`}
+ onClick={() => select(opt)}
+ onKeyDown={(e) => onKeyDown(e, idx)}
+ >
+ {renderOption ? renderOption(opt, { selected, disabled }) : key}
+
+ );
+ return reason ? (
+
+ {btn}
+
+ ) : (
+ btn
+ );
+ })}
+
+ );
+
+ return groupDisabled ? (
+
+ {group}
+
+ ) : (
+ group
+ );
+};
+
+export default OptionGroup;
diff --git a/src/components/creation/params/ParamRenderer.jsx b/src/components/creation/params/ParamRenderer.jsx
new file mode 100644
index 00000000..cbe484b2
--- /dev/null
+++ b/src/components/creation/params/ParamRenderer.jsx
@@ -0,0 +1,152 @@
+/*
+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 .
+
+For commercial licensing, please contact support@quantumnous.com
+*/
+
+import React, { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+import RatioPicker from './RatioPicker';
+import ChipGroup from './ChipGroup';
+import DurationSegmented from './DurationSegmented';
+import ParamSwitch from './ParamSwitch';
+import ParamSelect from './ParamSelect';
+import ParamTextArea from './ParamTextArea';
+import ParamSlider from './ParamSlider';
+import SeedInput from './SeedInput';
+import { applyConstraints, optionKey } from './constraints';
+import { formatConstraintReason, paramLabel } from './labels';
+import './creation-params.css';
+
+/** schema type → 控件。未知 type 不渲染(前向兼容后端新增类型)。 */
+export const PARAM_CONTROLS = {
+ ratio: RatioPicker,
+ chips: ChipGroup,
+ segmented: DurationSegmented,
+ switch: ParamSwitch,
+ select: ParamSelect,
+ textarea: ParamTextArea,
+ slider: ParamSlider,
+ seed: SeedInput,
+};
+
+const INLINE_TYPES = new Set(['switch']);
+
+/**
+ * schema 驱动的参数渲染器(纯展示,不发请求)。
+ *
+ * props:
+ * params schema.params[]
+ * values { [key]: value }
+ * onChange(key, value)
+ * placement 'dock' | 'advanced':只渲染 placement 匹配的参数(hidden 永不渲染;
+ * 缺省 placement 视为 'dock')
+ * constraints schema.constraints[],命中时禁用选项并在控件下说明原因
+ * disabledReasons { [key]: string } 整个参数禁用的原因(如"当前模式不支持")
+ * showLabels 默认 true
+ * className
+ */
+const ParamRenderer = ({
+ params = [],
+ values = {},
+ onChange,
+ placement = 'dock',
+ constraints = [],
+ disabledReasons = {},
+ showLabels = true,
+ className = '',
+}) => {
+ const { t } = useTranslation();
+
+ const visible = useMemo(
+ () =>
+ (params || []).filter(
+ (p) =>
+ p &&
+ p.key &&
+ PARAM_CONTROLS[p.type] &&
+ (p.placement || 'dock') !== 'hidden' &&
+ (p.placement || 'dock') === placement,
+ ),
+ [params, placement],
+ );
+
+ const { disabledOptions, reasons } = useMemo(
+ () => applyConstraints(values, constraints, params),
+ [values, constraints, params],
+ );
+
+ if (visible.length === 0) return null;
+
+ return (
+
+ {visible.map((param) => {
+ const Control = PARAM_CONTROLS[param.type];
+ const dis = disabledOptions[param.key] || {};
+ const optionDisabledReasons = {};
+ Object.keys(dis).forEach((k) => {
+ optionDisabledReasons[k] = formatConstraintReason(
+ t,
+ dis[k],
+ param,
+ params,
+ );
+ });
+ const wholeReason = disabledReasons[param.key]
+ ? t(disabledReasons[param.key])
+ : '';
+ const paramReasons = reasons[param.key] || [];
+ const currentInvalid = Boolean(dis[optionKey(values[param.key])]);
+ // 有选项被约束禁用、当前值不合法或无选项参数被约束时,在控件下方给出说明
+ const hint =
+ !wholeReason &&
+ paramReasons.length > 0 &&
+ (Object.keys(dis).length > 0 || currentInvalid || !param.options)
+ ? formatConstraintReason(t, paramReasons[0], param, params)
+ : '';
+ const label = paramLabel(t, param);
+ const inline = INLINE_TYPES.has(param.type);
+ return (
+
+ {showLabels ?
{label}
: null}
+
+ onChange && onChange(param.key, v)}
+ optionDisabledReasons={optionDisabledReasons}
+ disabledReason={wholeReason}
+ />
+
+ {hint ? (
+
+ {hint}
+
+ ) : null}
+
+ );
+ })}
+
+ );
+};
+
+export default ParamRenderer;
diff --git a/src/components/creation/params/ParamSelect.jsx b/src/components/creation/params/ParamSelect.jsx
new file mode 100644
index 00000000..c498cd4e
--- /dev/null
+++ b/src/components/creation/params/ParamSelect.jsx
@@ -0,0 +1,107 @@
+/*
+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 .
+
+For commercial licensing, please contact support@quantumnous.com
+*/
+
+import React, { useMemo } from 'react';
+import { Select, Tooltip } from '@douyinfe/semi-ui';
+import { useTranslation } from 'react-i18next';
+import { optionKey, optionValue } from './constraints';
+import { optionLabel, paramLabel } from './labels';
+import './creation-params.css';
+
+/**
+ * 下拉选择(schema type = 'select'),也用于运镜预设:
+ * options 可为原始值,或 { value, label, description } 对象(description 作为说明文字显示)。
+ * 被约束禁用的选项置灰,并以说明行展示原因(下拉内不依赖 Tooltip,键盘用户同样可见)。
+ *
+ * props: { param, value, onChange(value), optionDisabledReasons?, disabledReason? }
+ */
+const ParamSelect = ({
+ param,
+ value,
+ onChange,
+ optionDisabledReasons = {},
+ disabledReason,
+}) => {
+ const { t } = useTranslation();
+ const options = useMemo(() => param?.options || [], [param]);
+
+ const optionList = useMemo(
+ () =>
+ options.map((opt) => {
+ const reason = optionDisabledReasons[optionKey(opt)] || '';
+ const desc =
+ opt && typeof opt === 'object' && opt.description
+ ? t(opt.description)
+ : '';
+ const text = optionLabel(t, param, opt);
+ return {
+ value: optionValue(opt),
+ disabled: Boolean(reason),
+ showTick: true,
+ label: (
+
+ {text}
+ {reason || desc ? (
+ {reason || desc}
+ ) : null}
+
+ ),
+ };
+ }),
+ [options, optionDisabledReasons, param, t],
+ );
+
+ // 选项可能是数字,取值可能是字符串:映射到选项的规范值,保证 Select 能命中
+ const hit = options.find((o) => optionKey(o) === optionKey(value));
+ const current = hit !== undefined ? optionValue(hit) : undefined;
+
+ const sel = (
+ onChange && onChange(v)}
+ aria-label={paramLabel(t, param)}
+ placeholder={t('请选择')}
+ dropdownClassName='cp-select-dropdown'
+ renderSelectedItem={(item) =>
+ item && item.value !== undefined
+ ? optionLabel(
+ t,
+ param,
+ options.find((o) => optionKey(o) === optionKey(item.value)) ??
+ item.value,
+ )
+ : ''
+ }
+ />
+ );
+
+ return disabledReason ? (
+
+ {sel}
+
+ ) : (
+ sel
+ );
+};
+
+export default ParamSelect;
diff --git a/src/components/creation/params/ParamSlider.jsx b/src/components/creation/params/ParamSlider.jsx
new file mode 100644
index 00000000..417430fd
--- /dev/null
+++ b/src/components/creation/params/ParamSlider.jsx
@@ -0,0 +1,61 @@
+/*
+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 .
+
+For commercial licensing, please contact support@quantumnous.com
+*/
+
+import React from 'react';
+import { Slider, Tooltip } from '@douyinfe/semi-ui';
+import { useTranslation } from 'react-i18next';
+import { paramLabel } from './labels';
+import './creation-params.css';
+
+/**
+ * 滑块(schema type = 'slider'):param.min / max / step / unit。
+ * props: { param, value, onChange(number), disabledReason? }
+ */
+const ParamSlider = ({ param, value, onChange, disabledReason }) => {
+ const { t } = useTranslation();
+ const min = typeof param?.min === 'number' ? param.min : 0;
+ const max = typeof param?.max === 'number' ? param.max : 100;
+ const step = typeof param?.step === 'number' ? param.step : 1;
+ const v = typeof value === 'number' ? value : (param?.default ?? min);
+ const unit = param?.unit || '';
+ const body = (
+
+ onChange && onChange(n)}
+ tipFormatter={(n) => `${n}${unit}`}
+ aria-label={paramLabel(t, param)}
+ />
+ {`${v}${unit}`}
+
+ );
+ return disabledReason ? (
+
+ {body}
+
+ ) : (
+ body
+ );
+};
+
+export default ParamSlider;
diff --git a/src/components/creation/params/ParamSwitch.jsx b/src/components/creation/params/ParamSwitch.jsx
new file mode 100644
index 00000000..8ac5153f
--- /dev/null
+++ b/src/components/creation/params/ParamSwitch.jsx
@@ -0,0 +1,51 @@
+/*
+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 .
+
+For commercial licensing, please contact support@quantumnous.com
+*/
+
+import React from 'react';
+import { Switch, Tooltip } from '@douyinfe/semi-ui';
+import { useTranslation } from 'react-i18next';
+import { paramLabel } from './labels';
+import './creation-params.css';
+
+/**
+ * 开关(schema type = 'switch'),如生成音频、水印、智能扩写。
+ * props: { param, value, onChange(boolean), disabledReason? }
+ */
+const ParamSwitch = ({ param, value, onChange, disabledReason }) => {
+ const { t } = useTranslation();
+ const sw = (
+ onChange && onChange(checked)}
+ aria-label={paramLabel(t, param)}
+ className='cp-switch'
+ />
+ );
+ return disabledReason ? (
+
+ {sw}
+
+ ) : (
+ sw
+ );
+};
+
+export default ParamSwitch;
diff --git a/src/components/creation/params/ParamTextArea.jsx b/src/components/creation/params/ParamTextArea.jsx
new file mode 100644
index 00000000..64dbaef4
--- /dev/null
+++ b/src/components/creation/params/ParamTextArea.jsx
@@ -0,0 +1,56 @@
+/*
+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 .
+
+For commercial licensing, please contact support@quantumnous.com
+*/
+
+import React from 'react';
+import { TextArea, Tooltip } from '@douyinfe/semi-ui';
+import { useTranslation } from 'react-i18next';
+import { paramLabel } from './labels';
+import './creation-params.css';
+
+/**
+ * 多行文本(schema type = 'textarea'),如反向提示词。
+ * props: { param, value, onChange(string), disabledReason? };param.max_length 限制字数。
+ */
+const ParamTextArea = ({ param, value, onChange, disabledReason }) => {
+ const { t } = useTranslation();
+ const max =
+ Number(param?.max_length) > 0 ? Number(param.max_length) : undefined;
+ const area = (
+