merge: 合入总仓库 weiyuan(bfdfb339) web/ 新功能,保留 ui-optimization 的 UI 重构

来源:luoguang/monkey-ai weiyuan@bfdfb339 的 web/(经 sync/main-weiyuan-web-bfdfb339 同步)
同步基准:总仓库 a2ca13cb = 本仓库初始导入 d8f3aee2

冲突处理原则:保留 ui-optimization 的 UI(样式/结构/组件),嫁接 weiyuan 的功能逻辑。
- i18n:按键三方合并;ours 的「令牌→密钥」改名键上移植 theirs 的术语修订
- task-logs / OrgLogs:ours 已手工移植同一功能(6ad95e2),保留 ours
- 删除:OrgCreate(theirs 下线 /org/create)、旧 image 组件与 VideoRegenerateModal(theirs 体验中心重写)、
  OrgAvatarSection / PricingBentoPage / CommissionConsole(ours 重构中已移除)
- 测试:users-pagination 的 i18next mock 补 t();theirs 新增文件补 license header
This commit is contained in:
qiubaishen
2026-11-10 12:01:21 +08:00
266 changed files with 38432 additions and 7570 deletions
+11 -8
View File
@@ -19,6 +19,10 @@ For commercial licensing, please contact support@quantumnous.com
import React, { lazy, Suspense, useContext, useMemo } from 'react'; import React, { lazy, Suspense, useContext, useMemo } from 'react';
import { Route, Routes, Navigate, useLocation } from 'react-router-dom'; import { Route, Routes, Navigate, useLocation } from 'react-router-dom';
import {
isMiniProgramPaymentPath,
isMiniProgramWebView,
} from './helpers/miniProgram';
import Loading from './components/common/ui/Loading'; import Loading from './components/common/ui/Loading';
import { AuthRedirect, PrivateRoute, AdminRoute } from './helpers'; import { AuthRedirect, PrivateRoute, AdminRoute } from './helpers';
import NotFound from './pages/NotFound'; import NotFound from './pages/NotFound';
@@ -91,7 +95,6 @@ const PersonalSetting = lazy(
const Setup = lazy(() => import('./pages/Setup')); const Setup = lazy(() => import('./pages/Setup'));
const Analytics = lazy(() => import('./pages/Analytics')); const Analytics = lazy(() => import('./pages/Analytics'));
const Organization = lazy(() => import('./pages/Organization')); const Organization = lazy(() => import('./pages/Organization'));
const OrgCreate = lazy(() => import('./pages/Organization/OrgCreate'));
const AdminOrganizations = lazy(() => import('./pages/AdminOrganizations')); const AdminOrganizations = lazy(() => import('./pages/AdminOrganizations'));
const AdminOrder = lazy(() => import('./pages/AdminOrder')); const AdminOrder = lazy(() => import('./pages/AdminOrder'));
const AdminInvoice = lazy(() => import('./pages/AdminInvoice')); const AdminInvoice = lazy(() => import('./pages/AdminInvoice'));
@@ -226,6 +229,11 @@ function App() {
); );
} }
// WeyAi 小程序的 web-view 里不出现付费页面(见 helpers/miniProgram.js),直接回到个人中心。
if (isMiniProgramWebView() && isMiniProgramPaymentPath(location.pathname)) {
return <Navigate to='/user-center' replace />;
}
return ( return (
<SetupCheck> <SetupCheck>
<Routes> <Routes>
@@ -843,13 +851,8 @@ function App() {
path='/org/create' path='/org/create'
element={ element={
<PrivateRoute> <PrivateRoute>
{isOrgCenterAvailable ? ( {/* 已下线的自助加入企业页:旧链接/书签统一交给企业中心入口解析 */}
<Suspense fallback={<Loading />}> <Navigate to='/org' replace />
<OrgCreate />
</Suspense>
) : (
<Navigate to='/user-center/dashboard' replace />
)}
</PrivateRoute> </PrivateRoute>
} }
/> />
@@ -149,7 +149,7 @@ const ChannelConsumption = ({ data, title, icon, t, embedded = false }) => {
pageSize, pageSize,
showSizeChanger: true, showSizeChanger: true,
pageSizeOpts: [10, 20, 30], pageSizeOpts: [10, 20, 30],
showTotal: (total) => `${t('共')} ${total} ${t('条')}`, showTotal: (total) => t('共 {{total}} 条', { total, count: total }),
onPageChange: (page) => setCurrentPage(page), onPageChange: (page) => setCurrentPage(page),
onPageSizeChange: (size) => { onPageSizeChange: (size) => {
setPageSize(size); setPageSize(size);
+1 -1
View File
@@ -200,7 +200,7 @@ const DailyStatsTable = ({ data, title, icon, t, embedded = false }) => {
pagination={{ pagination={{
pageSize: 10, pageSize: 10,
showSizeChanger: true, showSizeChanger: true,
showTotal: (total) => `${t('共')} ${total} ${t('条')}`, showTotal: (total) => t('共 {{total}} 条', { total, count: total }),
}} }}
scroll={{ x: 1100 }} scroll={{ x: 1100 }}
size='small' size='small'
+16 -3
View File
@@ -29,9 +29,9 @@ import {
TrendingUp, TrendingUp,
TrendingDown, TrendingDown,
} from 'lucide-react'; } from 'lucide-react';
import { renderQuota } from '../../helpers'; import { renderQuota, timestamp2string } from '../../helpers';
const OverviewCards = ({ overview, t }) => { const OverviewCards = ({ overview, loading = false, t }) => {
if (!overview) { if (!overview) {
return ( return (
<div className='grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4'> <div className='grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4'>
@@ -124,7 +124,12 @@ const OverviewCards = ({ overview, t }) => {
}; };
return ( return (
<div className='grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4'> <div>
<div
className={`grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4 transition-opacity ${
loading ? 'opacity-50' : ''
}`}
>
{cards.map((card, index) => ( {cards.map((card, index) => (
<Card <Card
key={index} key={index}
@@ -150,6 +155,14 @@ const OverviewCards = ({ overview, t }) => {
</Card> </Card>
))} ))}
</div> </div>
{/* 活跃/消耗取自汇总层时会落后一个同步周期(约 30~60 秒),把截止时间标出来,
避免「数字和日志对不上」被当成算错;data_as_of 为 0 表示本次是实时直查。 */}
{overview.data_as_of > 0 && (
<p className='mt-2 text-xs text-gray-400 dark:text-gray-500 text-right'>
{t('活跃与消耗数据截至')} {timestamp2string(overview.data_as_of)}
</p>
)}
</div>
); );
}; };
@@ -45,7 +45,8 @@ const TopupChannelChart = ({ data, title, icon, t }) => {
if (!data || data.length === 0) return null; if (!data || data.length === 0) return null;
const chartData = data.map((item) => ({ 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, value: item.amount || 0,
count: item.count || 0, count: item.count || 0,
})); }));
@@ -53,7 +54,7 @@ const TopupChannelChart = ({ data, title, icon, t }) => {
// 根据支付渠道名称生成颜色数组 // 根据支付渠道名称生成颜色数组
const colorList = chartData.map((item, index) => { const colorList = chartData.map((item, index) => {
return ( return (
CHANNEL_COLORS[item.name] || CHANNEL_COLORS[item.rawName] ||
DEFAULT_COLORS[index % DEFAULT_COLORS.length] DEFAULT_COLORS[index % DEFAULT_COLORS.length]
); );
}); });
@@ -80,7 +81,7 @@ const TopupChannelChart = ({ data, title, icon, t }) => {
}, },
{ {
key: () => 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' className='flex items-center justify-between text-sm py-1 border-b border-gray-100 dark:border-gray-700 last:border-0'
> >
<span className='text-gray-600 dark:text-gray-400'> <span className='text-gray-600 dark:text-gray-400'>
{item.payment_method} {item.payment_method ? t(item.payment_method) : t('未知')}
</span> </span>
<div className='text-right'> <div className='text-right'>
<span className='font-medium'> <span className='font-medium'>
+2 -2
View File
@@ -65,7 +65,7 @@ const TrendCharts = ({ title, icon, data, type, t }) => {
{ {
key: (datum) => datum?.type, key: (datum) => datum?.type,
value: (datum) => 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, key: (datum) => datum?.type,
value: (datum) => value: (datum) =>
`${(datum?.value || 0).toLocaleString()} ${t('人')}`, t('{{n}} 人', { n: (datum?.value || 0).toLocaleString(), count: datum?.value || 0 }),
}, },
], ],
}, },
+27 -12
View File
@@ -99,7 +99,7 @@ const UserSurveyStats = ({ title, icon, t }) => {
return null; return null;
const chartData = surveyStats.job_type_stats.map((item) => ({ 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, value: item.count,
percentage: item.percentage, percentage: item.percentage,
})); }));
@@ -122,7 +122,11 @@ const UserSurveyStats = ({ title, icon, t }) => {
content: [ content: [
{ {
key: (datum) => datum?.name, key: (datum) => datum?.name,
value: (datum) => `${datum?.value || 0} ${t('人')}`, value: (datum) =>
t('{{n}} 人', {
n: datum?.value || 0,
count: datum?.value || 0,
}),
}, },
{ {
key: () => t('占比'), key: () => t('占比'),
@@ -151,7 +155,7 @@ const UserSurveyStats = ({ title, icon, t }) => {
return null; return null;
const chartData = surveyStats.ai_tool_stats.map((item) => ({ 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, value: item.count,
percentage: item.percentage, percentage: item.percentage,
})); }));
@@ -174,7 +178,11 @@ const UserSurveyStats = ({ title, icon, t }) => {
content: [ content: [
{ {
key: (datum) => datum?.name, key: (datum) => datum?.name,
value: (datum) => `${datum?.value || 0} ${t('人')}`, value: (datum) =>
t('{{n}} 人', {
n: datum?.value || 0,
count: datum?.value || 0,
}),
}, },
{ {
key: () => t('占比'), key: () => t('占比'),
@@ -236,7 +244,11 @@ const UserSurveyStats = ({ title, icon, t }) => {
}, },
{ {
key: () => 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 > 0 && (
<Tag color='purple' size='small'> <Tag color='purple' size='small'>
{totalUsers} {t('人已填写')} {t('{{n}} 人已填写', { n: totalUsers, count: totalUsers })}
</Tag> </Tag>
)} )}
</> </>
@@ -394,7 +406,7 @@ const UserSurveyStats = ({ title, icon, t }) => {
{config?.icon} {config?.icon}
</span> </span>
<span className='text-sm text-gray-600 dark:text-gray-400'> <span className='text-sm text-gray-600 dark:text-gray-400'>
{config?.label} {t(config?.label || '')}
</span> </span>
</div> </div>
<div className='flex items-center gap-2'> <div className='flex items-center gap-2'>
@@ -461,7 +473,7 @@ const UserSurveyStats = ({ title, icon, t }) => {
{config?.icon} {config?.icon}
</span> </span>
<span className='text-sm text-gray-600 dark:text-gray-400'> <span className='text-sm text-gray-600 dark:text-gray-400'>
{config?.label} {t(config?.label || '')}
</span> </span>
</div> </div>
<div className='flex items-center gap-2'> <div className='flex items-center gap-2'>
@@ -549,7 +561,10 @@ const UserSurveyStats = ({ title, icon, t }) => {
{JOB_TYPE_CONFIG[item.job_type]?.icon} {JOB_TYPE_CONFIG[item.job_type]?.icon}
</span> </span>
<span className='text-gray-700 dark:text-gray-300'> <span className='text-gray-700 dark:text-gray-300'>
{JOB_TYPE_CONFIG[item.job_type]?.label} {t(
JOB_TYPE_CONFIG[item.job_type]
?.label || '',
)}
</span> </span>
</div> </div>
</td> </td>
@@ -561,10 +576,10 @@ const UserSurveyStats = ({ title, icon, t }) => {
} }
size='small' size='small'
> >
{ {t(
AI_TOOL_CONFIG[item.ai_tool_usage] AI_TOOL_CONFIG[item.ai_tool_usage]
?.label ?.label || '',
} )}
</Tag> </Tag>
</td> </td>
<td className='py-2 px-3 text-right font-medium'> <td className='py-2 px-3 text-right font-medium'>
@@ -158,7 +158,7 @@ const columnsFor = (tab, cny, t, atRisk) => {
: 'var(--ui-color-warning)', : 'var(--ui-color-warning)',
}} }}
> >
{v < 1 ? t('不足 1 天') : `${v.toFixed(1)} ${t('天')}`} {v < 1 ? t('不足 1 天') : t('{{days}} 天', { days: v.toFixed(1) })}
</span> </span>
); );
}, },
@@ -195,7 +195,7 @@ export const KpiGrid = ({ report, lists, cny, onJump, t }) => {
}, },
{ {
title: 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}`, sub: `${t('活跃率')} ${pct(k.active_orgs, servingOrgs).toFixed(1)}% · ${t('新增')} ${k.new_orgs || 0}`,
compare: ( compare: (
<ChangeText cur={k.active_orgs} prev={k.prev_active_orgs} t={t} /> <ChangeText cur={k.active_orgs} prev={k.prev_active_orgs} t={t} />
@@ -212,7 +212,7 @@ export const KpiGrid = ({ report, lists, cny, onJump, t }) => {
}, },
{ {
title: 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()}`, sub: `${t('渗透率')} ${Math.min(100, pct(k.active_members, k.total_members)).toFixed(1)}% · ${t('成员')} ${(k.total_members || 0).toLocaleString()}`,
tip: t('本期通过企业密钥产生调用的去重成员数(按自然日统计)'), tip: t('本期通过企业密钥产生调用的去重成员数(按自然日统计)'),
onClick: () => onJump('growth'), onClick: () => onJump('growth'),
@@ -238,7 +238,7 @@ export const KpiGrid = ({ report, lists, cny, onJump, t }) => {
{ {
title: t('未来 30 天充值缺口'), title: t('未来 30 天充值缺口'),
value: formatCny(k.topup_gap_30d, cny), 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 天所需金额,减去当前余额后累加'), tip: t('按各企业近 7 日日均消耗覆盖 30 天所需金额,减去当前余额后累加'),
accent: accent:
k.topup_gap_30d > 0 k.topup_gap_30d > 0
@@ -308,7 +308,7 @@ export const OrgDetailTable = ({ report, filter, setFilter, cny, t }) => {
<Text type='tertiary'>—</Text> <Text type='tertiary'>—</Text>
) : ( ) : (
<span className='tabular-nums'> <span className='tabular-nums'>
{v < 1 ? t('不足 1 天') : `${v.toFixed(0)} ${t('天')}`} {v < 1 ? t('不足 1 天') : t('{{days}} 天', { days: v.toFixed(0) })}
</span> </span>
), ),
sorter: (a, b) => sorter: (a, b) =>
+10 -1
View File
@@ -23,6 +23,7 @@ import React, {
useRef, useRef,
useState, useState,
useCallback, useCallback,
useMemo,
lazy, lazy,
Suspense, Suspense,
} from 'react'; } from 'react';
@@ -70,6 +71,10 @@ import GlassCard from './GlassCard';
import AuthCardHeader from './AuthCardHeader'; import AuthCardHeader from './AuthCardHeader';
import AuthLoginTabs from './AuthLoginTabs'; import AuthLoginTabs from './AuthLoginTabs';
import AgreementModal from '../common/DocumentRenderer/AgreementModal'; import AgreementModal from '../common/DocumentRenderer/AgreementModal';
import {
isMiniProgramWebView,
withMiniProgramLogins,
} from '../../helpers/miniProgram';
// 懒加载 Telegram 登录组件(345KB),只在需要时加载 // 懒加载 Telegram 登录组件(345KB),只在需要时加载
const TelegramLogin = lazy(() => import('./TelegramLogin')); const TelegramLogin = lazy(() => import('./TelegramLogin'));
@@ -177,7 +182,11 @@ const LoginForm = () => {
// 使用 StatusContext 获取最新状态,而不是从 localStorage 读取 // 使用 StatusContext 获取最新状态,而不是从 localStorage 读取
const [statusState] = useContext(StatusContext); 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 statusLoaded = statusState?.status !== undefined;
// affCode 只需在挂载时提取一次,避免每次渲染都执行 // affCode 只需在挂载时提取一次,避免每次渲染都执行
+16 -7
View File
@@ -23,6 +23,7 @@ import React, {
useRef, useRef,
useState, useState,
useCallback, useCallback,
useMemo,
lazy, lazy,
Suspense, Suspense,
} from 'react'; } from 'react';
@@ -65,6 +66,10 @@ import AuthCardHeader from './AuthCardHeader';
import AuthLoginTabs from './AuthLoginTabs'; import AuthLoginTabs from './AuthLoginTabs';
import { ArrowRight, Shield, Smartphone, QrCode } from 'lucide-react'; import { ArrowRight, Shield, Smartphone, QrCode } from 'lucide-react';
import AgreementModal from '../common/DocumentRenderer/AgreementModal'; import AgreementModal from '../common/DocumentRenderer/AgreementModal';
import {
isMiniProgramWebView,
withMiniProgramLogins,
} from '../../helpers/miniProgram';
// 懒加载 Telegram 登录组件(345KB),只在需要时加载 // 懒加载 Telegram 登录组件(345KB),只在需要时加载
const TelegramLogin = lazy(() => import('./TelegramLogin')); const TelegramLogin = lazy(() => import('./TelegramLogin'));
@@ -148,7 +153,11 @@ const RegisterForm = () => {
// 使用 StatusContext 获取最新状态,而不是从 localStorage 读取 // 使用 StatusContext 获取最新状态,而不是从 localStorage 读取
const [statusState] = useContext(StatusContext); 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 statusLoaded = statusState?.status !== undefined;
const [showEmailVerification, setShowEmailVerification] = useState(() => { const [showEmailVerification, setShowEmailVerification] = useState(() => {
@@ -235,7 +244,7 @@ const RegisterForm = () => {
const onSubmitWeChatVerificationCode = async () => { const onSubmitWeChatVerificationCode = async () => {
if (turnstileEnabled && turnstileToken === '') { if (turnstileEnabled && turnstileToken === '') {
showInfo('请稍后几秒重试,Turnstile 正在检查用户环境!'); showInfo(t('请稍后几秒重试,Turnstile 正在检查用户环境!'));
return; return;
} }
setWechatCodeSubmitLoading(true); setWechatCodeSubmitLoading(true);
@@ -253,7 +262,7 @@ const RegisterForm = () => {
showError(message); showError(message);
} }
} catch (error) { } catch (error) {
showError('登录失败,请重试'); showError(t('登录失败,请重试'));
} finally { } finally {
setWechatCodeSubmitLoading(false); setWechatCodeSubmitLoading(false);
} }
@@ -281,7 +290,7 @@ const RegisterForm = () => {
} }
if (username && password) { if (username && password) {
if (turnstileEnabled && turnstileToken === '') { if (turnstileEnabled && turnstileToken === '') {
showInfo('请稍后几秒重试,Turnstile 正在检查用户环境!'); showInfo(t('请稍后几秒重试,Turnstile 正在检查用户环境!'));
return; return;
} }
setRegisterLoading(true); setRegisterLoading(true);
@@ -316,7 +325,7 @@ const RegisterForm = () => {
const sendVerificationCode = async () => { const sendVerificationCode = async () => {
if (inputs.email === '') return; if (inputs.email === '') return;
if (turnstileEnabled && turnstileToken === '') { if (turnstileEnabled && turnstileToken === '') {
showInfo('请稍后几秒重试,Turnstile 正在检查用户环境!'); showInfo(t('请稍后几秒重试,Turnstile 正在检查用户环境!'));
return; return;
} }
setVerificationCodeLoading(true); setVerificationCodeLoading(true);
@@ -445,7 +454,7 @@ const RegisterForm = () => {
showError(message); showError(message);
} }
} catch (error) { } catch (error) {
showError('登录失败,请重试'); showError(t('登录失败,请重试'));
} }
}; };
@@ -529,7 +538,7 @@ const RegisterForm = () => {
loading={githubLoading} loading={githubLoading}
disabled={githubButtonDisabled} disabled={githubButtonDisabled}
> >
{githubButtonText} {t(githubButtonText)}
</OAuthButton> </OAuthButton>
)} )}
@@ -345,7 +345,12 @@ const DocumentRenderer = ({
const seen = new Map(); const seen = new Map();
const headings = root.querySelectorAll('h2, h3'); const headings = root.querySelectorAll('h2, h3');
headings.forEach((h) => { 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); let base = h.id || slugify(h.textContent);
if (!base) return; if (!base) return;
let id = base; let id = base;
@@ -357,7 +362,7 @@ const DocumentRenderer = ({
const a = document.createElement('a'); const a = document.createElement('a');
a.href = `#${id}`; a.href = `#${id}`;
a.className = 'doc-anchor'; a.className = 'doc-anchor';
a.setAttribute('aria-label', '复制段落链接'); a.setAttribute('aria-label', t('复制段落链接'));
a.textContent = '#'; a.textContent = '#';
a.addEventListener('click', (e) => { a.addEventListener('click', (e) => {
e.preventDefault(); e.preventDefault();
@@ -429,7 +434,7 @@ const DocumentRenderer = ({
{t('内容正在准备中')} {t('内容正在准备中')}
</h3> </h3>
<p className='text-sm text-gray-500 dark:text-gray-400'> <p className='text-sm text-gray-500 dark:text-gray-400'>
{t('管理员尚未设置') + title + t('内容')} {t('管理员尚未设置{{title}}内容', { title })}
</p> </p>
</div> </div>
); );
@@ -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' 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'
> >
<BookOpen size={16} /> <BookOpen size={16} />
{t('访问') + title} {t('访问{{title}}', { title })}
<ExternalLink <ExternalLink
size={14} size={14}
className='transition-transform group-hover:translate-x-0.5' className='transition-transform group-hover:translate-x-0.5'
+3 -1
View File
@@ -144,7 +144,9 @@ const ModelSelector = ({
title={t('暂无可用模型')} title={t('暂无可用模型')}
description={ description={
category category
? `${MODEL_CATEGORY_NAMES[category]}类模型暂无可用` ? t('{{category}}类模型暂无可用', {
category: MODEL_CATEGORY_NAMES[category],
})
: t('请先添加模型') : t('请先添加模型')
} }
/> />
@@ -70,6 +70,7 @@ export function Mermaid(props) {
// 等 setIsLoading(false) 触发重渲染时,React 找不到那些被 mermaid 删掉的节点, // 等 setIsLoading(false) 触发重渲染时,React 找不到那些被 mermaid 删掉的节点,
// 就抛 removeChild "NotFoundError"。改用 mermaid.render() 拿 svg 字符串后写进 svgRef, // 就抛 removeChild "NotFoundError"。改用 mermaid.render() 拿 svg 字符串后写进 svgRef,
// React 始终认为 svgRef 这个 div 是空的,便不会与 mermaid 的 DOM 改动冲突。 // React 始终认为 svgRef 这个 div 是空的,便不会与 mermaid 的 DOM 改动冲突。
const { t } = useTranslation();
const svgRef = useRef(null); const svgRef = useRef(null);
const [hasError, setHasError] = useState(false); const [hasError, setHasError] = useState(false);
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
@@ -164,7 +165,7 @@ export function Mermaid(props) {
animation: 'spin 1s linear infinite', animation: 'spin 1s linear infinite',
}} }}
/> />
加载图表中... {t('加载图表中...')}
</div> </div>
)} )}
{/* React 视角下这个 div 恒为空,SVG 由 effect 通过 innerHTML 注入,互不干涉 */} {/* React 视角下这个 div 恒为空,SVG 由 effect 通过 innerHTML 注入,互不干涉 */}
@@ -305,7 +306,7 @@ export function PreCode(props) {
color: 'var(--ui-color-text-2)', color: 'var(--ui-color-text-2)',
}} }}
> >
HTML预览: {t('HTML预览:')}
</div> </div>
<div dangerouslySetInnerHTML={{ __html: htmlCode }} /> <div dangerouslySetInnerHTML={{ __html: htmlCode }} />
</div> </div>
@@ -719,6 +720,7 @@ export function MarkdownRenderer(props) {
previousContentLength = 0, previousContentLength = 0,
...otherProps ...otherProps
} = props; } = props;
const { t } = useTranslation();
return ( return (
<div <div
@@ -753,7 +755,7 @@ export function MarkdownRenderer(props) {
animation: 'spin 1s linear infinite', animation: 'spin 1s linear infinite',
}} }}
/> />
正在渲染... {t('正在渲染...')}
</div> </div>
) : ( ) : (
<MarkdownContent <MarkdownContent
+1 -1
View File
@@ -672,7 +672,7 @@ const JSONEditor = ({
{hasJsonError && ( {hasJsonError && (
<Banner <Banner
type='danger' type='danger'
description={`JSON 格式错误: ${jsonError}`} description={t('JSON 格式错误: {{error}}', { error: jsonError })}
className='mb-3' className='mb-3'
/> />
)} )}
+2
View File
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import React, { useEffect, useMemo, useState } from 'react'; import React, { useEffect, useMemo, useState } from 'react';
import i18next from 'i18next';
// 读品牌值:localStorage → window.__WL_BRAND__(index.html 内联脚本写入)→ 空。 // 读品牌值:localStorage → window.__WL_BRAND__(index.html 内联脚本写入)→ 空。
// 不用 getSystemName/getLogo —— 它们的终极兜底是 'Weelinking' / '/logo.svg'(老品牌), // 不用 getSystemName/getLogo —— 它们的终极兜底是 'Weelinking' / '/logo.svg'(老品牌),
@@ -38,6 +39,7 @@ const readBrand = (key, windowKey) => {
// 加载文案根据浏览器语言决定,避免 i18n 还没初始化时硬编码中文。 // 加载文案根据浏览器语言决定,避免 i18n 还没初始化时硬编码中文。
const getLoadingText = () => { const getLoadingText = () => {
if (i18next.isInitialized) return i18next.t('加载中...');
const lang = ((typeof navigator !== 'undefined' && navigator.language) || 'zh').toLowerCase(); const lang = ((typeof navigator !== 'undefined' && navigator.language) || 'zh').toLowerCase();
return lang.startsWith('zh') ? '加载中...' : 'Loading...'; return lang.startsWith('zh') ? '加载中...' : 'Loading...';
}; };
+148
View File
@@ -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 <https://www.gnu.org/licenses/>.
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 (
<Modal
visible={visible}
title={t('确认对比生成')}
onCancel={onCancel}
maskClosable={!submitting}
width='min(560px, 94vw)'
footer={
<div className='cs-summary-foot'>
<Button onClick={onCancel} disabled={submitting}>
{t('取消')}
</Button>
<Button
theme='solid'
type={overThreshold ? 'warning' : 'primary'}
loading={submitting}
onClick={onConfirm}
>
{total
? t('确认生成(合计 {{amount}})', { amount: totalText })
: t('确认生成')}
</Button>
</div>
}
>
<div className='cs-summary'>
<p className='cs-summary-desc'>
{t(
'将用同一提示词分别提交 {{n}} 个模型,每个模型单独计费,失败自动退还',
{
n: entries.length,
},
)}
</p>
<ul className='cs-summary-list'>
{entries.map((entry, i) => {
const amount = amountOf(items[i]);
const params = compareParamSummary(entry.payload);
return (
<li key={entry.payload.model} className='cs-summary-row'>
<span className='cs-summary-model' title={entry.payload.model}>
{displayNameOf(entry.model)}
</span>
<span className='cs-summary-params' title={params}>
{params || '-'}
</span>
<span className='cs-summary-price'>
{amount ? (
items[i]?.approximate ? (
t('约 {{amount}}', { amount })
) : (
amount
)
) : quoteLoading ? (
<Spin size='small' />
) : (
'-'
)}
</span>
{entry.adjustments?.length ? (
<span className='cs-summary-note'>
{t('部分参数已按该模型调整')}
</span>
) : null}
</li>
);
})}
</ul>
<div className='cs-summary-total'>
<span>{t('合计')}</span>
<span className='cs-num'>{totalText}</span>
</div>
{quoteFailed ? (
<p className='cs-summary-desc'>{t('估价失败,价格以实际扣费为准')}</p>
) : null}
{overThreshold ? (
<div className='cs-summary-warn' role='alert'>
<AlertTriangle size={14} aria-hidden='true' />
<span>{t('本次合计金额较高,请确认后再生成')}</span>
</div>
) : null}
</div>
</Modal>
);
};
export default CompareSummary;
File diff suppressed because it is too large Load Diff
+178
View File
@@ -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 <https://www.gnu.org/licenses/>.
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 }) => (
<div className='cs-guide-step'>
<div className='cs-guide-title'>
<span className='cs-guide-index' aria-hidden='true'>
{index}
</span>
{title}
</div>
<div className='cs-guide-text'>{text}</div>
</div>
);
/**
* @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: (
<StepBody
index={1}
title={t('写描述')}
text={
kind === 'video'
? t('用一句话描述画面和运动,也可以先套用一个灵感模板')
: t('用一句话描述你想要的画面,也可以先套用一个灵感模板')
}
/>
),
},
{
target: TARGETS.model,
placement: 'top',
content: (
<StepBody
index={2}
title={t('选模型')}
text={t('不同模型风格、价格和速度不同,卡片上标明了单价和预计耗时')}
/>
),
},
{
target: TARGETS.generate,
placement: 'top',
content: (
<StepBody
index={3}
title={t('生成')}
text={t('按钮旁会显示预计价格,失败自动退还;结果出现在上方作品流')}
/>
),
},
],
[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 (
<Joyride
steps={steps}
run={run}
continuous
showSkipButton
showProgress
disableScrolling
disableOverlayClose={false}
callback={handleCallback}
locale={{
back: t('上一步'),
close: t('关闭'),
last: t('开始创作'),
next: t('下一步'),
skip: t('跳过'),
}}
styles={{
options: {
zIndex: 10000,
primaryColor: 'var(--semi-color-primary)',
backgroundColor: 'var(--surface-card)',
arrowColor: 'var(--surface-card)',
textColor: 'var(--text-primary)',
overlayColor: 'var(--semi-color-overlay-bg)',
},
tooltip: { borderRadius: 14, padding: 16 },
tooltipContainer: { textAlign: 'left' },
tooltipContent: { padding: 0 },
buttonNext: { borderRadius: 8, fontSize: 13 },
buttonBack: { fontSize: 13 },
buttonSkip: { fontSize: 12, color: 'var(--text-secondary)' },
spotlight: { borderRadius: 12 },
}}
/>
);
};
export default CreationGuide;
+225
View File
@@ -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 <https://www.gnu.org/licenses/>.
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 (
<div className='creation-studio' data-kind={kind}>
<header className='cs-header'>
<h1 className='cs-title'>{t(TITLES[kind])}</h1>
<div className='cs-filter-slot'>{filterBar}</div>
{quota !== undefined && quota !== null ? (
<div className='cs-balance'>
<span className='cs-balance-label'>{t('余额')}</span>
<span className='cs-num'>{renderQuota(quota)}</span>
</div>
) : null}
</header>
<section
className='cs-feed app-scrollbar'
aria-label={t('作品')}
tabIndex={-1}
>
{feed}
</section>
<div className='cs-dock-wrap'>{dock}</div>
{guide}
</div>
);
};
/**
* 新创作台外壳(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 (
<StudioLayout
kind={kind}
filterBar={
<FilterBar
kind={kind}
api={tasksApi}
selecting={selecting}
onToggleSelecting={
kind === 'image' ? () => setSelecting((v) => !v) : undefined
}
/>
}
feed={
<WorkFeed
kind={kind}
api={tasksApi}
form={form}
selecting={selecting}
onSelectingChange={setSelecting}
onUseAsVideoFirstFrame={
canUseVideo ? sendToVideoFirstFrame : undefined
}
/>
}
dock={<CreationDock form={form} compare={compare} />}
guide={
<CreationGuide
kind={kind}
ready={!form.modelsLoading && form.models.length > 0}
/>
}
/>
);
};
export default CreationStudio;
@@ -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 <https://www.gnu.org/licenses/>.
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 = (
<ModelPickerPanel
kind={kind}
models={models}
value={value}
params={params}
mode={mode}
recent={recent}
loading={loading}
error={error}
onRetry={onRetry}
onSelect={handleSelect}
onClose={close}
compact={isMobile}
compare={compare}
/>
);
const label = comparing
? t('对比 {{n}} 个模型', { n: compare.names.length })
: selected
? displayNameOf(selected)
: loading
? t('模型列表加载中')
: t('选择模型');
const trigger = (
<button
ref={triggerRef}
type='button'
className={`mp-trigger${comparing ? ' is-compare' : ''} ${className}`}
aria-haspopup='listbox'
aria-expanded={open}
aria-label={t('选择模型:{{name}}', { name: label })}
disabled={disabled}
onClick={() => setOpen((v) => !v)}
>
{selected?.level_locked ? <Lock size={13} aria-hidden /> : null}
<span className='mp-trigger-name'>{label}</span>
<ChevronDown size={14} aria-hidden className='mp-trigger-caret' />
</button>
);
if (isMobile) {
return (
<>
{trigger}
<SideSheet
visible={open}
placement='bottom'
height={sheetHeight(80)}
title={t('选择模型')}
onCancel={close}
bodyStyle={{
padding: 0,
paddingBottom: 'env(safe-area-inset-bottom, 0px)',
display: 'flex',
flexDirection: 'column',
}}
className='mp-sheet'
closeOnEsc
>
{open ? panel : null}
</SideSheet>
</>
);
}
return (
<Popover
visible={open}
trigger='custom'
position='topLeft'
showArrow={false}
onClickOutSide={() => setOpen(false)}
onEscKeyDown={close}
content={open ? panel : null}
contentClassName='mp-popover'
>
{trigger}
</Popover>
);
};
export default ModelPicker;
@@ -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 <https://www.gnu.org/licenses/>.
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 (
<div
id={option.id}
role='option'
aria-selected={selected}
aria-disabled={locked || Boolean(compareBlock) || undefined}
className={cls}
onMouseDown={(e) => e.preventDefault()}
onClick={() => onPick(model)}
onMouseMove={onHover}
>
<div className='mp-card-head'>
<span className='mp-card-name' title={model.model}>
{displayNameOf(model)}
</span>
{badges.map((b) => (
<span key={b.key} className={`mp-badge mp-badge--${b.key}`}>
{t(b.label)}
</span>
))}
{locked ? (
<span className='mp-badge mp-badge--locked'>
<Lock size={11} aria-hidden />
{t('需升级')}
</span>
) : null}
{comparing ? (
<span
className={`mp-card-box${selected ? ' is-on' : ''}`}
aria-hidden
>
{selected ? <Check size={12} /> : <Square size={12} />}
</span>
) : selected ? (
<Check size={14} className='mp-card-check' aria-hidden />
) : null}
</div>
{model.description ? (
<div className='mp-card-desc' title={model.description}>
{model.description}
</div>
) : null}
{tags.length ? (
<div className='mp-card-tags'>
{tags.map((tag) => (
<span key={tag.key} className='mp-tag'>
{t(tag.label, tag.values)}
</span>
))}
</div>
) : null}
{amount || p50 > 0 || incompatible ? (
<div className='mp-card-meta'>
{amount ? (
<span className='mp-num'>
{price.unitLabel
? t('{{amount}}/{{unit}}', {
amount,
unit: t(price.unitLabel),
})
: amount}
{price.tier ? ` · ${price.tier}` : ''}
</span>
) : null}
{p50 > 0 ? (
<span className='mp-num'>
<Clock size={11} aria-hidden />
{t('约 {{n}} 秒', { n: p50 })}
</span>
) : null}
{incompatible ? (
<span className='mp-card-reason'>
{comparing
? t(incompatible.key, incompatible.values)
: t(incompatible.key, {
mode: t(incompatible.values.mode),
})}
</span>
) : null}
</div>
) : null}
</div>
);
};
/**
* 模型列表面板(组合框模式):焦点留在搜索框,上下键移动 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 = (
<div className='mp-state' aria-busy='true'>
<Skeleton
active
loading
placeholder={<Skeleton.Paragraph rows={4} />}
/>
</div>
);
} else if (error && !models.length) {
body = (
<div className='mp-state' role='alert'>
<span>{t('模型列表加载失败')}</span>
{onRetry ? (
<Button size='small' onClick={() => onRetry()}>
{t('重试')}
</Button>
) : null}
</div>
);
} else if (!models.length) {
body = (
<div className='mp-state'>
{t('当前分组暂无可用模型,请联系管理员开通')}
</div>
);
} else if (!options.length) {
body = <div className='mp-state'>{t('没有匹配的模型')}</div>;
} else {
let cursor = -1;
body = groups.map((g) => {
const headId = `${listId}-${g.key === RECENT_GROUP ? 'recent' : String(g.key).replace(/[^\w-]/g, '_')}`;
return (
<div key={g.key} role='group' aria-labelledby={headId}>
<div id={headId} className='mp-group-title'>
{groupLabel(g)}
</div>
<div className='mp-group-grid'>
{g.models.map((m) => {
cursor += 1;
const index = cursor;
const option = options[index];
return (
<ModelCard
key={option.id}
kind={kind}
model={m}
option={option}
active={index === active}
selected={isSelected(m)}
params={params}
mode={mode}
compare={compare}
onPick={pick}
onHover={() => index !== active && setActive(index)}
/>
);
})}
</div>
</div>
);
});
}
const activeId = options[active]?.id;
return (
<div
className={`mp-panel${compact ? ' mp-panel--compact' : ''}`}
onKeyDown={(e) => e.key === 'Escape' && onKeyDown(e)}
>
{compare?.supported ? (
<div className='mp-compare'>
<Columns2 size={14} aria-hidden className='mp-compare-icon' />
<span className='mp-compare-text'>
<span className='mp-compare-title'>{t('对比生成')}</span>
<span className='mp-compare-desc'>
{t('同一提示词选择 2~4 个模型同时生成,对比效果')}
</span>
</span>
<Switch
size='small'
checked={comparing}
onChange={(on) => compare.setEnabled(on)}
aria-label={t('对比生成')}
/>
</div>
) : null}
<div className='mp-search'>
<Search size={14} aria-hidden className='mp-search-icon' />
<input
ref={inputRef}
type='search'
className='mp-search-input'
placeholder={t('搜索模型')}
value={query}
onChange={(e) => setQuery(e.target.value)}
onKeyDown={onKeyDown}
role='combobox'
aria-expanded='true'
aria-controls={listId}
aria-autocomplete='list'
aria-activedescendant={activeId}
aria-label={t('搜索模型')}
/>
</div>
<div
id={listId}
ref={listRef}
role='listbox'
aria-label={t('选择模型')}
aria-multiselectable={comparing || undefined}
className='mp-list app-scrollbar'
>
{body}
</div>
{comparing ? (
<div className='mp-compare-foot' role='status'>
<span className='mp-compare-count'>
{t('已选 {{n}} / {{max}} 个模型', {
n: compare.names.length,
max: 4,
})}
</span>
<Button size='small' theme='solid' type='primary' onClick={onClose}>
{t('完成')}
</Button>
</div>
) : null}
{lockedNotice ? (
<div className='mp-upgrade' role='status'>
<Lock size={14} aria-hidden />
<span className='mp-upgrade-text'>
{t('{{name}} 需要更高的会员等级', {
name: displayNameOf(lockedNotice),
})}
</span>
<Button
size='small'
theme='solid'
type='primary'
onClick={() => {
onClose();
navigate(UPGRADE_PATH);
}}
>
{t('升级')}
</Button>
</div>
) : null}
</div>
);
};
export default ModelPickerPanel;
@@ -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 <https://www.gnu.org/licenses/>.
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';
@@ -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 <https://www.gnu.org/licenses/>.
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;
}
@@ -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 <https://www.gnu.org/licenses/>.
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.<kind>.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;
};
@@ -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 <https://www.gnu.org/licenses/>.
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']);
});
@@ -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 <https://www.gnu.org/licenses/>.
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 (
<section className='wf-api'>
<button
type='button'
className='wf-api-toggle'
aria-expanded={open}
aria-controls={panelId}
onClick={toggle}
>
<Code2 size={14} aria-hidden='true' />
<span className='wf-api-title'>{t('获取 API 代码')}</span>
<span className='wf-api-badge'>{t('API 同价')}</span>
<ChevronDown
size={14}
aria-hidden='true'
className={`wf-api-caret${open ? ' is-open' : ''}`}
/>
</button>
{open ? (
<div id={panelId} className='wf-api-body'>
<p className='wf-api-desc'>
{t('用同样的参数通过 API 调用,价格与体验中心一致')}
</p>
<div className='wf-api-bar'>
<div
className='wf-api-tabs'
role='tablist'
aria-label={t('代码语言')}
>
{API_CODE_LANGS.map((key) => (
<button
key={key}
type='button'
role='tab'
aria-selected={lang === key}
className={`wf-api-tab${lang === key ? ' is-active' : ''}`}
onClick={() => setLang(key)}
>
{LANG_LABELS[key]}
</button>
))}
</div>
<Button
size='small'
theme='borderless'
icon={<Copy size={12} aria-hidden='true' />}
onClick={async () => {
if (await copy(code)) showSuccess(t('已复制'));
}}
>
{t('复制')}
</Button>
</div>
<pre
className='wf-api-code app-scrollbar'
role='tabpanel'
aria-label={LANG_LABELS[lang]}
tabIndex={0}
>
<code>{code}</code>
</pre>
{call.notes.length ? (
<ul className='wf-api-notes'>
{call.notes.map((note) => (
<li key={note}>{t(note, { path: call.path })}</li>
))}
</ul>
) : null}
<div className='wf-api-foot'>
<span className='wf-api-hint'>
{t('把 sk-xxx 替换为你的 API 密钥')}
</span>
<Button
size='small'
theme='solid'
icon={<KeyRound size={12} aria-hidden='true' />}
onClick={() => navigate(KEY_MANAGEMENT_FROM_STUDIO)}
>
{t('创建密钥')}
</Button>
</div>
</div>
) : null}
</section>
);
};
export default ApiCodePanel;
@@ -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 <https://www.gnu.org/licenses/>.
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 ? <div className='wf-filter-panel-label'>{text}</div> : null;
const wrap = (node, text) =>
vertical ? (
<div>
{label(text)}
{node}
</div>
) : (
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(
<Input
className='wf-filters-search'
prefix={<Search size={14} aria-hidden='true' />}
placeholder={t('搜索提示词或模型')}
aria-label={t('搜索提示词或模型')}
value={input}
onChange={setInput}
showClear
/>,
t('搜索'),
)}
{wrap(
<Select
aria-label={t('状态')}
value={filters.status}
onChange={(v) => setFilters({ status: v })}
optionList={STATUS_OPTIONS.map((o) => ({
value: o.value,
label: t(o.label),
}))}
/>,
t('状态'),
)}
{wrap(
<Select
aria-label={t('模型')}
value={filters.model}
onChange={(v) => setFilters({ model: v })}
optionList={modelOptions}
filter
/>,
t('模型'),
)}
{kind === 'image'
? wrap(
<Select
aria-label={t('尺寸')}
value={filters.size}
onChange={(v) => setFilters({ size: v })}
optionList={sizeOptions}
/>,
t('尺寸'),
)
: null}
<Button
theme={filters.favoritesOnly ? 'solid' : 'light'}
type={filters.favoritesOnly ? 'warning' : 'tertiary'}
icon={<Star size={14} aria-hidden='true' />}
aria-pressed={filters.favoritesOnly}
onClick={() => setFilters({ favoritesOnly: !filters.favoritesOnly })}
>
{t('只看收藏')}
</Button>
</>
);
};
/**
* 作品流筛选栏(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 ? (
<Button
theme={selecting ? 'solid' : 'light'}
type={selecting ? 'primary' : 'tertiary'}
icon={<GitCompare size={14} aria-hidden='true' />}
aria-pressed={selecting}
aria-label={t('多选对比')}
title={t('多选对比')}
onClick={onToggleSelecting}
>
{compact ? null : t('多选对比')}
</Button>
) : null;
if (!compact) {
return (
<div className='wf-filters' role='search'>
<Controls
kind={kind}
api={api}
facets={facets}
input={input}
setInput={setInput}
/>
{compareButton}
</div>
);
}
const panel = (
<div className='wf-filter-panel' role='search'>
<Controls
kind={kind}
api={api}
facets={facets}
vertical
input={input}
setInput={setInput}
/>
<div className='wf-filter-panel-actions'>
<Button
type='tertiary'
disabled={count === 0}
onClick={() => {
setInput('');
api.resetFilters();
}}
>
{t('清除筛选')}
</Button>
<Button theme='solid' onClick={() => setOpen(false)}>
{t('完成')}
</Button>
</div>
</div>
);
const trigger = (
<Badge count={count || undefined} type='primary'>
<Button
theme='light'
type='tertiary'
icon={<Filter size={16} aria-hidden='true' />}
aria-label={t('筛选')}
aria-expanded={open}
onClick={() => setOpen((v) => !v)}
/>
</Badge>
);
return (
<div className='wf-filters'>
{compareButton}
{isMobile ? (
<>
{trigger}
<SideSheet
className='wf-filter-sheet'
title={t('筛选')}
visible={open}
placement='bottom'
height='auto'
onCancel={() => setOpen(false)}
>
{panel}
</SideSheet>
</>
) : (
<Popover
visible={open}
trigger='custom'
position='bottomRight'
onClickOutSide={() => setOpen(false)}
onEscKeyDown={() => setOpen(false)}
content={<div className='p-3'>{panel}</div>}
>
{trigger}
</Popover>
)}
</div>
);
};
export default FilterBar;
@@ -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 <https://www.gnu.org/licenses/>.
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 (
<div className={`wf-placeholder ${className || ''}`}>
<ImageIcon size={20} aria-hidden='true' />
<span>{t('图片暂不可用')}</span>
{canRefresh ? (
<Button
size='small'
theme='borderless'
icon={<RefreshCw size={12} aria-hidden='true' />}
loading={busy}
onClick={(e) => {
e.stopPropagation();
refresh();
}}
>
{t('刷新链接')}
</Button>
) : null}
</div>
);
}
return (
<img
src={image.url}
alt={alt}
loading='lazy'
decoding='async'
className={className}
onError={onError}
/>
);
};
/**
* 视频封面:静音;桌面悬停自动播放,触屏设备进入视口播放;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 (
<div className='wf-placeholder'>
<Clapperboard size={22} aria-hidden='true' />
{failed ? <span>{t('视频暂不可用')}</span> : null}
</div>
);
}
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 (
<video
ref={ref}
// #t=0.1 让未自动播放的浏览器(iOS Safari)也显示首帧作为封面
src={`${url}#t=0.1`}
muted
loop
playsInline
preload='metadata'
aria-label={alt}
onMouseEnter={onEnter}
onMouseLeave={onLeave}
onFocus={onEnter}
onBlur={onLeave}
onError={onError}
/>
);
};
const ActiveOverlay = ({ task, estSeconds, p90 = 0, now }) => {
const { t } = useTranslation();
const elapsed = elapsedSeconds(task, now);
const slow = isSlowTask(task, p90, now);
return (
<div className='wf-active'>
<span className='wf-active-label'>
{task.status === 'queued' ? t('排队中') : t('生成中')}
</span>
<span className='wf-num'>
{estSeconds > 0
? t('已用时 {{elapsed}} / 预计 {{est}}', {
elapsed: formatSeconds(elapsed),
est: formatSeconds(estSeconds),
})
: t('已用时 {{elapsed}}', { elapsed: formatSeconds(elapsed) })}
</span>
{task.progress > 0 ? (
<div
className='wf-progress'
role='progressbar'
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={task.progress}
aria-label={t('生成进度')}
>
<span style={{ width: `${task.progress}%` }} />
</div>
) : null}
{slow ? (
<span className='wf-slow' role='note'>
{t('比平时慢,可以切到其他页面,完成后会提醒你')}
</span>
) : null}
</div>
);
};
export const RefundNote = ({ task }) => {
const { t } = useTranslation();
if (!(task.refundedQuota > 0)) return null;
return (
<span className='wf-refund'>
{t('已退还 {{amount}}', { amount: renderQuota(task.refundedQuota) })}
</span>
);
};
/** 失败原因 → 统一错误映射({ 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 (
<div className='wf-failed'>
<span className='wf-failed-title'>
<AlertCircle size={14} aria-hidden='true' />
{t('生成失败')}
</span>
{reason ? (
<span className='wf-failed-reason' title={task.failReason}>
{reason}
</span>
) : null}
<RefundNote task={task} />
</div>
);
};
const ImageMedia = ({ task, onRefreshImage, alt }) => {
const { t } = useTranslation();
const count = task.images.length;
if (count > 1) {
return (
<>
<div className='wf-grid4'>
{task.images.slice(0, 4).map((_, i) => (
<ResultImage
key={i}
task={task}
index={i}
onRefresh={onRefreshImage}
alt={`${alt} (${i + 1})`}
/>
))}
</div>
<span className='wf-badge wf-badge--br'>
<LayoutGrid size={11} aria-hidden='true' />
{t('{{n}} 张', { n: count })}
</span>
</>
);
}
return (
<ResultImage task={task} index={0} onRefresh={onRefreshImage} alt={alt} />
);
};
/**
* 作品卡片(图像 / 视频)。
* 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 (
<article
className={`wf-card${selected ? ' is-selected' : ''}`}
data-status={task.status}
>
<button
type='button'
className='wf-media'
style={{ aspectRatio: String(ratio) }}
onClick={handleMediaClick}
aria-label={mediaLabel}
aria-pressed={selecting && selectable ? selected : undefined}
disabled={selecting && !selectable}
>
{task.status === 'success' ? (
task.kind === 'video' ? (
<VideoThumb task={task} onRefresh={onRefreshVideo} alt={alt} />
) : (
<ImageMedia task={task} onRefreshImage={onRefreshImage} alt={alt} />
)
) : null}
{active ? (
<ActiveOverlay
task={task}
estSeconds={estSeconds}
p90={p90}
now={now}
/>
) : null}
{failed ? <FailedOverlay task={task} /> : null}
{task.kind === 'video' && task.duration > 0 && !active ? (
<span className='wf-badge wf-badge--bl wf-num'>
{formatSeconds(task.duration)}
</span>
) : null}
{selecting && selectable ? (
<span className='wf-check' aria-hidden='true'>
{selected ? <Check size={14} /> : null}
</span>
) : null}
</button>
{!selecting ? (
<div className={`wf-tools${task.favorited ? ' is-pinned' : ''}`}>
{active && task.cancelable ? (
<Button
size='small'
type='danger'
theme='light'
onClick={() => onCancel?.(task)}
>
{t('取消')}
</Button>
) : null}
{!active ? (
<button
type='button'
className={`wf-icon-btn${task.favorited ? ' is-on' : ''}`}
aria-pressed={task.favorited}
aria-label={task.favorited ? t('取消收藏') : t('收藏')}
title={task.favorited ? t('取消收藏') : t('收藏')}
onClick={() => onFavorite?.(task)}
>
<Star
size={15}
aria-hidden='true'
fill={task.favorited ? 'currentColor' : 'none'}
/>
</button>
) : null}
{actions.length ? (
<Dropdown
trigger='click'
position='bottomRight'
render={
<Dropdown.Menu>
{actions.map((action) => (
<Dropdown.Item
key={action.key}
icon={action.icon}
type={action.danger ? 'danger' : undefined}
onClick={() => action.onClick(task)}
>
{action.label}
</Dropdown.Item>
))}
</Dropdown.Menu>
}
>
<button
type='button'
className='wf-icon-btn'
aria-label={t('更多操作')}
title={t('更多操作')}
>
<MoreHorizontal size={15} aria-hidden='true' />
</button>
</Dropdown>
) : null}
</div>
) : null}
<div className='wf-body'>
<p className='wf-prompt' title={task.prompt}>
{task.prompt || t('(无提示词)')}
</p>
<div className='wf-meta'>
<span title={task.model}>{task.model || t('未知模型')}</span>
{task.kind === 'image' && task.size ? (
<span className='wf-num'>{task.size.replace('x', '×')}</span>
) : null}
{task.kind === 'video' && task.resolution ? (
<span>{task.resolution}</span>
) : null}
</div>
</div>
</article>
);
};
export default memo(WorkCard);
@@ -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 <https://www.gnu.org/licenses/>.
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 (
<div className='wf-placeholder'>
{failed ? t('视频暂不可用') : <Spin />}
</div>
);
}
return (
<video
src={task.videoUrl}
controls
playsInline
preload='metadata'
aria-label={altOf(task, t)}
onError={async () => {
if (triedRef.current === task.videoUrl) {
setFailed(true);
return;
}
triedRef.current = task.videoUrl;
const next = await onRefresh(task);
if (!next || next === task.videoUrl) setFailed(true);
}}
/>
);
};
/**
* 作品详情抽屉(WP B-6,改造自 ImageDetailModal):大图 / 播放器 + 参数 + 操作。
* 桌面右侧抽屉,移动端底部抽屉。打开时拉取详情(参数快照 request、视频播放地址)。
*
* props: task(作品流中的最新对象), visible, onClose, estSeconds,
* getActions(task, index) → [{ key, label, icon, onClick, danger }],
* onFavorite, onCancel, fetchDetail, onRefreshImage, onRefreshVideo
*/
const WorkDetailDrawer = ({
task,
visible,
onClose,
estSeconds = 0,
p90 = 0,
now,
getActions,
onFavorite,
onCancel,
fetchDetail,
onRefreshImage,
onRefreshVideo,
}) => {
const { t } = useTranslation();
const navigate = useNavigate();
const isMobile = useIsMobile();
const [index, setIndex] = useState(0);
const [loadingDetail, setLoadingDetail] = useState(false);
const taskId = task?.id;
useEffect(() => {
setIndex(0);
}, [taskId]);
// 打开时拉取一次详情(快照 / 播放地址 / regenerate_supported)
const fetchedRef = useRef('');
useEffect(() => {
if (!visible || !task || fetchedRef.current === task.id) return;
fetchedRef.current = task.id;
let alive = true;
setLoadingDetail(true);
fetchDetail(task).finally(() => {
if (alive) setLoadingDetail(false);
});
return () => {
alive = false;
};
// 只按作品 id 触发
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [visible, taskId]);
useEffect(() => {
if (!visible) fetchedRef.current = '';
}, [visible]);
if (!task) return null;
const active = isActiveTask(task);
const req = task.request || {};
const modeLabels = adapterOf(task.kind).modeLabels || {};
const modeKey = task.mode || req.mode || '';
const modeLabel = modeKey
? t(modeLabels[modeKey] || LEGACY_MODE_LABELS[modeKey] || modeKey)
: '';
const actions = getActions ? getActions(task, index) : [];
// 失败原因的下一步动作:重试 → 再生成;修改提示词 / 重新上传 → 复用参数;余额不足 → 去充值
const failure = task.status === 'failed' ? failureOf(t, task) : null;
const failureAction = (() => {
if (!failure || !failure.actionLabel) return null;
const action = failure.info.action;
if (action === ERROR_ACTIONS.TOPUP) {
return { topup: true, onClick: () => navigate('/console/topup') };
}
const key = action === ERROR_ACTIONS.RETRY ? 'regenerate' : 'reuse';
const hit = actions.find((a) => a.key === key);
return hit ? { onClick: hit.onClick } : null;
})();
const params = [
[t('模型'), task.model || '-'],
modeLabel ? [t('生成模式'), modeLabel] : null,
task.kind === 'image' && task.size
? [t('尺寸'), task.size.replace('x', '×')]
: null,
task.kind === 'image' && task.quality ? [t('画质'), task.quality] : null,
task.kind === 'image' && task.n > 1 ? [t('张数'), task.n] : null,
task.kind === 'video' && task.ratio ? [t('比例'), task.ratio] : null,
task.kind === 'video' && task.resolution
? [t('分辨率'), task.resolution]
: null,
task.kind === 'video' && task.duration > 0
? [t('时长'), formatSeconds(task.duration)]
: null,
typeof req.seed === 'number' ? [t('种子'), req.seed] : null,
[t('创建时间'), formatTime(task.createdAt)],
task.finishedAt && task.startedAt && !active
? [t('耗时'), formatSeconds((task.finishedAt - task.startedAt) / 1000)]
: null,
task.quota > 0 ? [t('消耗'), renderQuota(task.quota)] : null,
task.quotedQuota > 0 ? [t('预估'), renderQuota(task.quotedQuota)] : null,
].filter(Boolean);
const images = task.images || [];
const elapsed = elapsedSeconds(task, now);
let media;
if (task.status === 'success') {
media =
task.kind === 'video' ? (
<DetailVideo task={task} onRefresh={onRefreshVideo} />
) : (
<ResultImage
task={task}
index={index}
onRefresh={onRefreshImage}
alt={altOf(task, t)}
/>
);
} else if (active) {
media = (
<div className='wf-placeholder'>
<Spin />
<span>{task.status === 'queued' ? t('排队中') : t('生成中')}</span>
<span className='wf-num'>
{estSeconds > 0
? t('已用时 {{elapsed}} / 预计 {{est}}', {
elapsed: formatSeconds(elapsed),
est: formatSeconds(estSeconds),
})
: t('已用时 {{elapsed}}', { elapsed: formatSeconds(elapsed) })}
</span>
{isSlowTask(task, p90, now) ? (
<span className='wf-slow' role='note'>
{t('比平时慢,可以切到其他页面,完成后会提醒你')}
</span>
) : null}
</div>
);
} else {
media = <div className='wf-placeholder'>{t('生成失败')}</div>;
}
return (
<SideSheet
visible={visible}
onCancel={onClose}
title={task.kind === 'video' ? t('视频详情') : t('图片详情')}
placement={isMobile ? 'bottom' : 'right'}
width={isMobile ? undefined : 'min(720px, 92vw)'}
height={isMobile ? sheetHeight(92) : undefined}
bodyStyle={{
paddingBottom: 'calc(16px + env(safe-area-inset-bottom, 0px))',
}}
className='app-scrollbar'
>
<div className='wf-detail'>
<div className='wf-detail-media'>{media}</div>
{task.kind === 'image' && images.length > 1 ? (
<div
className='wf-thumbs app-scrollbar'
role='tablist'
aria-label={t('结果图片')}
>
{images.map((img, i) => (
<button
key={i}
type='button'
role='tab'
aria-selected={i === index}
aria-label={t('第 {{n}} 张', { n: i + 1 })}
className={`wf-thumb${i === index ? ' is-active' : ''}`}
onClick={() => setIndex(i)}
>
{img.url ? <img src={img.url} alt='' loading='lazy' /> : null}
</button>
))}
</div>
) : null}
{task.status === 'failed' ? (
<div className='wf-detail-alert' role='note'>
{failure ? (
<>
<strong>{failure.title}</strong>
{failure.detail ? <div>{failure.detail}</div> : null}
{failure.info.category !== 'unknown' &&
failure.title !== task.failReason ? (
<div className='wf-detail-raw'>{task.failReason}</div>
) : null}
</>
) : (
<div>{t('生成失败')}</div>
)}
<RefundNote task={task} />
{failureAction ? (
<Button
size='small'
type={failureAction.topup ? 'warning' : 'tertiary'}
onClick={failureAction.onClick}
>
{failure.actionLabel}
</Button>
) : null}
</div>
) : null}
<div className='wf-detail-actions'>
{!active ? (
<Button
icon={
<Star
size={14}
aria-hidden='true'
fill={task.favorited ? 'currentColor' : 'none'}
/>
}
type={task.favorited ? 'warning' : 'tertiary'}
aria-pressed={task.favorited}
onClick={() => onFavorite(task)}
>
{task.favorited ? t('已收藏') : t('收藏')}
</Button>
) : null}
{active && task.cancelable ? (
<Button type='danger' onClick={() => onCancel(task)}>
{t('取消任务')}
</Button>
) : null}
{actions.map((action) => (
<Button
key={action.key}
icon={action.icon}
type={action.danger ? 'danger' : 'tertiary'}
onClick={() => action.onClick(task)}
>
{action.label}
</Button>
))}
</div>
<section>
<div className='flex items-center justify-between gap-2'>
<h3 className='wf-detail-section-title'>{t('提示词')}</h3>
{task.prompt ? (
<Button
size='small'
theme='borderless'
icon={<Copy size={12} aria-hidden='true' />}
onClick={async () => {
if (await copy(task.prompt)) showSuccess(t('已复制'));
}}
>
{t('复制')}
</Button>
) : null}
</div>
<p className='wf-detail-prompt'>{task.prompt || t('(无提示词)')}</p>
</section>
<section>
<h3 className='wf-detail-section-title'>
{t('参数')}
{loadingDetail ? (
<Spin size='small' wrapperClassName='ml-2' />
) : null}
</h3>
<dl className='wf-params'>
{params.map(([label, value]) => (
<div key={label}>
<dt>{label}</dt>
<dd title={String(value)}>{value}</dd>
</div>
))}
</dl>
</section>
{!active ? <ApiCodePanel key={task.id} task={task} /> : null}
</div>
</SideSheet>
);
};
export default WorkDetailDrawer;
@@ -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 <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { Button, Modal, Spin } from '@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 (
<div className='wf-wall'>
<div className='wf-wall-head'>
<p className='wf-wall-eyebrow'>{t('灵感模板')}</p>
<h2 className='wf-wall-title'>
{kind === 'video'
? t('从一个模板开始你的第一个视频')
: t('从一个模板开始你的第一张作品')}
</h2>
<p className='wf-wall-desc'>
{t('点击模板会填好提示词与推荐参数,可在下方创作台继续修改')}
</p>
</div>
{groups.map((group) => (
<section
key={group.group || 'default'}
className='wf-wall-group'
aria-label={group.group ? t(group.group) : t('灵感模板')}
>
{group.group ? (
<h3 className='wf-group-title'>
{t(group.group)}
<span className='wf-group-count'>{group.items.length}</span>
</h3>
) : null}
<div className='wf-wall-grid'>
{group.items.map((tpl) => {
const summary = templateParamsSummary(tpl);
return (
<button
key={tpl.id}
type='button'
className='wf-tpl'
onClick={() => onApply(tpl)}
aria-label={t('使用模板:{{title}}', { title: t(tpl.title) })}
>
<span className='wf-tpl-head'>
<span className='wf-tpl-icon' aria-hidden='true'>
<Icon size={16} />
</span>
<span className='wf-tpl-title'>{t(tpl.title)}</span>
{summary ? (
<span className='wf-tpl-meta'>{summary}</span>
) : null}
</span>
<span className='wf-tpl-prompt'>{tpl.prompt}</span>
</button>
);
})}
</div>
</section>
))}
<div className='wf-wall-foot'>
<Button onClick={onStart}>{t('自己写提示词')}</Button>
</div>
</div>
);
};
/**
* 作品流(WP B-6,方案 §4.1 / §4.4 / §4.5):按日期分组、进行中置顶;图像 / 视频卡片;详情抽屉;
* 多选对比(图像);无限滚动;加载 / 空 / 错误态;状态变化 aria-live 播报。
*
* props:
* kind, api = useCreationTasks(kind), form = useCreationForm(kind),
* selecting / onSelectingChange(图像多选对比,开关在 FilterBar)
* onUseAsVideoFirstFrame?(task, ref, previewUrl):图像"用作视频首帧"跨页入口(WP C-3,未传时不显示)
* onContinueVideo?(task):覆盖视频"续写下一段"的默认实现(默认在本页回填尾帧为首帧)
*/
const WorkFeed = ({
kind,
api,
form,
selecting = false,
onSelectingChange,
onUseAsVideoFirstFrame,
onContinueVideo,
}) => {
const { t } = useTranslation();
const {
tasks,
filters,
loading,
loadingMore,
error,
hasMore,
loadMore,
reload,
resetFilters,
announcement,
} = api;
const visibleTasks = useMemo(
() => filterTasks(tasks, filters),
[tasks, filters],
);
const hasActive = useMemo(() => tasks.some(isActiveTask), [tasks]);
const now = useNow(hasActive);
const groups = useMemo(
() => groupTasksByDate(visibleTasks, Date.now()),
[visibleTasks],
);
// 预计耗时 p50 / p90(来自 schema est_seconds;超过 p90 显示慢任务提示)
const estByModel = useMemo(() => {
const map = new Map();
(form.models || []).forEach((m) => {
const p50 = Number(m?.est_seconds?.p50) || 0;
if (m?.model && p50 > 0) map.set(m.model, p50);
});
return map;
}, [form.models]);
const p90ByModel = useMemo(() => {
const map = new Map();
(form.models || []).forEach((m) => {
const p90 = Number(m?.est_seconds?.p90) || 0;
if (m?.model && p90 > 0) map.set(m.model, p90);
});
return map;
}, [form.models]);
// 模型 schema 中的种子参数("换种子再来"只对支持指定种子的模型显示)
const seedParamOf = useCallback(
(modelName) => {
const model = (form.models || []).find((m) => m?.model === modelName);
if (!model) return null;
return (
adapterOf(kind)
.requestParamsOf(model)
.find((p) => p.key === 'seed') || null
);
},
[form.models, kind],
);
// ---------------------------------------------------------------------------
// 详情抽屉
// ---------------------------------------------------------------------------
const [detailId, setDetailId] = useState('');
const detailTask = useMemo(
() => tasks.find((task) => task.id === detailId) || null,
[tasks, detailId],
);
const openDetail = useCallback((task) => setDetailId(task.id), []);
const closeDetail = useCallback(() => setDetailId(''), []);
// ---------------------------------------------------------------------------
// 二次创作:复用参数 / 再生成 / 用作参考图 / 编辑此图 / 下载 / 删除
// ---------------------------------------------------------------------------
const resolveFilled = useCallback(
async (task) => {
let full = task;
if (!full.request) full = (await api.fetchDetail(task)) || task;
if (kind === 'video') {
if (!full.request) {
showError(t('该任务不支持复用参数'));
return null;
}
const filled = formFromTaskRequest(full.request, { newId: newSlotId });
return {
filled: { ...filled, modelName: filled.modelName || full.model },
missing: 0,
supported: full.regenerateSupported === true,
};
}
const filled = full.request
? formFromImageRequest(full.request, { newId: newSlotId })
: formFromLegacyTask(legacyShapeOf(full), { newId: newSlotId });
return {
filled: {
modelName: filled.modelName || full.model || '',
mode: filled.mode,
prompt: filled.prompt,
params: filled.params,
images: {
first_frame: null,
last_frame: null,
reference_images: filled.references,
},
},
missing: filled.missingReferences,
supported: Boolean(full.request) && full.regenerateSupported !== false,
};
},
[api, kind, t],
);
const reuse = useCallback(
async (task) => {
const r = await resolveFilled(task);
if (!r) return;
if (r.missing > 0) showInfo(t('部分参考图已失效,请重新上传'));
if (form.prefill(r.filled)) {
trackCreationEvent('reuse_params', {
kind,
model: r.filled.modelName || '',
regenerate: false,
});
closeDetail();
}
},
[resolveFilled, form, closeDetail, kind, t],
);
// 再生成 = 回填 + 参数仍有效时立即提交;参考图失效 / 快照不完整时只回填并提示
const regenerate = useCallback(
async (task) => {
const r = await resolveFilled(task);
if (!r) return;
const autoSubmit = r.supported && r.missing === 0;
if (!autoSubmit) {
showInfo(t('原参数部分已失效,已回填,请确认后生成'));
}
if (form.prefill(r.filled, { autoSubmit })) {
trackCreationEvent('reuse_params', {
kind,
model: r.filled.modelName || '',
regenerate: true,
});
closeDetail();
}
},
[resolveFilled, form, closeDetail, kind, t],
);
// 换种子再来(WP C-3):同一请求换一个随机种子;参数原样有效时立即提交,否则只回填
const variation = useCallback(
async (task) => {
const r = await resolveFilled(task);
if (!r) return;
const filled = {
...r.filled,
params: variationParams(
r.filled.params,
seedParamOf(r.filled.modelName || task.model),
),
};
const autoSubmit = r.supported && r.missing === 0;
if (!autoSubmit) {
showInfo(t('原参数部分已失效,已回填,请确认后生成'));
}
if (form.prefill(filled, { autoSubmit })) {
trackCreationEvent('reuse_params', {
kind,
model: filled.modelName || '',
regenerate: true,
variation: true,
});
closeDetail();
}
},
[resolveFilled, seedParamOf, form, closeDetail, kind, t],
);
// 续写下一段(WP C-3):尾帧作为首帧(task://id#last_frame,后端优先已转存的尾帧),
// 图生视频、同模型同参数,提示词沿用原文供修改
const continueVideo = useCallback(
async (task) => {
let full = task;
if (!full.request) full = (await api.fetchDetail(task)) || task;
const base = full.request
? formFromTaskRequest(full.request, { newId: newSlotId })
: { modelName: '', prompt: '', params: {} };
const filled = {
modelName: base.modelName || full.model,
mode: 'image2video',
prompt: base.prompt || full.prompt || '',
params: base.params || {},
images: {
first_frame: {
id: newSlotId(),
status: 'ready',
ref: taskLastFrameRef(full.id),
previewUrl: full.lastFrameUrl || null,
source: 'task',
identityType: 'aigc',
},
last_frame: null,
reference_images: [],
},
};
if (
form.prefill(filled, {
notice: t('已将尾帧放入首帧,描述下一段内容后生成'),
})
) {
closeDetail();
}
},
[api, form, closeDetail, t],
);
const handleContinueVideo = onContinueVideo || continueVideo;
const addReference = useCallback(
async (task, index) => {
const image = task.images?.[index];
if (!image?.url) {
showError(t('该图片暂不可用作参考图'));
return false;
}
if (image.reusable) {
form.setImageRef('reference_images', undefined, {
ref: taskImageRef(task.id, index),
previewUrl: image.url,
});
return true;
}
try {
const file = await urlToFile(
image.url,
`reference-${task.id}-${index}`,
);
return await form.pickImage('reference_images', undefined, file);
} catch (e) {
showError(t('参考图加载失败'));
return false;
}
},
[form, t],
);
const applyAsReference = useCallback(
async (task, index = 0) => {
if (!(await addReference(task, index))) return;
form.setMode('edit');
showInfo(t('已加入参考图'));
closeDetail();
form.requestFocus();
},
[addReference, form, closeDetail, t],
);
// 编辑此图:替换参考图槽为这张图,切到编辑模式,光标进入提示词
const editImage = useCallback(
async (task, index = 0) => {
const images = form.form.images || {};
form.setImages({ ...images, reference_images: [] });
if (!(await addReference(task, index))) {
form.setImages(images);
return;
}
form.setMode('edit');
closeDetail();
form.requestFocus();
},
[addReference, form, closeDetail],
);
const download = useCallback(
async (task, index = 0) => {
if (task.kind === 'video') {
const url = task.videoUrl || (await api.refreshVideoUrl(task));
if (!url) {
showError(t('未找到视频URL'));
return;
}
triggerDownload(url, `video_${task.id}.mp4`);
showSuccess(t('开始下载'));
return;
}
const url = task.images?.[index]?.url;
if (!url) {
showError(t('图片不存在'));
return;
}
try {
const resp = await fetch(url);
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
const blob = await resp.blob();
const ext = (blob.type.split('/')[1] || 'png').replace('jpeg', 'jpg');
const objectUrl = URL.createObjectURL(blob);
triggerDownload(objectUrl, `image_${task.id}_${index + 1}.${ext}`);
setTimeout(() => URL.revokeObjectURL(objectUrl), 1000);
showSuccess(t('开始下载'));
} catch (e) {
// 跨域等原因无法读取时,在新窗口打开由用户另存
window.open(url, '_blank', 'noopener');
}
},
[api, t],
);
const confirmDelete = useCallback(
(task) => {
Modal.confirm({
title: t('删除作品'),
content: t('删除后不可恢复,确定删除这个作品吗?'),
okButtonProps: { 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: <SlidersHorizontal size={14} aria-hidden='true' />,
onClick: () => reuse(task),
});
list.push({
key: 'regenerate',
label: t('再生成'),
icon: <RotateCcw size={14} aria-hidden='true' />,
onClick: () => regenerate(task),
});
}
if (done && seedParamOf(task.model)) {
list.push({
key: 'variation',
label: t('换种子再来'),
icon: <Dices size={14} aria-hidden='true' />,
onClick: () => variation(task),
});
}
if (kind === 'image' && done && task.images?.[index]?.url) {
list.push({
key: 'reference',
label: t('用作参考图'),
icon: <ImagePlus size={14} aria-hidden='true' />,
onClick: () => applyAsReference(task, index),
});
list.push({
key: 'edit',
label: t('编辑此图'),
icon: <PenLine size={14} aria-hidden='true' />,
onClick: () => editImage(task, index),
});
// 只有服务端判定可复用(reusable_as_input)的结果才能以 task:// 带到视频页
if (onUseAsVideoFirstFrame && task.images[index].reusable) {
list.push({
key: 'video-first-frame',
label: t('用作视频首帧'),
icon: <Film size={14} aria-hidden='true' />,
onClick: () =>
onUseAsVideoFirstFrame(
task,
taskImageRef(task.id, index),
task.images[index].url,
),
});
}
}
if (
kind === 'video' &&
done &&
task.reusableAsInput !== false &&
(task.reusableAsInput === true || task.lastFrameUrl)
) {
list.push({
key: 'continue',
label: t('续写下一段'),
icon: <Clapperboard size={14} aria-hidden='true' />,
onClick: () => handleContinueVideo(task),
});
}
if (done) {
list.push({
key: 'download',
label: t('下载'),
icon: <Download size={14} aria-hidden='true' />,
onClick: () => download(task, index),
});
}
if (!active) {
list.push({
key: 'delete',
label: t('删除'),
icon: <Trash2 size={14} aria-hidden='true' />,
danger: true,
onClick: () => confirmDelete(task),
});
}
return list;
},
[
kind,
reuse,
regenerate,
applyAsReference,
editImage,
download,
confirmDelete,
onUseAsVideoFirstFrame,
handleContinueVideo,
variation,
seedParamOf,
t,
],
);
// ---------------------------------------------------------------------------
// 多选对比(图像)
// ---------------------------------------------------------------------------
const [selectedIds, setSelectedIds] = useState([]);
const [compareOpen, setCompareOpen] = useState(false);
useEffect(() => {
if (!selecting) setSelectedIds([]);
}, [selecting]);
const isSelectable = useCallback(
(task) =>
kind === 'image' &&
task.status === 'success' &&
Boolean(task.images?.[0]?.url),
[kind],
);
const toggleSelect = useCallback(
(task) => {
setSelectedIds((prev) => {
if (prev.includes(task.id)) return prev.filter((id) => id !== task.id);
if (prev.length >= COMPARE_MAX) {
showInfo(t('最多选择 {{n}} 张', { n: COMPARE_MAX }));
return prev;
}
return [...prev, task.id];
});
},
[t],
);
const compareTasks = useMemo(
() =>
selectedIds
.map((id) => tasks.find((task) => task.id === id))
.filter(Boolean)
.map(compareItemOf),
[selectedIds, tasks],
);
// 对比生成批次的"对比视图"(WP C-2)
const [batchCompare, setBatchCompare] = useState(null);
const openBatchCompare = useCallback(
(batchTasks) => {
const items = comparableBatchTasks(batchTasks).map(compareItemOf);
if (items.length < 2) {
showInfo(t('至少需要 2 张已完成的图片才能对比'));
return;
}
setBatchCompare(items);
},
[t],
);
// ---------------------------------------------------------------------------
// 无限滚动:哨兵在滚动容器(.cs-feed)内可见时持续加载下一页
// ---------------------------------------------------------------------------
const [sentinelVisible, setSentinelVisible] = useState(false);
const observerRef = useRef(null);
const sentinelRef = useCallback((el) => {
observerRef.current?.disconnect();
observerRef.current = null;
if (!el || typeof IntersectionObserver === 'undefined') {
setSentinelVisible(false);
return;
}
const io = new IntersectionObserver(
([entry]) => setSentinelVisible(entry.isIntersecting),
{ root: el.closest('.cs-feed'), rootMargin: '400px 0px' },
);
io.observe(el);
observerRef.current = io;
}, []);
useEffect(() => () => observerRef.current?.disconnect(), []);
// 本地过滤(关键词 / 模型 / 尺寸 / 进行中)时不把全部历史自动翻完:连续 3 页没有新命中就停,
// 改为"加载更多"按钮(WP B-7)。服务端过滤(成功 / 失败 / 收藏)不受影响。
const clientFiltered = hasClientFilter(filters);
const clientKey = `${filters.status}|${filters.model}|${filters.size}|${filters.keyword}`;
const [emptyStreak, setEmptyStreak] = useState(0);
const matchesBeforeRef = useRef(null);
useEffect(() => {
setEmptyStreak(0);
matchesBeforeRef.current = null;
}, [clientKey]);
const loadNextPage = useCallback(() => {
matchesBeforeRef.current = visibleTasks.length;
loadMore();
}, [visibleTasks.length, loadMore]);
useEffect(() => {
if (loadingMore || matchesBeforeRef.current === null) return;
const before = matchesBeforeRef.current;
matchesBeforeRef.current = null;
if (!clientFiltered) return;
setEmptyStreak((n) => nextEmptyStreak(n, before, visibleTasks.length));
// 只在一页加载结束时结算
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [loadingMore]);
const autoLoad = shouldAutoLoad(filters, emptyStreak);
const loadMoreManually = useCallback(() => {
setEmptyStreak(0);
loadNextPage();
}, [loadNextPage]);
useEffect(() => {
if (
autoLoad &&
sentinelVisible &&
hasMore &&
!loading &&
!loadingMore &&
!error
) {
loadNextPage();
}
}, [
autoLoad,
sentinelVisible,
hasMore,
loading,
loadingMore,
error,
loadNextPage,
]);
// ---------------------------------------------------------------------------
// 渲染
// ---------------------------------------------------------------------------
const filtered = activeFilterCount(filters) > 0;
const renderCard = (task) => {
const active = isActiveTask(task);
return (
<WorkCard
key={task.id}
task={task}
estSeconds={estByModel.get(task.model) || 0}
p90={p90ByModel.get(task.model) || 0}
now={active ? now : 0}
getActions={getActions}
onOpen={openDetail}
onFavorite={api.toggleFavorite}
onCancel={api.cancelTask}
onRefreshImage={api.refreshImageUrl}
onRefreshVideo={api.refreshVideoUrl}
selecting={selecting}
selectable={selecting && isSelectable(task)}
selected={selectedIds.includes(task.id)}
onToggleSelect={toggleSelect}
/>
);
};
const liveRegion = (
<div className='wf-sr-only' role='status' aria-live='polite'>
{announcement}
</div>
);
if (loading && tasks.length === 0) {
return (
<div className='wf' aria-busy='true'>
{liveRegion}
<div className='wf-grid'>
{Array.from({ length: 8 }, (_, i) => (
<div key={i} className='wf-skeleton' />
))}
</div>
</div>
);
}
if (error && tasks.length === 0) {
return (
<div className='wf'>
{liveRegion}
<div className='wf-state' role='alert'>
<p className='wf-state-title'>{t('作品加载失败')}</p>
<span>{t('请检查网络后重试')}</span>
<Button onClick={reload}>{t('重试')}</Button>
</div>
</div>
);
}
if (tasks.length === 0 && !filtered) {
return (
<div className='wf'>
{liveRegion}
<TemplateWall
kind={kind}
onApply={(tpl) => {
if (form.applyTemplate(tpl)) {
showSuccess(t('已套用模板:{{title}}', { title: t(tpl.title) }));
}
}}
onStart={form.requestFocus}
/>
</div>
);
}
return (
<div className='wf'>
{liveRegion}
{selecting ? (
<div className='wf-selectbar' role='region' aria-label={t('多选对比')}>
<span className='wf-selectbar-text'>
{t('已选 {{n}} / {{max}} 张,选择 2~4 张已完成的图片进行对比', {
n: selectedIds.length,
max: COMPARE_MAX,
})}
</span>
<Button
theme='solid'
disabled={selectedIds.length < 2}
onClick={() => setCompareOpen(true)}
>
{t('对比')}
</Button>
<Button type='tertiary' onClick={() => onSelectingChange?.(false)}>
{t('取消')}
</Button>
</div>
) : null}
{visibleTasks.length === 0 ? (
<div className='wf-state'>
<p className='wf-state-title'>{t('没有符合条件的作品')}</p>
{hasMore && autoLoad ? (
<span>{t('正在继续查找更早的作品…')}</span>
) : null}
{hasMore && !autoLoad ? (
<span>{t('已加载的作品中没有匹配项,可继续加载更早的作品')}</span>
) : null}
<div className='wf-state-actions'>
{hasMore && !autoLoad ? (
<Button loading={loadingMore} onClick={loadMoreManually}>
{t('加载更多')}
</Button>
) : null}
<Button onClick={resetFilters}>{t('清除筛选')}</Button>
</div>
</div>
) : (
groups.map((group) => (
<section key={group.key} aria-label={t(GROUP_LABEL_KEYS[group.key])}>
<h2 className='wf-group-title'>
{t(GROUP_LABEL_KEYS[group.key])}
<span className='wf-group-count'>{group.tasks.length}</span>
</h2>
<div className='wf-grid'>
{groupBatchRows(group.tasks).map((row) =>
row.type === 'batch' ? (
<div
key={row.key}
className='wf-batch'
role='group'
aria-label={t('对比生成 · {{n}} 个模型', {
n: row.tasks.length,
})}
>
<div className='wf-batch-head'>
<Columns2 size={14} aria-hidden='true' />
<span className='wf-batch-title'>
{t('对比生成 · {{n}} 个模型', {
n: row.tasks.length,
})}
</span>
{kind === 'image' && !selecting ? (
<Button
size='small'
theme='light'
disabled={comparableBatchTasks(row.tasks).length < 2}
onClick={() => openBatchCompare(row.tasks)}
>
{t('对比视图')}
</Button>
) : null}
</div>
<div className='wf-grid'>
{row.tasks.map((task) => renderCard(task))}
</div>
</div>
) : (
renderCard(row.task)
),
)}
</div>
</section>
))
)}
<div ref={sentinelRef} className='wf-more'>
{loadingMore ? <Spin size='small' /> : null}
{!loadingMore && error ? (
<Button size='small' type='tertiary' onClick={loadNextPage}>
{t('加载失败,点击重试')}
</Button>
) : null}
{!loadingMore &&
!error &&
hasMore &&
!autoLoad &&
visibleTasks.length > 0 ? (
<Button size='small' type='tertiary' onClick={loadMoreManually}>
{t('加载更多')}
</Button>
) : null}
{!loadingMore && !error && !hasMore && tasks.length > PAGE_SIZE ? (
<span>{t('没有更多了')}</span>
) : null}
</div>
<WorkDetailDrawer
task={detailTask}
visible={Boolean(detailTask)}
onClose={closeDetail}
estSeconds={detailTask ? estByModel.get(detailTask.model) || 0 : 0}
p90={detailTask ? p90ByModel.get(detailTask.model) || 0 : 0}
now={now}
getActions={getActions}
onFavorite={api.toggleFavorite}
onCancel={api.cancelTask}
fetchDetail={api.fetchDetail}
onRefreshImage={api.refreshImageUrl}
onRefreshVideo={api.refreshVideoUrl}
/>
{kind === 'image' ? (
<ImageCompareModal
visible={compareOpen || Boolean(batchCompare)}
tasks={batchCompare || compareTasks}
onClose={() => {
setCompareOpen(false);
setBatchCompare(null);
}}
/>
) : null}
</div>
);
};
export default WorkFeed;
@@ -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 <https://www.gnu.org/licenses/>.
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;
}
+39
View File
@@ -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 <https://www.gnu.org/licenses/>.
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(),
});
};
+599
View File
@@ -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;
}
}
+347
View File
@@ -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 <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
/*
* 新创作台外壳(WP B-2,方案 §4.1):头部 / 全宽作品流 / 底部创作台。
* - 整页背景由父级 ExperienceCenter 的 <PageBackground rich> 提供,这里不画背景。
* - 顶栏与跑马灯的让位由 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;
}
@@ -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 <https://www.gnu.org/licenses/>.
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 (
<OptionGroup
variant='chips'
options={param?.options || []}
value={value}
onChange={onChange}
ariaLabel={paramLabel(t, param)}
optionDisabledReasons={optionDisabledReasons}
disabledReason={disabledReason}
renderOption={(opt) => (
<span className='cp-option-label'>{optionLabel(t, param, opt)}</span>
)}
/>
);
};
export default ChipGroup;
@@ -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 <https://www.gnu.org/licenses/>.
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 (
<OptionGroup
variant='segmented'
options={param?.options || []}
value={value}
onChange={onChange}
ariaLabel={paramLabel(t, param)}
optionDisabledReasons={optionDisabledReasons}
disabledReason={disabledReason}
getOptionAriaLabel={(opt) => `${optionValue(opt)} ${unitWord}`.trim()}
renderOption={(opt) => (
<span className='cp-option-label tabular-nums'>
{optionLabel(t, param, opt)}
</span>
)}
/>
);
};
export default DurationSegmented;
@@ -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 <https://www.gnu.org/licenses/>.
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' ? (
<img
className='cp-slot-img'
src={value.previewUrl}
alt={labelText}
draggable={false}
/>
) : null;
const ariaLabel = [
labelText,
disabled ? disabledReason : statusText,
canPick ? t('按回车选择图片') : '',
]
.filter(Boolean)
.join(',');
const slot = (
<div
className={`cp-slot is-${status}${dragOver ? ' is-dragover' : ''}${
disabled ? ' is-disabled' : ''
} ${className}`}
role={canPick ? 'button' : 'group'}
tabIndex={0}
aria-label={ariaLabel}
aria-disabled={disabled || undefined}
aria-busy={status === 'uploading' || undefined}
onClick={canPick ? openPicker : undefined}
onKeyDown={onKeyDown}
onDragOver={onDragOver}
onDragLeave={onDragLeave}
onDrop={onDrop}
onPaste={onPaste}
>
<input
ref={inputRef}
type='file'
accept={accept}
className='cp-slot-input'
tabIndex={-1}
aria-hidden='true'
onChange={onInputChange}
/>
{preview}
{status === 'empty' || status === 'expired' ? (
<div className='cp-slot-empty'>
<ImagePlus size={20} aria-hidden='true' />
<span className='cp-slot-status'>{statusText}</span>
{status === 'empty' && hint ? (
<span className='cp-slot-hint'>{t(hint)}</span>
) : null}
{status === 'expired' ? (
<span className='cp-slot-hint'>{t('请重新上传')}</span>
) : null}
</div>
) : null}
{status === 'uploading' ? (
<div className='cp-slot-overlay'>
<Spin size='small' />
<span className='cp-slot-status'>{statusText}</span>
</div>
) : null}
{status === 'error' ? (
<div className='cp-slot-overlay is-error'>
<span className='cp-slot-status'>{statusText}</span>
{onRetry ? (
<button
type='button'
className='cp-slot-action'
onClick={(e) => {
e.stopPropagation();
onRetry();
}}
>
<RotateCcw size={14} aria-hidden='true' />
<span>{t('重试')}</span>
</button>
) : null}
</div>
) : null}
{status === 'unused' ? (
<span className='cp-slot-badge'>{statusText}</span>
) : null}
{status !== 'empty' && onRemove && !disabled ? (
<button
type='button'
className='cp-slot-remove'
aria-label={t('移除{{label}}', { label: labelText })}
title={t('移除')}
onClick={(e) => {
e.stopPropagation();
onRemove();
}}
>
<X size={14} aria-hidden='true' />
</button>
) : null}
<span className='cp-slot-label'>{labelText}</span>
</div>
);
return disabled ? (
<Tooltip content={disabledReason} position='top'>
{slot}
</Tooltip>
) : (
slot
);
};
export default ImageSlot;
@@ -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 <https://www.gnu.org/licenses/>.
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 = (
<div
role='radiogroup'
aria-label={ariaLabel}
aria-disabled={groupDisabled || undefined}
className={`cp-option-group cp-option-group--${variant} ${className}`}
>
{options.map((opt, idx) => {
const key = optionKey(opt);
const selected = key === selectedKey;
const reason = groupDisabled ? '' : optionDisabledReasons[key] || '';
const disabled = isDisabled(opt);
const btn = (
<button
key={key}
ref={(el) => {
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}
</button>
);
return reason ? (
<Tooltip key={key} content={reason} position='top'>
{btn}
</Tooltip>
) : (
btn
);
})}
</div>
);
return groupDisabled ? (
<Tooltip content={disabledReason} position='top'>
{group}
</Tooltip>
) : (
group
);
};
export default OptionGroup;
@@ -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 <https://www.gnu.org/licenses/>.
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 (
<div
className={`creation-params cp-renderer cp-renderer--${placement} ${className}`}
>
{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 (
<div
key={param.key}
className={`cp-row${inline ? ' cp-row--inline' : ''}`}
data-param={param.key}
>
{showLabels ? <div className='cp-row-label'>{label}</div> : null}
<div className='cp-row-control'>
<Control
param={param}
value={values[param.key]}
onChange={(v) => onChange && onChange(param.key, v)}
optionDisabledReasons={optionDisabledReasons}
disabledReason={wholeReason}
/>
</div>
{hint ? (
<div className='cp-row-hint' role='note'>
{hint}
</div>
) : null}
</div>
);
})}
</div>
);
};
export default ParamRenderer;
@@ -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 <https://www.gnu.org/licenses/>.
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: (
<span className='cp-select-option'>
<span className='cp-select-option-label'>{text}</span>
{reason || desc ? (
<span className='cp-select-option-desc'>{reason || desc}</span>
) : null}
</span>
),
};
}),
[options, optionDisabledReasons, param, t],
);
// 选项可能是数字,取值可能是字符串:映射到选项的规范值,保证 Select 能命中
const hit = options.find((o) => optionKey(o) === optionKey(value));
const current = hit !== undefined ? optionValue(hit) : undefined;
const sel = (
<Select
className='cp-select'
size='small'
value={current}
optionList={optionList}
disabled={Boolean(disabledReason)}
onChange={(v) => 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 ? (
<Tooltip content={disabledReason} position='top'>
<span className='cp-inline-trigger cp-inline-trigger--block'>{sel}</span>
</Tooltip>
) : (
sel
);
};
export default ParamSelect;
@@ -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 <https://www.gnu.org/licenses/>.
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 = (
<div className='cp-slider'>
<Slider
min={min}
max={max}
step={step}
value={v}
disabled={Boolean(disabledReason)}
onChange={(n) => onChange && onChange(n)}
tipFormatter={(n) => `${n}${unit}`}
aria-label={paramLabel(t, param)}
/>
<span className='cp-slider-value tabular-nums'>{`${v}${unit}`}</span>
</div>
);
return disabledReason ? (
<Tooltip content={disabledReason} position='top'>
{body}
</Tooltip>
) : (
body
);
};
export default ParamSlider;
@@ -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 <https://www.gnu.org/licenses/>.
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 = (
<Switch
size='small'
checked={Boolean(value)}
disabled={Boolean(disabledReason)}
onChange={(checked) => onChange && onChange(checked)}
aria-label={paramLabel(t, param)}
className='cp-switch'
/>
);
return disabledReason ? (
<Tooltip content={disabledReason} position='top'>
<span className='cp-inline-trigger'>{sw}</span>
</Tooltip>
) : (
sw
);
};
export default ParamSwitch;
@@ -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 <https://www.gnu.org/licenses/>.
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 = (
<TextArea
className='cp-textarea app-scrollbar'
value={value ?? ''}
onChange={(v) => onChange && onChange(v)}
maxCount={max}
maxLength={max}
autosize={{ minRows: 2, maxRows: 5 }}
disabled={Boolean(disabledReason)}
aria-label={paramLabel(t, param)}
placeholder={param?.placeholder ? t(param.placeholder) : ''}
/>
);
return disabledReason ? (
<Tooltip content={disabledReason} position='top'>
<span className='cp-inline-trigger cp-inline-trigger--block'>{area}</span>
</Tooltip>
) : (
area
);
};
export default ParamTextArea;
@@ -0,0 +1,78 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import { useTranslation } from 'react-i18next';
import OptionGroup from './OptionGroup';
import { optionValue, parseRatio } from './constraints';
import { optionLabel, paramLabel } from './labels';
const BOX = 18;
const MIN_SIDE = 5;
/** 按宽高比绘制的小矩形图标(尺寸来自数值计算,颜色走 CSS token)。 */
export const RatioShape = ({ ratio }) => {
const r = parseRatio(ratio);
let w = BOX;
let h = BOX;
if (!Number.isNaN(r) && r > 0) {
if (r >= 1) h = Math.max(MIN_SIDE, Math.round(BOX / r));
else w = Math.max(MIN_SIDE, Math.round(BOX * r));
}
return (
<span className='cp-ratio-shape-box' aria-hidden='true'>
<span className='cp-ratio-shape' style={{ width: w, height: h }} />
</span>
);
};
/**
* 比例选择(schema type = 'ratio')。
* props: { param, value, onChange(value), optionDisabledReasons?, disabledReason? }
*/
const RatioPicker = ({
param,
value,
onChange,
optionDisabledReasons,
disabledReason,
}) => {
const { t } = useTranslation();
return (
<OptionGroup
variant='ratio'
options={param?.options || []}
value={value}
onChange={onChange}
ariaLabel={paramLabel(t, param)}
optionDisabledReasons={optionDisabledReasons}
disabledReason={disabledReason}
renderOption={(opt) => (
<>
<RatioShape ratio={optionValue(opt)} />
<span className='cp-option-label tabular-nums'>
{optionLabel(t, param, opt)}
</span>
</>
)}
/>
);
};
export default RatioPicker;
@@ -0,0 +1,104 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useRef } from 'react';
import { InputNumber, Switch, Tooltip } from '@douyinfe/semi-ui';
import { Dices } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { paramLabel } from './labels';
import './creation-params.css';
const DEFAULT_MAX_SEED = 2147483647;
export const isRandomSeed = (v) =>
v === undefined || v === null || v === '' || Number.isNaN(Number(v));
export const randomSeed = (max = DEFAULT_MAX_SEED) =>
Math.floor(Math.random() * (max + 1));
/**
* 随机种子(schema type = 'seed')。
* 取值约定:null / undefined → 随机(不传给后端);整数 → 锁定该种子。
* props: { param, value, onChange(number|null), disabledReason? }
*/
const SeedInput = ({ param, value, onChange, disabledReason }) => {
const { t } = useTranslation();
const min = typeof param?.min === 'number' ? param.min : 0;
const max = typeof param?.max === 'number' ? param.max : DEFAULT_MAX_SEED;
const random = isRandomSeed(value);
const lastLocked = useRef(random ? null : Number(value));
if (!random) lastLocked.current = Number(value);
const disabled = Boolean(disabledReason);
const label = paramLabel(t, param);
const emit = (v) => onChange && onChange(v);
const body = (
<div className='cp-seed' role='group' aria-label={label}>
<label className='cp-seed-toggle'>
<Switch
size='small'
checked={random}
disabled={disabled}
aria-label={t('随机种子开关')}
onChange={(checked) => {
if (checked) emit(null);
else emit(lastLocked.current ?? randomSeed(max));
}}
/>
<span className='cp-seed-toggle-text'>{t('随机')}</span>
</label>
<InputNumber
className='cp-seed-input tabular-nums'
size='small'
min={min}
max={max}
precision={0}
hideButtons
value={random ? undefined : Number(value)}
placeholder={t('随机')}
disabled={disabled || random}
aria-label={t('种子数值')}
onNumberChange={(n) => {
if (typeof n === 'number' && !Number.isNaN(n)) emit(n);
}}
/>
<button
type='button'
className='cp-icon-btn'
disabled={disabled}
aria-label={t('随机生成一个种子并锁定')}
title={t('随机生成一个种子并锁定')}
onClick={() => emit(randomSeed(max))}
>
<Dices size={16} aria-hidden='true' />
</button>
</div>
);
return disabledReason ? (
<Tooltip content={disabledReason} position='top'>
{body}
</Tooltip>
) : (
body
);
};
export default SeedInput;
@@ -0,0 +1,300 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
// 创作参数 schema 的纯函数工具(无 React / 无 i18n 依赖,可直接 node --test)。
//
// schema 约定见 docs/11-前端与体验中心/12-体验中心图像与视频生成升级改造方案.md §3.1:
// params[]: { key, type, options?, default?, unit?, placement?, min?, max?, step?, modes? }
// constraints[]: { when: { [key]: value | value[] }, limit: { [key]: allowedValue[] }, message? }
/** 选项的规范化 key:数字 5 与字符串 "5" 视为同一选项。 */
export function optionKey(v) {
if (v && typeof v === 'object' && 'value' in v) return String(v.value);
return String(v);
}
/**
* 参数是否适用于当前生成模式:schema 参数可带 modes: string[](缺省 / 空数组 = 所有模式)。
* 不适用的参数不渲染、不提交(如 gpt-image 的 background 只在文生图可用,图生图不可用)。
* mode 为空时不过滤。
*/
export function paramSupportsMode(param, mode) {
if (!param || !mode) return true;
const modes = param.modes;
if (!Array.isArray(modes) || modes.length === 0) return true;
return modes.includes(mode);
}
/** 按当前模式过滤参数列表(见 paramSupportsMode)。 */
export function paramsForMode(params, mode) {
return (params || []).filter((p) => paramSupportsMode(p, mode));
}
/** 选项的取值(兼容 { value, label } 对象形式的选项)。 */
export function optionValue(v) {
if (v && typeof v === 'object' && 'value' in v) return v.value;
return v;
}
function matchesWhen(values, when) {
if (!when || typeof when !== 'object') return false;
const entries = Object.entries(when);
if (entries.length === 0) return false;
return entries.every(([k, expected]) => {
const actual = values ? values[k] : undefined;
if (actual === undefined || actual === null) return false;
if (Array.isArray(expected)) {
return expected.some((e) => optionKey(e) === optionKey(actual));
}
return optionKey(expected) === optionKey(actual);
});
}
/**
* 根据当前取值计算被约束禁用的选项。
*
* @param {Record<string, any>} values 当前参数取值
* @param {Array<{when:object, limit:object, message?:string}>} constraints
* @param {Array<{key:string, options?:any[]}>} [params] 传入时才能算出"被禁用的具体选项";
* 不传时只返回 allowed 白名单与 reasons。
* @returns {{
* disabledOptions: Record<string, Record<string, {when:object, allowed:any[], message?:string}>>,
* allowed: Record<string, any[]>,
* reasons: Record<string, Array<{when:object, allowed:any[], message?:string}>>,
* }}
* - disabledOptions[key][optionKey] → 禁用原因(命中的那条约束)
* - allowed[key] → 多条约束命中时取交集后的合法值
* - reasons[key] → 命中的约束列表(用于控件下方说明)
*/
export function applyConstraints(values, constraints, params) {
const disabledOptions = {};
const allowed = {};
const reasons = {};
if (!Array.isArray(constraints)) return { disabledOptions, allowed, reasons };
const paramMap = {};
if (Array.isArray(params)) {
params.forEach((p) => {
if (p && p.key) paramMap[p.key] = p;
});
}
constraints.forEach((c) => {
if (!c || !c.limit || !matchesWhen(values, c.when)) return;
Object.entries(c.limit).forEach(([key, list]) => {
if (!Array.isArray(list)) return;
const reason = { when: c.when, allowed: list };
if (c.message) reason.message = c.message;
(reasons[key] = reasons[key] || []).push(reason);
const listKeys = new Set(list.map(optionKey));
allowed[key] = allowed[key]
? allowed[key].filter((v) => listKeys.has(optionKey(v)))
: list.slice();
const param = paramMap[key];
if (param && Array.isArray(param.options)) {
param.options.forEach((opt) => {
const k = optionKey(opt);
if (listKeys.has(k)) return;
disabledOptions[key] = disabledOptions[key] || {};
if (!disabledOptions[key][k]) disabledOptions[key][k] = reason;
});
}
});
});
return { disabledOptions, allowed, reasons };
}
/** 解析 "16:9" / "16x9" / "16/9" 为宽高比数值;无法解析返回 NaN。 */
export function parseRatio(v) {
if (typeof v === 'number') return v;
if (typeof v !== 'string') return NaN;
const m = v.trim().match(/^(\d+(?:\.\d+)?)\s*[:x×/*]\s*(\d+(?:\.\d+)?)$/i);
if (!m) return NaN;
const w = Number(m[1]);
const h = Number(m[2]);
if (!w || !h) return NaN;
return w / h;
}
function toNumber(v) {
if (typeof v === 'number') return v;
if (typeof v === 'string') {
// 允许带单位后缀:"5"、"5s"、"720P"
const m = v.trim().match(/^(-?\d+(?:\.\d+)?)\s*[a-z]*$/i);
return m ? Number(m[1]) : NaN;
}
return NaN;
}
/** 参数默认值:schema default 合法时用它,否则取第一个选项。 */
export function getParamDefault(param) {
if (!param) return undefined;
const opts = Array.isArray(param.options) ? param.options : null;
if (opts && opts.length > 0) {
if (param.default !== undefined) {
const hit = opts.find((o) => optionKey(o) === optionKey(param.default));
if (hit !== undefined) return optionValue(hit);
}
return optionValue(opts[0]);
}
if (param.default !== undefined) return param.default;
if (param.type === 'switch') return false;
return undefined;
}
/** 由 params 生成默认取值表(跳过无默认值的参数,如 seed)。 */
export function getDefaultValues(params) {
const out = {};
(params || []).forEach((p) => {
if (!p || !p.key) return;
const d = getParamDefault(p);
if (d !== undefined) out[p.key] = d;
});
return out;
}
/**
* 将取值吸附到该参数最近的合法选项。
*
* - ratio:按宽高比的对数距离取最接近者(16:10 → 16:9)
* - 数值选项(时长等):取数值最接近者,距离相同取较小值
* - 其他(chips/select 字符串):取默认值,否则第一个选项
* - 无 options 的参数(switch/seed/textarea/slider):
* slider 夹到 [min,max];其余原样返回
*
* @param {object} param schema 中的单个参数
* @param {any} value 当前取值
* @param {Record<string, any>} [disabled] 该参数被约束禁用的选项(applyConstraints().disabledOptions[key])
* @returns {{ value: any, changed: boolean }}
* value 为 null/undefined 时返回默认值且 changed=false(不是用户值被改,不需要提示)。
*/
export function snapToNearest(param, value, disabled) {
if (!param) return { value, changed: false };
const opts = Array.isArray(param.options) ? param.options : null;
if (!opts || opts.length === 0) {
if (param.type === 'slider' && value !== undefined && value !== null) {
const n = toNumber(value);
if (Number.isNaN(n)) {
return { value: getParamDefault(param), changed: true };
}
let clamped = n;
if (typeof param.min === 'number') clamped = Math.max(param.min, clamped);
if (typeof param.max === 'number') clamped = Math.min(param.max, clamped);
return { value: clamped, changed: clamped !== n };
}
if (value === undefined || value === null) {
return { value: getParamDefault(param), changed: false };
}
return { value, changed: false };
}
const usable = opts.filter((o) => !(disabled && disabled[optionKey(o)]));
const pool = usable.length > 0 ? usable : opts;
if (value === undefined || value === null || value === '') {
const d = getParamDefault(param);
const inPool = pool.find((o) => optionKey(o) === optionKey(d));
return {
value: inPool !== undefined ? optionValue(inPool) : optionValue(pool[0]),
changed: false,
};
}
const exact = pool.find((o) => optionKey(o) === optionKey(value));
if (exact !== undefined) return { value: optionValue(exact), changed: false };
if (param.type === 'ratio') {
const target = parseRatio(value);
if (!Number.isNaN(target)) {
let best = null;
let bestDist = Infinity;
pool.forEach((o) => {
const r = parseRatio(optionValue(o));
if (Number.isNaN(r)) return;
const d = Math.abs(Math.log(r) - Math.log(target));
if (d < bestDist - 1e-9) {
bestDist = d;
best = o;
}
});
if (best !== null) return { value: optionValue(best), changed: true };
}
}
const target = toNumber(value);
const numericPool = pool.filter(
(o) => !Number.isNaN(toNumber(optionValue(o))),
);
if (!Number.isNaN(target) && numericPool.length === pool.length) {
let best = numericPool[0];
let bestDist = Infinity;
numericPool.forEach((o) => {
const n = toNumber(optionValue(o));
const d = Math.abs(n - target);
if (d < bestDist || (d === bestDist && n < toNumber(optionValue(best)))) {
bestDist = d;
best = o;
}
});
return { value: optionValue(best), changed: true };
}
const d = getParamDefault(param);
const inPool = pool.find((o) => optionKey(o) === optionKey(d));
return {
value: inPool !== undefined ? optionValue(inPool) : optionValue(pool[0]),
changed: true,
};
}
/**
* 对整张取值表做吸附(切换模型时用)。
*
* @returns {{ values: Record<string, any>, adjustments: Array<{key:string, from:any, to:any}> }}
* adjustments 只包含"用户原有值被改掉"的项,可用于轻提示。
*/
export function snapValues(params, values, constraints) {
const out = { ...(values || {}) };
const adjustments = [];
const list = (params || []).filter((p) => p && p.key);
list.forEach((p) => {
const r = snapToNearest(p, out[p.key]);
if (r.changed)
adjustments.push({ key: p.key, from: out[p.key], to: r.value });
if (r.value !== undefined) out[p.key] = r.value;
});
// 约束可能使某些已吸附的值失效,再按约束吸附一轮
if (Array.isArray(constraints) && constraints.length > 0) {
const { disabledOptions } = applyConstraints(out, constraints, list);
list.forEach((p) => {
const dis = disabledOptions[p.key];
if (!dis || !dis[optionKey(out[p.key])]) return;
const r = snapToNearest(p, out[p.key], dis);
if (r.changed) {
adjustments.push({ key: p.key, from: out[p.key], to: r.value });
out[p.key] = r.value;
}
});
}
return { values: out, adjustments };
}
@@ -0,0 +1,195 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import assert from 'node:assert/strict';
import test from 'node:test';
import {
applyConstraints,
getDefaultValues,
parseRatio,
snapToNearest,
snapValues,
} from './constraints.js';
const params = [
{
key: 'aspect_ratio',
type: 'ratio',
options: ['16:9', '9:16', '1:1', '4:3', '3:4', '21:9'],
default: '16:9',
placement: 'dock',
},
{
key: 'resolution',
type: 'chips',
options: ['480P', '720P', '1080P'],
default: '720P',
placement: 'dock',
},
{
key: 'duration',
type: 'segmented',
options: [5, 10],
default: 5,
unit: 's',
placement: 'dock',
},
{
key: 'generate_audio',
type: 'switch',
default: true,
placement: 'advanced',
},
{ key: 'seed', type: 'seed', placement: 'advanced' },
];
const constraints = [
{ when: { resolution: '1080P' }, limit: { duration: [5] } },
];
test('applyConstraints disables options outside the limit when matched', () => {
const r = applyConstraints(
{ resolution: '1080P', duration: 10 },
constraints,
params,
);
assert.deepEqual(Object.keys(r.disabledOptions.duration), ['10']);
assert.deepEqual(r.allowed.duration, [5]);
assert.equal(r.reasons.duration.length, 1);
assert.deepEqual(r.disabledOptions.duration['10'].when, {
resolution: '1080P',
});
});
test('applyConstraints ignores unmatched constraints and bad input', () => {
assert.deepEqual(
applyConstraints({ resolution: '720P' }, constraints, params),
{
disabledOptions: {},
allowed: {},
reasons: {},
},
);
assert.deepEqual(applyConstraints({}, null).disabledOptions, {});
});
test('applyConstraints supports array conditions and intersects limits', () => {
const r = applyConstraints(
{ resolution: '1080P' },
[
{
when: { resolution: ['720P', '1080P'] },
limit: { aspect_ratio: ['16:9', '9:16', '1:1'] },
},
{
when: { resolution: '1080P' },
limit: { aspect_ratio: ['16:9', '1:1'] },
},
],
params,
);
assert.deepEqual(r.allowed.aspect_ratio, ['16:9', '1:1']);
assert.deepEqual(Object.keys(r.disabledOptions.aspect_ratio).sort(), [
'21:9',
'3:4',
'4:3',
'9:16',
]);
});
test('parseRatio', () => {
assert.equal(parseRatio('16:9'), 16 / 9);
assert.equal(parseRatio('4x3'), 4 / 3);
assert.ok(Number.isNaN(parseRatio('auto')));
});
test('snapToNearest: ratio picks closest aspect', () => {
const p = params[0];
assert.deepEqual(snapToNearest(p, '16:9'), { value: '16:9', changed: false });
assert.deepEqual(snapToNearest(p, '16:10'), { value: '16:9', changed: true });
assert.deepEqual(snapToNearest(p, '2:3'), { value: '3:4', changed: true });
assert.deepEqual(snapToNearest(p, '5:2'), { value: '21:9', changed: true });
});
test('snapToNearest: numbers pick nearest, ties go lower', () => {
const p = params[2];
assert.deepEqual(snapToNearest(p, 8), { value: 10, changed: true });
assert.deepEqual(snapToNearest(p, 6), { value: 5, changed: true });
assert.deepEqual(snapToNearest(p, 7.5), { value: 5, changed: true });
assert.deepEqual(snapToNearest(p, '10'), { value: 10, changed: false });
});
test('snapToNearest: strings fall back to default, missing value is not a change', () => {
const p = {
key: 'style',
type: 'select',
options: ['vivid', 'natural'],
default: 'natural',
};
assert.deepEqual(snapToNearest(p, 'anime'), {
value: 'natural',
changed: true,
});
assert.deepEqual(snapToNearest(p, undefined), {
value: 'natural',
changed: false,
});
assert.deepEqual(snapToNearest(params[3], undefined), {
value: true,
changed: false,
});
assert.deepEqual(snapToNearest(params[4], 42), { value: 42, changed: false });
});
test('snapToNearest respects disabled options', () => {
const { disabledOptions } = applyConstraints(
{ resolution: '1080P' },
constraints,
params,
);
assert.deepEqual(snapToNearest(params[2], 10, disabledOptions.duration), {
value: 5,
changed: true,
});
});
test('snapToNearest clamps slider values', () => {
const p = { key: 'strength', type: 'slider', min: 0, max: 1, step: 0.1 };
assert.deepEqual(snapToNearest(p, 3), { value: 1, changed: true });
assert.deepEqual(snapToNearest(p, 0.5), { value: 0.5, changed: false });
});
test('getDefaultValues and snapValues', () => {
assert.deepEqual(getDefaultValues(params), {
aspect_ratio: '16:9',
resolution: '720P',
duration: 5,
generate_audio: true,
});
const r = snapValues(
params,
{ aspect_ratio: '3:2', resolution: '1080P', duration: 10 },
constraints,
);
assert.equal(r.values.aspect_ratio, '4:3');
assert.equal(r.values.duration, 5);
assert.deepEqual(
r.adjustments.map((a) => a.key),
['aspect_ratio', 'duration'],
);
});
@@ -0,0 +1,494 @@
/*
* 创作参数控件库(WP B-1)样式。
* 配色全部从主题 token 派生(frontend-design skill 铁律一),禁止裸色值。
* 局部变量挂在每个可独立使用的控件根上,单独引用某个控件时同样生效。
*/
.creation-params,
.cp-option-group,
.cp-slot,
.cp-seed,
.cp-slider,
.cp-select,
.cp-select-dropdown {
--cp-ink: var(--text-primary);
--cp-muted: var(--text-secondary);
--cp-line: var(--border-subtle);
--cp-surface: var(--surface-card);
--cp-accent: var(--semi-color-primary);
--cp-accent-tint: color-mix(
in srgb,
var(--semi-color-primary) 10%,
transparent
);
--cp-accent-line: color-mix(
in srgb,
var(--semi-color-primary) 45%,
transparent
);
--cp-fill: color-mix(in srgb, var(--text-primary) 4%, var(--surface-card));
--cp-fill-hover: color-mix(
in srgb,
var(--semi-color-primary) 6%,
var(--surface-card)
);
--cp-danger: var(--semi-color-danger);
--cp-danger-tint: color-mix(
in srgb,
var(--semi-color-danger) 10%,
var(--surface-card)
);
--cp-warning: var(--semi-color-warning);
--cp-ring: color-mix(in srgb, var(--semi-color-primary) 55%, transparent);
--cp-overlay: color-mix(in srgb, var(--surface-card) 78%, transparent);
--cp-dur: var(--motion-fast, 150ms);
}
/* ---------- 渲染器布局 ---------- */
.cp-renderer {
display: flex;
flex-direction: column;
gap: 14px;
min-width: 0;
}
.cp-row {
display: flex;
flex-direction: column;
gap: 6px;
min-width: 0;
}
.cp-row--inline {
flex-direction: row;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
}
.cp-row--inline .cp-row-hint {
flex-basis: 100%;
}
.cp-row-label {
font-size: 12px;
font-weight: 600;
color: var(--cp-muted);
line-height: 18px;
}
.cp-row-control {
min-width: 0;
}
.cp-row-hint {
font-size: 12px;
line-height: 18px;
color: var(--cp-warning);
}
/* ---------- 单选按钮组 ---------- */
.cp-option-group {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.cp-option {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 6px;
min-height: 30px;
padding: 4px 12px;
border: 1px solid var(--cp-line);
border-radius: 8px;
background: var(--cp-fill);
color: var(--cp-ink);
font-size: 13px;
line-height: 20px;
cursor: pointer;
transition:
background-color var(--cp-dur) ease,
border-color var(--cp-dur) ease,
color var(--cp-dur) ease;
}
.cp-option:hover:not(.is-disabled):not(.is-selected) {
background: var(--cp-fill-hover);
border-color: var(--cp-accent-line);
}
.cp-option.is-selected {
background: var(--cp-accent-tint);
border-color: var(--cp-accent);
color: var(--cp-accent);
font-weight: 600;
}
.cp-option.is-disabled {
cursor: not-allowed;
opacity: 0.45;
}
.cp-option-group[aria-disabled='true'] .cp-option {
cursor: not-allowed;
}
.creation-params button:focus-visible,
.cp-option:focus-visible,
.cp-icon-btn:focus-visible,
.cp-slot:focus-visible,
.cp-slot button:focus-visible {
outline: 2px solid var(--cp-ring);
outline-offset: 2px;
}
/* 分段:紧凑连体外观 */
.cp-option-group--segmented {
gap: 0;
display: inline-flex;
padding: 2px;
border: 1px solid var(--cp-line);
border-radius: 9px;
background: var(--cp-fill);
}
.cp-option-group--segmented .cp-option {
min-width: 48px;
border-color: transparent;
background: transparent;
border-radius: 7px;
}
.cp-option-group--segmented .cp-option.is-selected {
background: var(--cp-surface);
border-color: var(--cp-accent-line);
}
/* 比例:形状图标 + 文字,纵向排布 */
.cp-option-group--ratio .cp-option {
flex-direction: column;
gap: 4px;
min-width: 52px;
padding: 6px 8px;
}
.cp-ratio-shape-box {
display: inline-flex;
align-items: center;
justify-content: center;
width: 18px;
height: 18px;
}
.cp-ratio-shape {
display: block;
border: 1.5px solid currentColor;
border-radius: 3px;
opacity: 0.85;
}
.cp-option-label {
white-space: nowrap;
}
.tabular-nums,
.cp-option-group--segmented .cp-option-label,
.cp-option-group--ratio .cp-option-label {
font-variant-numeric: tabular-nums;
}
/* ---------- Select / TextArea / Slider ---------- */
.cp-select {
width: 100%;
}
.cp-select-option {
display: flex;
flex-direction: column;
min-width: 0;
}
.cp-select-option-label {
color: var(--cp-ink);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.cp-select-option-desc {
font-size: 12px;
line-height: 16px;
color: var(--cp-muted);
white-space: normal;
}
.cp-inline-trigger {
display: inline-flex;
}
.cp-inline-trigger--block {
display: flex;
width: 100%;
}
.cp-textarea {
width: 100%;
}
.cp-slider {
display: flex;
align-items: center;
gap: 10px;
}
.cp-slider > :first-child {
flex: 1;
min-width: 0;
}
.cp-slider-value {
min-width: 40px;
text-align: right;
font-size: 13px;
color: var(--cp-ink);
}
/* ---------- 种子 ---------- */
.cp-seed {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
}
.cp-seed-toggle {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 13px;
color: var(--cp-ink);
cursor: pointer;
}
.cp-seed-input {
width: 140px;
}
.cp-icon-btn {
display: inline-flex;
align-items: center;
justify-content: center;
width: 30px;
height: 30px;
border: 1px solid var(--cp-line);
border-radius: 8px;
background: var(--cp-fill);
color: var(--cp-muted);
cursor: pointer;
transition:
color var(--cp-dur) ease,
border-color var(--cp-dur) ease,
background-color var(--cp-dur) ease;
}
.cp-icon-btn:hover:not(:disabled) {
color: var(--cp-accent);
border-color: var(--cp-accent-line);
background: var(--cp-fill-hover);
}
.cp-icon-btn:disabled {
cursor: not-allowed;
opacity: 0.45;
}
/* ---------- 图片槽 ---------- */
.cp-slot {
position: relative;
display: flex;
align-items: center;
justify-content: center;
width: 112px;
height: 112px;
border: 1px dashed var(--cp-line);
border-radius: 12px;
background: var(--cp-fill);
color: var(--cp-muted);
overflow: hidden;
transition:
border-color var(--cp-dur) ease,
background-color var(--cp-dur) ease;
}
.cp-slot[role='button'] {
cursor: pointer;
}
.cp-slot[role='button']:hover,
.cp-slot.is-dragover {
border-color: var(--cp-accent);
background: var(--cp-fill-hover);
color: var(--cp-accent);
}
.cp-slot.is-ready,
.cp-slot.is-uploading,
.cp-slot.is-unused {
border-style: solid;
}
.cp-slot.is-error {
border-color: var(--cp-danger);
}
.cp-slot.is-expired {
border-color: var(--cp-warning);
}
.cp-slot.is-disabled {
cursor: not-allowed;
opacity: 0.5;
}
.cp-slot-input {
display: none;
}
.cp-slot-img {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
object-fit: cover;
}
.cp-slot.is-unused .cp-slot-img {
filter: grayscale(1);
opacity: 0.4;
}
.cp-slot.is-error .cp-slot-img {
opacity: 0.35;
}
.cp-slot-empty {
display: flex;
flex-direction: column;
align-items: center;
gap: 4px;
padding: 18px 8px 22px;
text-align: center;
}
.cp-slot-status {
font-size: 12px;
line-height: 16px;
word-break: break-all;
}
.cp-slot.is-expired .cp-slot-status {
color: var(--cp-warning);
font-weight: 600;
}
.cp-slot-hint {
font-size: 11px;
line-height: 14px;
color: var(--cp-muted);
}
.cp-slot-overlay {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 6px;
padding: 8px 8px 22px;
background: var(--cp-overlay);
color: var(--cp-ink);
text-align: center;
}
.cp-slot-overlay.is-error {
background: var(--cp-danger-tint);
color: var(--cp-danger);
}
.cp-slot-action {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 2px 10px;
border: 1px solid currentColor;
border-radius: 999px;
background: var(--cp-surface);
color: inherit;
font-size: 12px;
cursor: pointer;
}
.cp-slot-remove {
position: absolute;
top: 4px;
right: 4px;
z-index: 2;
display: inline-flex;
align-items: center;
justify-content: center;
width: 22px;
height: 22px;
border: 1px solid var(--cp-line);
border-radius: 999px;
background: var(--cp-overlay);
color: var(--cp-ink);
cursor: pointer;
}
.cp-slot-remove:hover {
color: var(--cp-danger);
border-color: var(--cp-danger);
}
.cp-slot-badge {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
max-width: calc(100% - 12px);
padding: 2px 8px;
border-radius: 999px;
background: var(--cp-overlay);
border: 1px solid var(--cp-line);
color: var(--cp-muted);
font-size: 11px;
line-height: 16px;
text-align: center;
}
.cp-slot-label {
position: absolute;
left: 0;
right: 0;
bottom: 0;
z-index: 1;
padding: 2px 6px;
background: var(--cp-overlay);
color: var(--cp-ink);
font-size: 11px;
line-height: 16px;
text-align: center;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
@media (prefers-reduced-motion: reduce) {
.cp-option,
.cp-icon-btn,
.cp-slot {
transition: none;
}
}
+46
View File
@@ -0,0 +1,46 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
export { default as ParamRenderer, PARAM_CONTROLS } from './ParamRenderer';
export { default as OptionGroup } from './OptionGroup';
export { default as RatioPicker, RatioShape } from './RatioPicker';
export { default as ChipGroup } from './ChipGroup';
export { default as DurationSegmented } from './DurationSegmented';
export { default as ParamSwitch } from './ParamSwitch';
export { default as ParamSelect } from './ParamSelect';
export { default as ParamTextArea } from './ParamTextArea';
export { default as ParamSlider } from './ParamSlider';
export { default as SeedInput, isRandomSeed, randomSeed } from './SeedInput';
export { default as ImageSlot } from './ImageSlot';
export {
applyConstraints,
snapToNearest,
snapValues,
getParamDefault,
getDefaultValues,
parseRatio,
optionKey,
optionValue,
} from './constraints';
export {
PARAM_LABEL_KEYS,
paramLabel,
optionLabel,
formatConstraintReason,
} from './labels';
+97
View File
@@ -0,0 +1,97 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { optionKey, optionValue } from './constraints';
// 已知参数 key 的中文标签(作为 i18n key)。schema 下发了 label 时优先用 label。
export const PARAM_LABEL_KEYS = {
aspect_ratio: '画面比例',
ratio: '画面比例',
resolution: '分辨率',
duration: '时长',
generate_audio: '生成音频',
audio: '生成音频',
seed: '随机种子',
watermark: '水印',
return_last_frame: '返回尾帧',
camera_motion: '运镜',
camera_fixed: '固定镜头',
negative_prompt: '反向提示词',
prompt_extend: '智能扩写提示词',
quality: '画质',
n: '生成数量',
size: '尺寸',
style: '风格',
mode: '生成模式',
};
/** 参数显示名。 */
export function paramLabel(t, param) {
if (!param) return '';
if (param.label) return t(param.label);
const k = PARAM_LABEL_KEYS[param.key];
return k ? t(k) : param.key;
}
/** 单个选项的显示文本:对象选项取 label,否则拼接单位(5 + "s" → "5s")。 */
export function optionLabel(t, param, opt) {
if (opt && typeof opt === 'object' && opt.label) return t(opt.label);
const v = optionValue(opt);
if (typeof v === 'boolean') return v ? t('是') : t('否');
const unit = param && param.unit ? param.unit : '';
return `${v}${unit}`;
}
function describeWhen(t, when, params) {
const byKey = {};
(params || []).forEach((p) => {
if (p && p.key) byKey[p.key] = p;
});
return Object.entries(when || {})
.map(([k, v]) => {
const p = byKey[k] || { key: k };
const vs = Array.isArray(v) ? v : [v];
return `${paramLabel(t, p)} ${vs.map((x) => optionLabel(t, p, x)).join('/')}`;
})
.join('、');
}
/**
* 约束原因 → 一句人话,如"分辨率 1080P 时,时长仅支持 5s"。
* reason 为 applyConstraints 返回的 { when, allowed, message? }。
*/
export function formatConstraintReason(t, reason, param, params) {
if (!reason) return '';
if (reason.message) return t(reason.message);
const allowed = (reason.allowed || [])
.map((v) => optionLabel(t, param, v))
.join(' / ');
return t('{{cond}} 时,{{name}}仅支持 {{allowed}}', {
cond: describeWhen(t, reason.when, params),
name: paramLabel(t, param),
allowed,
});
}
/** 判断选项是否被禁用;返回原因文本或空串。 */
export function disabledReasonOf(t, disabledMap, opt, param, params) {
if (!disabledMap) return '';
const r = disabledMap[optionKey(opt)];
return r ? formatConstraintReason(t, r, param, params) : '';
}
+36
View File
@@ -0,0 +1,36 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
// 底部抽屉高度:支持 dvh 时用动态视口单位(iOS Safari / 微信 H5 地址栏伸缩、键盘弹起时不被裁切),
// 旧内核(不支持 dvh 的 X5 / 旧 WebView)回退 vh——内联样式里写不支持的单位会整条失效。
const SUPPORTS_DVH = (() => {
try {
return (
typeof CSS !== 'undefined' &&
typeof CSS.supports === 'function' &&
CSS.supports('height', '100dvh')
);
} catch (e) {
return false;
}
})();
/** 视口高度百分比:sheetHeight(80) → '80dvh' | '80vh'。 */
export const sheetHeight = (percent) =>
`${percent}${SUPPORTS_DVH ? 'dvh' : 'vh'}`;
@@ -1,613 +0,0 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useState, useCallback, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import {
Input,
Select,
Card,
Button,
Collapse,
Divider,
Tag,
Tooltip,
Slider,
Switch,
Typography,
Alert,
} from '@/components/ui';
import {
PlusCircle,
Zap,
Info,
Palette,
Image as ImageIcon,
Eye,
Sparkles,
Trash2,
} from 'lucide-react';
const { TextArea, InputNumber } = Input;
const { Title, Text } = Typography;
/**
* 图像生成参数配置组件
* @param {Object} props 组件属性
* @param {Object} props.modelInfo 当前选择的模型信息
* @param {Function} props.onParamsChange 参数变化回调函数
* @param {Function} props.onGenerate 生成按钮点击回调
* @param {boolean} props.isGenerating 是否正在生成中
* @param {Object} props.initialParams 初始参数
*/
const ImageGenerationParams = ({
modelInfo,
onParamsChange,
onGenerate,
isGenerating = false,
initialParams = {},
}) => {
const { t } = useTranslation();
// 提取模型能力信息
const modelCapabilities = modelInfo?.capabilities || {};
// 状态管理
const [params, setParams] = useState(() => ({
prompt: initialParams.prompt || '',
negativePrompt: initialParams.negativePrompt || '',
n: initialParams.n || 1,
size: initialParams.size || modelCapabilities.sizes?.[0] || '1024x1024',
quality: initialParams.quality || 'standard',
style: initialParams.style || 'natural',
creativity: initialParams.creativity || 0.7,
guidanceScale: initialParams.guidanceScale || 7.5,
seed: initialParams.seed || null,
useSeed: initialParams.useSeed || false,
showAdvanced: initialParams.showAdvanced || false,
}));
// 当模型信息变化时,更新可用参数
useEffect(() => {
setParams((prev) => {
const newParams = { ...prev };
// 检查当前尺寸是否在模型支持的尺寸列表中
if (
modelCapabilities.sizes &&
!modelCapabilities.sizes.includes(prev.size)
) {
newParams.size = modelCapabilities.sizes[0];
}
// 如果模型不支持质量选择,确保质量设置为standard
if (!modelCapabilities.supportsQuality && prev.quality !== 'standard') {
newParams.quality = 'standard';
}
// 限制生成数量不超过模型支持的最大值
if (modelCapabilities.maxImages && prev.n > modelCapabilities.maxImages) {
newParams.n = modelCapabilities.maxImages;
}
return newParams;
});
}, [modelInfo]);
// 参数更新函数
const updateParam = useCallback(
(key, value) => {
setParams((prev) => {
const newParams = { ...prev, [key]: value };
// 触发参数变化回调
onParamsChange(newParams);
return newParams;
});
},
[onParamsChange],
);
// 处理生成按钮点击
const handleGenerate = useCallback(() => {
// 验证提示词
if (!params.prompt || !params.prompt.trim()) {
alert(t('请输入提示词'));
return;
}
// 调用生成回调
onGenerate(params);
}, [params, onGenerate, t]);
// 样式选项
const styleOptions = [
{
value: 'natural',
label: t('自然'),
description: t('生成逼真、自然的图像'),
},
{
value: 'vivid',
label: t('生动'),
description: t('生成更具表现力、丰富色彩的图像'),
},
{
value: 'artistic',
label: t('艺术'),
description: t('生成具有艺术风格的图像'),
},
{
value: 'photographic',
label: t('摄影'),
description: t('生成类似照片的真实图像'),
},
];
// 获取尺寸选项
const getSizeOptions = useCallback(() => {
const sizeMap = {
'256x256': { label: '256×256', description: t('最小尺寸,生成速度快') },
'512x512': {
label: '512×512',
description: t('中等尺寸,平衡质量和速度'),
},
'1024x1024': { label: '1024×1024', description: t('标准高清尺寸') },
'1024x1792': {
label: '1024×1792 (9:16)',
description: t('纵向比例,适合手机壁纸'),
},
'1792x1024': {
label: '1792×1024 (16:9)',
description: t('横向比例,适合桌面壁纸'),
},
'1344x1024': { label: '1344×1024', description: t('宽屏比例') },
'1024x1344': { label: '1024×1344', description: '竖屏比例' },
};
// 如果有模型支持的尺寸列表,使用它过滤
if (modelCapabilities.sizes) {
return modelCapabilities.sizes.map((size) => ({
value: size,
label: sizeMap[size]?.label || size,
description: sizeMap[size]?.description || '',
}));
}
// 否则返回所有尺寸
return Object.keys(sizeMap).map((size) => ({
value: size,
label: sizeMap[size].label,
description: sizeMap[size].description,
}));
}, [modelCapabilities.sizes, t]);
// 质量选项
const qualityOptions = [
{
value: 'standard',
label: t('标准'),
description: t('标准质量,速度较快'),
},
{ value: 'hd', label: t('高清'), description: t('更高质量,细节更丰富') },
];
// 预设提示词模板
const promptTemplates = [
{
title: t('风景照片'),
prompt: t(
'a beautiful landscape with mountains, lake and trees, in realistic style, high detail, natural lighting',
),
},
{
title: t('肖像'),
prompt: t(
'portrait of a person, detailed facial features, professional photography, soft lighting',
),
},
{
title: t('科幻场景'),
prompt: t(
'futuristic cityscape, flying cars, neon lights, science fiction, highly detailed',
),
},
{
title: t('动画风格'),
prompt: t(
'cute anime character, colorful, detailed, digital illustration, anime style',
),
},
];
// 应用提示词模板
const applyPromptTemplate = useCallback(
(template) => {
updateParam('prompt', template.prompt);
},
[updateParam],
);
// 清除所有参数
const clearAllParams = useCallback(() => {
const clearedParams = {
prompt: '',
negativePrompt: '',
n: 1,
size: modelCapabilities.sizes?.[0] || '1024x1024',
quality: 'standard',
style: 'natural',
creativity: 0.7,
guidanceScale: 7.5,
seed: null,
useSeed: false,
};
setParams(clearedParams);
onParamsChange(clearedParams);
}, [modelCapabilities.sizes, onParamsChange]);
// 渲染尺寸选项下拉框
const renderSizeSelect = () => {
const sizeOptions = getSizeOptions();
return (
<Tooltip
content={
sizeOptions.find((option) => option.value === params.size)
?.description || ''
}
position='topLeft'
trigger={['hover']}
>
<Select
value={params.size}
onChange={(value) => updateParam('size', value)}
options={sizeOptions.map((option) => ({
value: option.value,
label: option.label,
}))}
className='w-full'
/>
</Tooltip>
);
};
// 渲染质量选项下拉框
const renderQualitySelect = () => {
const disabled = !modelCapabilities.supportsQuality;
return (
<Tooltip
content={disabled ? t('当前模型不支持质量选择') : ''}
position='topLeft'
trigger={['hover']}
>
<Select
value={params.quality}
onChange={(value) => updateParam('quality', value)}
options={qualityOptions}
disabled={disabled}
className='w-full'
/>
</Tooltip>
);
};
// 最大图片数量
const maxImages = modelCapabilities.maxImages || 1;
return (
<Card className='overflow-hidden'>
<div className='p-6'>
{/* 提示词输入 */}
<div className='mb-6'>
<div className='flex justify-between items-center mb-2'>
<Title level={4} className='mb-0'>
<div className='flex items-center'>
<Sparkles size={16} className='mr-2 text-blue-500' />
{t('提示词')}
</div>
</Title>
<Tooltip content={t('提示词越详细,生成的图片越符合预期')}>
<Info size={16} className='text-gray-400 cursor-help' />
</Tooltip>
</div>
<TextArea
value={params.prompt}
onChange={(e) => updateParam('prompt', e.target.value)}
placeholder={t('描述你想要生成的图像...')}
rows={5}
className='mb-3'
maxLength={2000}
/>
<div className='text-xs text-gray-500 dark:text-gray-400 mb-4'>
{params.prompt.length}/2000
</div>
{/* 提示词模板 */}
{promptTemplates.length > 0 && (
<div>
<Text type='secondary' className='text-xs mb-2'>
{t('快速模板:')}
</Text>
<div className='flex flex-wrap gap-2'>
{promptTemplates.map((template, index) => (
<Tag
key={index}
clickable
color='blue'
size='small'
onClick={() => applyPromptTemplate(template)}
className='cursor-pointer'
>
{template.title}
</Tag>
))}
</div>
</div>
)}
</div>
{/* 高级选项 */}
<Collapse
items={[
{
title: (
<div className='flex items-center cursor-pointer'>
<PlusCircle size={16} className='mr-2' />
<span>{t('高级选项')}</span>
</div>
),
content: (
<div className='space-y-4 pt-2'>
{/* 反向提示词 */}
<div>
<div className='flex justify-between items-center mb-2'>
<Text type='secondary'>{t('反向提示词')}</Text>
<Tooltip content={t('描述你不想要在图像中出现的内容')}>
<Info size={14} className='text-gray-400 cursor-help' />
</Tooltip>
</div>
<TextArea
value={params.negativePrompt}
onChange={(e) =>
updateParam('negativePrompt', e.target.value)
}
placeholder={t('例如: 模糊, 扭曲, 低质量...')}
rows={3}
maxLength={1000}
/>
<div className='text-xs text-gray-500 dark:text-gray-400'>
{params.negativePrompt.length}/1000
</div>
</div>
<Divider />
{/* 基本参数 */}
<div>
<div className='flex justify-between items-center mb-3'>
<Text type='secondary'>{t('基本参数')}</Text>
</div>
<div className='grid grid-cols-1 sm:grid-cols-2 gap-4'>
{/* 图片数量 */}
<div>
<Text type='secondary' className='text-xs mb-1'>
{t('图片数量')}
</Text>
<InputNumber
value={params.n}
onChange={(value) =>
updateParam(
'n',
Math.min(Math.max(1, value), maxImages),
)
}
min={1}
max={maxImages}
className='w-full'
/>
<Text type='secondary' className='text-xs mt-1'>
{t('最大: {{max}}', { max: maxImages })}
</Text>
</div>
{/* 图片尺寸 */}
<div>
<Text type='secondary' className='text-xs mb-1'>
<div className='flex items-center'>
<ImageIcon size={12} className='mr-1' />
{t('图片尺寸')}
</div>
</Text>
{renderSizeSelect()}
</div>
{/* 图片质量 */}
<div>
<Text type='secondary' className='text-xs mb-1'>
<div className='flex items-center'>
<Eye size={12} className='mr-1' />
{t('图片质量')}
</div>
</Text>
{renderQualitySelect()}
</div>
{/* 风格 */}
<div>
<Text type='secondary' className='text-xs mb-1'>
<div className='flex items-center'>
<Palette size={12} className='mr-1' />
{t('风格')}
</div>
</Text>
<Select
value={params.style}
onChange={(value) => updateParam('style', value)}
options={styleOptions}
className='w-full'
/>
</div>
</div>
</div>
<Divider />
{/* 高级控制参数 */}
<div>
<div className='flex justify-between items-center mb-3'>
<Text type='secondary'>{t('高级控制')}</Text>
</div>
{/* 创意思维度 */}
<div className='mb-4'>
<div className='flex justify-between items-center mb-1'>
<Text type='secondary' className='text-xs'>
{t('创意思维度')}
</Text>
<Text type='secondary' className='text-xs'>
{params.creativity.toFixed(1)}
</Text>
</div>
<Slider
value={params.creativity}
onChange={(value) => updateParam('creativity', value)}
min={0.1}
max={1.0}
step={0.1}
/>
<div className='flex justify-between text-xs text-gray-500 dark:text-gray-400'>
<Text>{t('保守')}</Text>
<Text>{t('平衡')}</Text>
<Text>{t('创新')}</Text>
</div>
</div>
{/* 引导系数 */}
<div className='mb-4'>
<div className='flex justify-between items-center mb-1'>
<Text type='secondary' className='text-xs'>
{t('引导系数')}
</Text>
<Text type='secondary' className='text-xs'>
{params.guidanceScale.toFixed(1)}
</Text>
</div>
<Slider
value={params.guidanceScale}
onChange={(value) =>
updateParam('guidanceScale', value)
}
min={1}
max={20}
step={0.5}
/>
<div className='flex justify-between text-xs text-gray-500 dark:text-gray-400'>
<Text>{t('更自由')}</Text>
<Text>{t('更贴合提示')}</Text>
</div>
</div>
{/* 随机种子 */}
<div>
<div className='flex justify-between items-center mb-1'>
<div className='flex items-center'>
<Text type='secondary' className='text-xs mr-2'>
{t('使用随机种子')}
</Text>
<Switch
size='small'
checked={params.useSeed}
onChange={(checked) =>
updateParam('useSeed', checked)
}
/>
</div>
</div>
<InputNumber
value={params.seed}
onChange={(value) => updateParam('seed', value || null)}
disabled={!params.useSeed}
placeholder={t('输入种子值')}
className='w-full'
min={0}
max={Number.MAX_SAFE_INTEGER}
/>
<Text type='secondary' className='text-xs mt-1'>
{t('相同种子值将生成相似的图像')}
</Text>
</div>
</div>
</div>
),
isOpen: params.showAdvanced,
onItemClick: () =>
updateParam('showAdvanced', !params.showAdvanced),
},
]}
/>
<Divider className='my-4' />
{/* 操作按钮 */}
<div className='flex flex-col sm:flex-row gap-3'>
<Button
type='primary'
onClick={handleGenerate}
loading={isGenerating}
disabled={isGenerating || !params.prompt?.trim()}
icon={<Zap size={16} />}
className='flex-1'
>
{isGenerating ? t('生成中...') : t('生成图片')}
</Button>
<Button
type='tertiary'
onClick={clearAllParams}
disabled={isGenerating}
icon={<Trash2 size={16} />}
>
{t('清空')}
</Button>
</div>
{/* 提示信息 */}
<Alert
type='info'
showIcon
description={
<div className='text-xs'>
<Text type='secondary'>
{t(
'提示:详细的提示词能生成更符合您预期的图像。尝试描述场景、风格、光线、构图等元素。',
)}
</Text>
</div>
}
className='mt-4'
/>
</div>
</Card>
);
};
export default ImageGenerationParams;
-622
View File
@@ -1,622 +0,0 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useState, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import {
Card,
Empty,
Button,
Input,
Tag,
Space,
Modal,
Typography,
Collapse,
Spin,
Divider,
Popconfirm,
Dropdown,
Badge,
} from '@/components/ui';
import {
History,
Search,
Clock,
Image as ImageIcon,
Download,
Trash2,
MoreVertical,
X,
Filter,
} from 'lucide-react';
const { Title, Paragraph, Text } = Typography;
/**
* 图像生成历史记录组件
* @param {Object} props 组件属性
* @param {Array} props.history 历史记录数据
* @param {boolean} props.isLoading 是否正在加载
* @param {Function} props.onLoadFromHistory 从历史记录加载参数的回调
* @param {Function} props.onDeleteRecord 删除记录的回调
* @param {Function} props.onClearAll 清空所有历史记录的回调
* @param {Function} props.onRegenerate 重新生成图片的回调
*/
const ImageHistory = ({
history = [],
isLoading = false,
onLoadFromHistory,
onDeleteRecord,
onClearAll,
onRegenerate,
}) => {
const { t } = useTranslation();
// 状态管理
const [searchKeyword, setSearchKeyword] = useState('');
const [filteredHistory, setFilteredHistory] = useState([]);
const [showDetailModal, setShowDetailModal] = useState(false);
const [selectedRecord, setSelectedRecord] = useState(null);
const [sortOrder, setSortOrder] = useState('newest'); // 'newest' | 'oldest'
const [filterModel, setFilterModel] = useState('');
const [showFilters, setShowFilters] = useState(false);
// 获取所有模型列表
const allModels = useMemo(() => {
const modelsSet = new Set(
history.map((item) => item.model).filter(Boolean),
);
return Array.from(modelsSet).sort();
}, [history]);
// 过滤和排序历史记录
useMemo(() => {
let result = [...history];
// 应用搜索过滤
if (searchKeyword && searchKeyword.trim()) {
const keyword = searchKeyword.toLowerCase().trim();
result = result.filter(
(item) =>
item.prompt.toLowerCase().includes(keyword) ||
(item.negativePrompt &&
item.negativePrompt.toLowerCase().includes(keyword)) ||
item.model.toLowerCase().includes(keyword),
);
}
// 应用模型过滤
if (filterModel) {
result = result.filter((item) => item.model === filterModel);
}
// 应用排序
result.sort((a, b) => {
const dateA = new Date(a.timestamp);
const dateB = new Date(b.timestamp);
return sortOrder === 'newest' ? dateB - dateA : dateA - dateB;
});
setFilteredHistory(result);
}, [history, searchKeyword, filterModel, sortOrder]);
// 加载历史记录
const handleLoadFromHistory = useCallback(
(record) => {
if (onLoadFromHistory) {
onLoadFromHistory(record);
}
},
[onLoadFromHistory],
);
// 显示详情
const handleShowDetail = useCallback((record) => {
setSelectedRecord(record);
setShowDetailModal(true);
}, []);
// 删除单条记录
const handleDeleteRecord = useCallback(
(recordId) => {
if (onDeleteRecord) {
onDeleteRecord(recordId);
}
// 如果当前显示的是被删除的记录的详情,关闭详情模态框
if (selectedRecord && selectedRecord.id === recordId) {
setShowDetailModal(false);
setSelectedRecord(null);
}
},
[onDeleteRecord, selectedRecord],
);
// 重新生成图片
const handleRegenerate = useCallback(
(record) => {
if (onRegenerate) {
onRegenerate(record);
}
setShowDetailModal(false);
},
[onRegenerate],
);
// 清空所有历史记录
const handleClearAll = useCallback(() => {
if (onClearAll) {
onClearAll();
}
setShowDetailModal(false);
setSelectedRecord(null);
}, [onClearAll]);
// 切换排序顺序
const toggleSortOrder = useCallback(() => {
setSortOrder((prev) => (prev === 'newest' ? 'oldest' : 'newest'));
}, []);
// 重置过滤器
const resetFilters = useCallback(() => {
setSearchKeyword('');
setFilterModel('');
}, []);
// 格式化时间
const formatTime = useCallback((timestamp) => {
try {
const date = new Date(timestamp);
return date.toLocaleString();
} catch (error) {
return timestamp;
}
}, []);
// 获取模型厂商信息
const getVendorInfo = useCallback((modelValue) => {
const vendorMap = {
'dall-e-3': 'OpenAI',
'dall-e-2': 'OpenAI',
'gpt-image-1': 'OpenAI',
'imagen-3': 'Google',
'flux.1-schnell': 'Black Forest Labs',
'flux.1-dev': 'Black Forest Labs',
};
return vendorMap[modelValue] || 'Unknown';
}, []);
// 渲染历史记录项
const renderHistoryItem = useCallback(
(record) => {
return (
<Card
key={record.id}
className='cursor-pointer hover:shadow-md transition-all duration-200 mb-4'
>
<div className='p-4' onClick={() => handleShowDetail(record)}>
<div className='flex justify-between items-start mb-3'>
<div>
<div className='flex items-center'>
<Tag color='blue' className='mr-2'>
{getVendorInfo(record.model)}
</Tag>
<span className='font-medium text-sm'>{record.model}</span>
</div>
<div className='flex items-center mt-1'>
<Clock size={12} className='text-gray-400 mr-1' />
<span className='text-xs text-gray-500 dark:text-gray-400'>
{formatTime(record.timestamp)}
</span>
</div>
</div>
<div className='flex flex-col items-end'>
<span className='text-xs text-gray-500 dark:text-gray-400'>
{record.size}
</span>
<span className='text-xs text-gray-500 dark:text-gray-400'>
{record.images.length} {t('张图片')}
</span>
</div>
</div>
<Paragraph className='mb-3 text-sm line-clamp-2'>
{record.prompt}
</Paragraph>
<div className='grid grid-cols-4 gap-2'>
{record.images.slice(0, 4).map((img, idx) => (
<div
key={idx}
className='relative rounded overflow-hidden aspect-square bg-gray-100 dark:bg-gray-800'
>
<img
src={img.url}
alt={`Generated ${idx}`}
className='w-full h-full object-cover'
loading='lazy'
/>
{record.images.length > 4 && idx === 3 && (
<div className='absolute inset-0 bg-black bg-opacity-50 flex items-center justify-center'>
<span className='text-white text-xs'>
+{record.images.length - 4}
</span>
</div>
)}
</div>
))}
</div>
</div>
<div className='absolute top-2 right-2 z-10'>
<Dropdown
render={
<Space className='bg-white dark:bg-gray-800 shadow-lg rounded p-2'>
<Button
type='tertiary'
size='small'
className='w-full justify-start'
onClick={() => {
handleLoadFromHistory(record);
}}
>
{t('加载参数')}
</Button>
<Button
type='tertiary'
size='small'
className='w-full justify-start'
onClick={() => handleRegenerate(record)}
>
{t('重新生成')}
</Button>
<Divider className='my-1' />
<Popconfirm
title={t('确认删除')}
content={t('确定要删除这条历史记录吗?')}
onConfirm={() => handleDeleteRecord(record.id)}
okText={t('确认')}
cancelText={t('取消')}
>
<Button
type='tertiary'
size='small'
danger
className='w-full justify-start'
>
{t('删除')}
</Button>
</Popconfirm>
</Space>
}
>
<Button type='text' size='small' className='hover:bg-transparent'>
<MoreVertical size={16} />
</Button>
</Dropdown>
</div>
</Card>
);
},
[
handleShowDetail,
handleLoadFromHistory,
handleRegenerate,
handleDeleteRecord,
getVendorInfo,
formatTime,
t,
],
);
// 渲染详情模态框
const renderDetailModal = () => {
if (!selectedRecord) return null;
return (
<Modal
title={t('历史记录详情')}
visible={showDetailModal}
onCancel={() => setShowDetailModal(false)}
width={800}
footer={[
<Button
key='regenerate'
type='primary'
onClick={() => handleRegenerate(selectedRecord)}
>
{t('重新生成')}
</Button>,
<Button
key='load'
onClick={() => handleLoadFromHistory(selectedRecord)}
>
{t('加载参数')}
</Button>,
<Button key='close' onClick={() => setShowDetailModal(false)}>
{t('关闭')}
</Button>,
]}
>
<div className='space-y-4'>
{/* 基本信息 */}
<div>
<Title level={5} className='mb-2'>
{t('基本信息')}
</Title>
<div className='grid grid-cols-2 gap-4'>
<div>
<Text type='secondary' className='text-xs mb-1'>
{t('模型')}
</Text>
<div className='flex items-center'>
<Tag color='blue' className='mr-2'>
{getVendorInfo(selectedRecord.model)}
</Tag>
<Text>{selectedRecord.model}</Text>
</div>
</div>
<div>
<Text type='secondary' className='text-xs mb-1'>
{t('生成时间')}
</Text>
<div className='flex items-center'>
<Clock size={14} className='text-gray-400 mr-1' />
<Text>{formatTime(selectedRecord.timestamp)}</Text>
</div>
</div>
<div>
<Text type='secondary' className='text-xs mb-1'>
{t('图片尺寸')}
</Text>
<div className='flex items-center'>
<ImageIcon size={14} className='text-gray-400 mr-1' />
<Text>{selectedRecord.size}</Text>
</div>
</div>
<div>
<Text type='secondary' className='text-xs mb-1'>
{t('图片质量')}
</Text>
<Text>
{selectedRecord.quality === 'hd' ? t('高清') : t('标准')}
</Text>
</div>
</div>
</div>
<Divider />
{/* 提示词 */}
<div>
<Title level={5} className='mb-2'>
{t('提示词')}
</Title>
<Card className='bg-gray-50 dark:bg-gray-800/50'>
<Paragraph className='mb-0'>{selectedRecord.prompt}</Paragraph>
</Card>
</div>
{/* 反向提示词 */}
{selectedRecord.negativePrompt && (
<div>
<Title level={5} className='mb-2'>
{t('反向提示词')}
</Title>
<Card className='bg-gray-50 dark:bg-gray-800/50'>
<Paragraph className='mb-0'>
{selectedRecord.negativePrompt}
</Paragraph>
</Card>
</div>
)}
<Divider />
{/* 生成的图片 */}
<div>
<Title level={5} className='mb-2'>
{t('生成结果')}
</Title>
<div className='grid grid-cols-1 sm:grid-cols-2 gap-4'>
{selectedRecord.images.map((img, idx) => (
<Card key={idx} className='overflow-hidden'>
<div className='aspect-square relative'>
<img
src={img.url}
alt={`Generated ${idx + 1}`}
className='w-full h-full object-contain bg-white dark:bg-gray-800'
/>
<Button
size='small'
type='primary'
circle
icon={<Download size={14} />}
className='absolute bottom-2 right-2 bg-white/90 hover:bg-white text-black'
onClick={() => {
const link = document.createElement('a');
link.href = img.url;
link.download = `history-image-${selectedRecord.id}-${idx}.png`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}}
/>
</div>
</Card>
))}
</div>
</div>
</div>
</Modal>
);
};
return (
<div className='space-y-4'>
{/* 标题和操作栏 */}
<div className='flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4'>
<div className='flex items-center'>
<History className='h-5 w-5 text-blue-600 dark:text-blue-400 mr-2' />
<Title level={4} className='mb-0'>
{t('生成历史')}
{filteredHistory.length > 0 && (
<Badge count={filteredHistory.length} className='ml-2' />
)}
</Title>
</div>
<div className='flex flex-wrap gap-2 w-full sm:w-auto'>
<Button
type='tertiary'
size='small'
icon={<Filter size={16} />}
onClick={() => setShowFilters(!showFilters)}
>
{t('筛选')}
</Button>
<Button
type='tertiary'
size='small'
icon={<Clock size={16} />}
onClick={toggleSortOrder}
>
{sortOrder === 'newest' ? t('最新优先') : t('最早优先')}
</Button>
<Popconfirm
title={t('确认清空')}
content={t('确定要清空所有历史记录吗?此操作不可恢复。')}
onConfirm={handleClearAll}
okText={t('确认')}
cancelText={t('取消')}
>
<Button
type='tertiary'
size='small'
danger
icon={<Trash2 size={16} />}
disabled={history.length === 0}
>
{t('清空全部')}
</Button>
</Popconfirm>
</div>
</div>
{/* 搜索框 */}
<div className='space-y-3'>
<Input
value={searchKeyword}
onChange={(e) => setSearchKeyword(e.target.value)}
placeholder={t('搜索提示词、反向提示词或模型...')}
prefix={<Search size={16} />}
allowClear
className='w-full'
/>
{/* 高级筛选 */}
<Collapse
items={[
{
title: t('高级筛选'),
content: (
<div className='space-y-3 p-2'>
<div>
<Text type='secondary' className='text-xs mb-1'>
{t('按模型筛选')}
</Text>
<div className='flex flex-wrap gap-2'>
<Tag
color={filterModel === '' ? 'blue' : 'gray'}
clickable
onClick={() => setFilterModel('')}
>
{t('全部')}
</Tag>
{allModels.map((model) => (
<Tag
key={model}
color={filterModel === model ? 'blue' : 'gray'}
clickable
onClick={() => setFilterModel(model)}
>
{model}
</Tag>
))}
</div>
</div>
{filterModel || searchKeyword ? (
<Button
type='text'
size='small'
onClick={resetFilters}
icon={<X size={14} />}
>
{t('重置筛选')}
</Button>
) : null}
</div>
),
isOpen: showFilters,
},
]}
/>
</div>
{/* 历史记录列表 */}
<div className='space-y-4'>
{isLoading ? (
<div className='py-16 flex justify-center'>
<Spin size='large' />
</div>
) : filteredHistory.length > 0 ? (
filteredHistory.map((record) => renderHistoryItem(record))
) : (
<Card className='text-center py-16'>
<Empty
description={
searchKeyword || filterModel
? t('没有找到匹配的历史记录')
: t('暂无历史记录')
}
>
{searchKeyword || filterModel ? (
<Button type='primary' size='small' onClick={resetFilters}>
{t('清除筛选条件')}
</Button>
) : (
<Text type='secondary' className='mt-2'>
{t('生成图片后,历史记录将显示在这里')}
</Text>
)}
</Empty>
</Card>
)}
</div>
{/* 详情模态框 */}
{renderDetailModal()}
</div>
);
};
export default ImageHistory;
-457
View File
@@ -1,457 +0,0 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import {
Spin,
Progress,
Alert,
Button,
Typography,
Card,
Empty,
Space,
} from '@/components/ui';
import {
Loading3,
AlertCircle,
CheckCircle,
Clock,
Image as ImageIcon,
FileQuestion,
Wifi,
CreditCard,
AlertTriangle,
Sparkles,
} from 'lucide-react';
const { Title, Text, Paragraph } = Typography;
/**
* 图片状态显示组件
* 用于展示图片生成过程中的加载、错误和成功状态
* @param {Object} props 组件属性
*/
const ImageStatusDisplay = ({
isLoading = false,
loadingStage = 'idle',
progress = 0,
error = null,
successMessage = '',
onRetry,
onBack,
onAction,
detailMode = false,
}) => {
const { t } = useTranslation();
// 根据加载阶段获取图标和描述
const loadingInfo = useMemo(() => {
const stageInfo = {
idle: {
icon: <Loading3 className='animate-spin' size={detailMode ? 48 : 24} />,
title: t('准备中'),
description: t('正在初始化...'),
},
processing: {
icon: (
<Sparkles className='animate-pulse' size={detailMode ? 48 : 24} />
),
title: t('处理提示词'),
description: t('正在分析您的提示词...'),
},
generating: {
icon: (
<ImageIcon
className='animate-spin-slow'
size={detailMode ? 48 : 24}
/>
),
title: t('生成图像'),
description: t('AI正在绘制图像...'),
},
completing: {
icon: <Loading3 className='animate-spin' size={detailMode ? 48 : 24} />,
title: t('优化质量'),
description: t('正在优化图片细节...'),
},
};
return stageInfo[loadingStage] || stageInfo.idle;
}, [loadingStage, detailMode, t]);
// 根据错误类型获取图标和建议
const errorInfo = useMemo(() => {
if (!error) return null;
const typeInfo = {
network: {
icon: <Wifi size={detailMode ? 48 : 24} />,
title: t('网络错误'),
action: t('重试连接'),
},
validation: {
icon: <AlertTriangle size={detailMode ? 48 : 24} />,
title: t('参数错误'),
action: t('修改参数'),
},
api: {
icon: <FileQuestion size={detailMode ? 48 : 24} />,
title: t('API错误'),
action: t('查看详情'),
},
rate_limit: {
icon: <Clock size={detailMode ? 48 : 24} />,
title: t('请求限制'),
action: t('稍后重试'),
},
credit: {
icon: <CreditCard size={detailMode ? 48 : 24} />,
title: t('余额不足'),
action: t('去充值'),
},
unknown: {
icon: <AlertCircle size={detailMode ? 48 : 24} />,
title: t('未知错误'),
action: t('联系支持'),
},
};
return typeInfo[error.type] || typeInfo.unknown;
}, [error, detailMode, t]);
// 渲染加载状态
const renderLoading = () => {
if (!isLoading) return null;
if (detailMode) {
return (
<Card className='text-center p-8'>
<div className='mb-6 flex justify-center'>
<div className='p-4 rounded-full bg-blue-50 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400'>
{loadingInfo.icon}
</div>
</div>
<Title level={4} className='mb-2'>
{loadingInfo.title}
</Title>
<Paragraph className='text-gray-500 dark:text-gray-400 mb-6'>
{loadingInfo.description}
</Paragraph>
<Progress
percent={progress}
strokeWidth={8}
status='active'
showText={false}
format={() => `${progress}%`}
className='mb-2'
/>
<Text type='secondary' className='text-xs'>
{`${t('进度')}: ${progress}%`}
</Text>
</Card>
);
}
return (
<div className='flex items-center justify-center p-4'>
<Space size='large' align='center'>
<Spin size='large' />
<div className='text-center'>
<div className='font-medium mb-1'>{loadingInfo.title}</div>
<div className='text-sm text-gray-500 dark:text-gray-400'>
{loadingInfo.description}
</div>
</div>
</Space>
</div>
);
};
// 渲染错误状态
const renderError = () => {
if (!error) return null;
const errorAction = () => {
if (error.type === 'network' || error.type === 'rate_limit') {
onRetry?.();
} else if (onAction) {
onAction(error.type, error);
}
};
if (detailMode) {
return (
<Card className='text-center p-8 bg-red-50/30 dark:bg-red-900/10'>
<div className='mb-6 flex justify-center'>
<div className='p-4 rounded-full bg-red-50 dark:bg-red-900/30 text-red-600 dark:text-red-400'>
{errorInfo.icon}
</div>
</div>
<Title level={4} className='mb-2'>
{errorInfo.title}
</Title>
<Paragraph className='text-gray-700 dark:text-gray-300 mb-6'>
{error.message}
</Paragraph>
{error.details && (
<div className='mb-6 bg-white dark:bg-gray-800 p-4 rounded-md text-left'>
<Text type='secondary' className='text-xs mb-2'>
{t('错误详情')}
</Text>
<Text className='text-xs whitespace-pre-wrap'>
{JSON.stringify(error.details, null, 2)}
</Text>
</div>
)}
<Space className='justify-center'>
<Button type='primary' onClick={errorAction}>
{errorInfo.action}
</Button>
{onBack && <Button onClick={onBack}>{t('返回')}</Button>}
</Space>
</Card>
);
}
return (
<Alert
type='error'
message={errorInfo.title}
description={error.message}
action={
<Button size='small' type='tertiary' onClick={errorAction}>
{errorInfo.action}
</Button>
}
className='my-4'
/>
);
};
// 渲染成功状态
const renderSuccess = () => {
if (isLoading || error || !successMessage) return null;
if (detailMode) {
return (
<Card className='text-center p-8 bg-green-50/30 dark:bg-green-900/10'>
<div className='mb-6 flex justify-center'>
<div className='p-4 rounded-full bg-green-50 dark:bg-green-900/30 text-green-600 dark:text-green-400'>
<CheckCircle size={detailMode ? 48 : 24} />
</div>
</div>
<Title level={4} className='mb-2'>
{t('成功')}
</Title>
<Paragraph className='text-gray-700 dark:text-gray-300 mb-6'>
{successMessage}
</Paragraph>
{onBack && <Button onClick={onBack}>{t('返回')}</Button>}
</Card>
);
}
return (
<Alert
type='success'
message={t('成功')}
description={successMessage}
showIcon
className='my-4'
/>
);
};
// 渲染空状态
const renderEmpty = () => {
if (isLoading || error || successMessage) return null;
return (
<Card className='text-center p-8'>
<Empty
description={
<Text type='secondary'>{t('请输入提示词并开始生成图片')}</Text>
}
/>
</Card>
);
};
// 如果在详情模式下,显示完整的状态卡片
if (detailMode) {
return (
<div className='animate-fade-in'>
{renderLoading()}
{renderError()}
{renderSuccess()}
{renderEmpty()}
</div>
);
}
// 非详情模式下,显示紧凑的状态信息
return (
<div className='space-y-4'>
{renderLoading()}
{renderError()}
{renderSuccess()}
{renderEmpty()}
</div>
);
};
/**
* 图片生成进度条组件
* 用于显示更详细的生成进度
*/
export const ImageProgressBar = ({ stage, progress }) => {
const { t } = useTranslation();
const stages = [
{ key: 'idle', label: t('准备'), icon: <Loading3 size={14} /> },
{ key: 'processing', label: t('处理'), icon: <Sparkles size={14} /> },
{ key: 'generating', label: t('生成'), icon: <ImageIcon size={14} /> },
{ key: 'completing', label: t('完成'), icon: <CheckCircle size={14} /> },
];
const currentStageIndex = stages.findIndex((s) => s.key === stage);
return (
<div className='bg-gray-100 dark:bg-gray-800 rounded-lg p-4'>
<Text type='secondary' className='text-xs mb-2'>
{t('生成进度')}
</Text>
<Progress
percent={progress}
strokeWidth={6}
status='active'
format={() => ''}
className='mb-4'
/>
<div className='flex items-center justify-between'>
{stages.map((s, index) => {
const isActive = index <= currentStageIndex;
const isLast = index === stages.length - 1;
return (
<React.Fragment key={s.key}>
<div
className={`flex flex-col items-center ${isActive ? 'text-blue-600 dark:text-blue-400' : 'text-gray-400'}`}
>
<div
className={`w-7 h-7 flex items-center justify-center rounded-full mb-1 ${isActive ? 'bg-blue-100 dark:bg-blue-900/40' : 'bg-gray-200 dark:bg-gray-700'}`}
>
{s.icon}
</div>
<Text className='text-xs whitespace-nowrap'>{s.label}</Text>
</div>
{!isLast && (
<div
className={`flex-1 mx-1 h-1 ${isActive ? 'bg-blue-600 dark:bg-blue-400' : 'bg-gray-300 dark:bg-gray-700'}`}
/>
)}
</React.Fragment>
);
})}
</div>
</div>
);
};
/**
* 图片生成通知组件
*/
export const ImageNotification = ({ notification, onClose }) => {
if (!notification) return null;
const getTypeProps = (type) => {
switch (type) {
case 'success':
return {
icon: <CheckCircle size={16} className='text-green-500' />,
bg: 'bg-green-50 dark:bg-green-900/20',
border: 'border-green-100 dark:border-green-800',
};
case 'error':
return {
icon: <AlertCircle size={16} className='text-red-500' />,
bg: 'bg-red-50 dark:bg-red-900/20',
border: 'border-red-100 dark:border-red-800',
};
case 'warning':
return {
icon: <AlertTriangle size={16} className='text-yellow-500' />,
bg: 'bg-yellow-50 dark:bg-yellow-900/20',
border: 'border-yellow-100 dark:border-yellow-800',
};
default:
return {
icon: <AlertCircle size={16} className='text-blue-500' />,
bg: 'bg-blue-50 dark:bg-blue-900/20',
border: 'border-blue-100 dark:border-blue-800',
};
}
};
const typeProps = getTypeProps(notification.type);
return (
<div
className={`fixed top-4 right-4 z-50 w-80 animate-slide-in-right ${typeProps.bg} border ${typeProps.border} rounded-lg p-4 shadow-lg`}
>
<div className='flex items-start justify-between'>
<div className='flex items-center'>
{typeProps.icon}
<Text className='ml-2 text-sm'>{notification.message}</Text>
</div>
<Button type='text' size='small' className='ml-2' onClick={onClose}>
<X size={14} />
</Button>
</div>
<div className='mt-2 h-1 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden'>
<div
className='h-full bg-gray-400 dark:bg-gray-500'
style={{
width: `${100 - (notification.duration * (Date.now() - notification.id)) / 1000}%`,
transition: 'width 10ms linear',
}}
/>
</div>
</div>
);
};
export default ImageStatusDisplay;
+1 -4
View File
@@ -114,10 +114,7 @@ const PageLayout = () => {
// 企业管理页面有自己的布局和滚动控制。 // 企业管理页面有自己的布局和滚动控制。
// 注意排除 /org/login、/org/register、/org/:slug/login 等认证页—— // 注意排除 /org/login、/org/register、/org/:slug/login 等认证页——
// 它们没有内部滚动容器,若被禁用外层滚动,内容超出视口(如企业注册开启邮箱验证时)会被截断且无法滚动。 // 它们没有内部滚动容器,若被禁用外层滚动,内容超出视口(如企业注册开启邮箱验证时)会被截断且无法滚动。
const isOrgPage = const isOrgPage = location.pathname.startsWith('/org') && !isAuthPage;
location.pathname.startsWith('/org') &&
location.pathname !== '/org/create' &&
!isAuthPage;
// 需要禁用外层滚动的页面(这些页面内部有自己的滚动容器) // 需要禁用外层滚动的页面(这些页面内部有自己的滚动容器)
const disableOuterScroll = const disableOuterScroll =
+8
View File
@@ -28,6 +28,10 @@ import { useSidebarCollapsed } from '../../hooks/common/useSidebarCollapsed';
import { useSidebar } from '../../hooks/common/useSidebar'; import { useSidebar } from '../../hooks/common/useSidebar';
import { useMinimumLoadingTime } from '../../hooks/common/useMinimumLoadingTime'; import { useMinimumLoadingTime } from '../../hooks/common/useMinimumLoadingTime';
import { isAdmin, isRoot, showError } from '../../helpers'; import { isAdmin, isRoot, showError } from '../../helpers';
import {
isMiniProgramPaymentPath,
isMiniProgramWebView,
} from '../../helpers/miniProgram';
import { StatusContext } from '../../context/Status'; import { StatusContext } from '../../context/Status';
import { UserContext } from '../../context/User'; import { UserContext } from '../../context/User';
import { import {
@@ -152,6 +156,10 @@ const SiderBar = ({ onNavigate = () => {}, forceExpanded = false }) => {
// 根据配置过滤项目 // 根据配置过滤项目
const filteredItems = items.filter((item) => { const filteredItems = items.filter((item) => {
const configVisible = isModuleVisible('personal', item.itemKey); const configVisible = isModuleVisible('personal', item.itemKey);
// WeyAi 小程序里不出现付费入口(helpers/miniProgram.js)。
if (isMiniProgramWebView() && isMiniProgramPaymentPath(item.to)) {
return false;
}
return configVisible; return configVisible;
}); });
@@ -19,6 +19,7 @@ For commercial licensing, please contact support@quantumnous.com
import React, { useState, useContext } from 'react'; import React, { useState, useContext } from 'react';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import { isMiniProgramWebView } from '../../../helpers/miniProgram';
import { Button as AntButton, Divider, Tooltip } from 'antd'; import { Button as AntButton, Divider, Tooltip } from 'antd';
import { Share2, BookOpen, Download, Wallet } from 'lucide-react'; import { Share2, BookOpen, Download, Wallet } from 'lucide-react';
import NewYearButton from './NewYearButton'; import NewYearButton from './NewYearButton';
@@ -184,7 +185,7 @@ const ActionButtons = ({
)} )}
{/* Recharge Button - 充值按钮 */} {/* Recharge Button - 充值按钮 */}
{isButtonVisible('recharge') && ( {isButtonVisible('recharge') && !isMiniProgramWebView() && (
<Link to='/recharge'> <Link to='/recharge'>
<AntButton <AntButton
icon={actionIcon(Wallet)} icon={actionIcon(Wallet)}
@@ -26,6 +26,7 @@ import React, {
} from 'react'; } from 'react';
import { Empty as AntEmpty, Tag as AntTag } from 'antd'; import { Empty as AntEmpty, Tag as AntTag } from 'antd';
import { Modal, Table, Typography, Pagination, Toast } from '@/components/ui'; import { Modal, Table, Typography, Pagination, Toast } from '@/components/ui';
import i18next from 'i18next';
import { API, renderQuota } from '../../helpers'; import { API, renderQuota } from '../../helpers';
const { Text } = Typography; const { Text } = Typography;
@@ -67,7 +68,7 @@ export const MembershipHistoryContent = ({ visible, t, inline = false }) => {
// 格式化时间戳为日期字符串(使用 useCallback 避免每次渲染都创建新函数) // 格式化时间戳为日期字符串(使用 useCallback 避免每次渲染都创建新函数)
const formatDate = useCallback((timestamp) => { const formatDate = useCallback((timestamp) => {
if (!timestamp) return '-'; if (!timestamp) return '-';
return new Date(timestamp * 1000).toLocaleDateString('zh-CN', { return new Date(timestamp * 1000).toLocaleDateString(i18next.language, {
year: 'numeric', year: 'numeric',
month: '2-digit', month: '2-digit',
day: '2-digit', day: '2-digit',
@@ -77,7 +78,7 @@ export const MembershipHistoryContent = ({ visible, t, inline = false }) => {
// 格式化时间戳为完整时间字符串 // 格式化时间戳为完整时间字符串
const formatDateTime = useCallback((timestamp) => { const formatDateTime = useCallback((timestamp) => {
if (!timestamp) return '-'; if (!timestamp) return '-';
return new Date(timestamp * 1000).toLocaleString('zh-CN', { return new Date(timestamp * 1000).toLocaleString(i18next.language, {
year: 'numeric', year: 'numeric',
month: '2-digit', month: '2-digit',
day: '2-digit', day: '2-digit',
@@ -172,8 +173,10 @@ export const MembershipHistoryContent = ({ visible, t, inline = false }) => {
<div> <div>
<Text>{text || '-'}</Text> <Text>{text || '-'}</Text>
<Text type='tertiary' size='small' className='block'> <Text type='tertiary' size='small' className='block'>
{PLAN_TYPE_MAP[record.plan_type] || record.plan_type} ·{' '} {PLAN_TYPE_MAP[record.plan_type]
{TIER_MAP[record.tier] || record.tier} ? t(PLAN_TYPE_MAP[record.plan_type])
: record.plan_type}{' '}
· {TIER_MAP[record.tier] ? t(TIER_MAP[record.tier]) : record.tier}
</Text> </Text>
</div> </div>
), ),
@@ -196,7 +199,7 @@ export const MembershipHistoryContent = ({ visible, t, inline = false }) => {
record.end_date && record.start_date record.end_date && record.start_date
? Math.round((record.end_date - record.start_date) / 86400) ? Math.round((record.end_date - record.start_date) / 86400)
: '-'; : '-';
return `${days} ${t('天')}`; return t('{{days}} 天', { days });
}, },
}, },
{ {
+3 -3
View File
@@ -58,7 +58,7 @@ const ConfigManager = ({
}); });
} catch (error) { } catch (error) {
Toast.error({ Toast.error({
content: t('导出配置失败: ') + error.message, content: t('导出配置失败: {{error}}', { error: error.message }),
duration: 3, duration: 3,
}); });
} }
@@ -90,7 +90,7 @@ const ConfigManager = ({
}); });
} catch (error) { } catch (error) {
Toast.error({ Toast.error({
content: t('导入配置失败: ') + error.message, content: t('导入配置失败: {{error}}', { error: error.message }),
duration: 3, duration: 3,
}); });
} finally { } finally {
@@ -148,7 +148,7 @@ const ConfigManager = ({
const timestamp = getConfigTimestamp(); const timestamp = getConfigTimestamp();
if (timestamp) { if (timestamp) {
const date = new Date(timestamp); const date = new Date(timestamp);
return t('上次保存: ') + date.toLocaleString(); return t('上次保存: {{time}}', { time: date.toLocaleString() });
} }
return t('已有保存的配置'); return t('已有保存的配置');
} }
+3 -1
View File
@@ -489,7 +489,9 @@ const MessageContent = ({
className='text-red-500 text-sm p-2 bg-red-50 rounded-lg border border-red-200' className='text-red-500 text-sm p-2 bg-red-50 rounded-lg border border-red-200'
style={{ display: 'none' }} style={{ display: 'none' }}
> >
图片加载失败: {imgItem.image_url.url} {t('图片加载失败: {{url}}', {
url: imgItem.image_url.url,
})}
</div> </div>
</div> </div>
); );
+1 -1
View File
@@ -222,7 +222,7 @@ const SSEViewer = ({ sseData }) => {
<Typography.Text strong>{t('SSE数据流')}</Typography.Text> <Typography.Text strong>{t('SSE数据流')}</Typography.Text>
<Badge count={stats.total} type='primary' /> <Badge count={stats.total} type='primary' />
{stats.errors > 0 && ( {stats.errors > 0 && (
<Badge count={`${stats.errors} ${t('错误')}`} type='danger' /> <Badge count={t('{{n}} 个错误', { n: stats.errors, count: stats.errors })} type='danger' />
)} )}
</div> </div>
@@ -105,7 +105,7 @@ const ThinkingContent = ({
style={{ color: 'white' }} style={{ color: 'white' }}
className='text-xs mt-0.5 opacity-80 hidden sm:block' className='text-xs mt-0.5 opacity-80 hidden sm:block'
> >
来源: {thinkingSource} {t('来源: {{source}}', { source: thinkingSource })}
</Typography.Text> </Typography.Text>
)} )}
</div> </div>
+15 -4
View File
@@ -17,6 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import i18next from 'i18next';
import { DEFAULT_CONFIG } from '../../constants/playground.constants'; import { DEFAULT_CONFIG } from '../../constants/playground.constants';
// 存储键前缀 // 存储键前缀
@@ -257,16 +258,26 @@ export const importConfig = (file) => {
resolve(importedConfig); resolve(importedConfig);
} else { } else {
reject(new Error('配置文件格式无效')); reject(new Error(i18next.t('配置文件格式无效')));
} }
} catch (parseError) { } catch (parseError) {
reject(new Error('解析配置文件失败: ' + parseError.message)); reject(
new Error(
i18next.t('解析配置文件失败: {{error}}', {
error: parseError.message,
}),
),
);
} }
}; };
reader.onerror = () => reject(new Error('读取文件失败')); reader.onerror = () => reject(new Error(i18next.t('读取文件失败')));
reader.readAsText(file); reader.readAsText(file);
} catch (error) { } catch (error) {
reject(new Error('导入配置失败: ' + error.message)); reject(
new Error(
i18next.t('导入配置失败: {{error}}', { error: error.message }),
),
);
} }
}); });
}; };
@@ -275,7 +275,7 @@ const PromotionPosterModal = ({ visible, onClose }) => {
link.click(); link.click();
showSuccess(t('海报下载成功')); showSuccess(t('海报下载成功'));
} catch (error) { } catch (error) {
showError(t('下载失败') + ': ' + error.message); showError(t('下载失败: {{error}}', { error: error.message }));
} finally { } finally {
setDownloading(false); setDownloading(false);
} }
@@ -458,7 +458,7 @@ const PromotionPosterModal = ({ visible, onClose }) => {
: 'border-transparent hover:border-gray-300 hover:scale-105' : 'border-transparent hover:border-gray-300 hover:scale-105'
}`} }`}
style={{ background: template.bgGradient }} style={{ background: template.bgGradient }}
title={template.name} title={t(template.name)}
> >
{selectedTemplate.id === template.id && ( {selectedTemplate.id === template.id && (
<div className='absolute inset-0 flex items-center justify-center bg-black/20'> <div className='absolute inset-0 flex items-center justify-center bg-black/20'>
+1 -1
View File
@@ -148,7 +148,7 @@ export const DEGRADE_TEXT = {
export const qualityErrorText = (t, message) => { export const qualityErrorText = (t, message) => {
const key = QUALITY_ERROR_TEXT[message]; const key = QUALITY_ERROR_TEXT[message];
if (key) return t(key); if (key) return t(key);
if (message && /[一-鿿]/.test(message)) return message; if (message && /[一-鿿]/.test(message)) return t(message);
return t('查询失败,请稍后重试'); return t('查询失败,请稍后重试');
}; };
+3 -1
View File
@@ -19,10 +19,12 @@ For commercial licensing, please contact support@quantumnous.com
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { Card, Spin } from '@/components/ui'; import { Card, Spin } from '@/components/ui';
import { useTranslation } from 'react-i18next';
import SettingsChats from '../../pages/Setting/Chat/SettingsChats'; import SettingsChats from '../../pages/Setting/Chat/SettingsChats';
import { API, showError, toBoolean } from '../../helpers'; import { API, showError, toBoolean } from '../../helpers';
const ChatsSetting = () => { const ChatsSetting = () => {
const { t } = useTranslation();
let [inputs, setInputs] = useState({ let [inputs, setInputs] = useState({
/* 聊天设置 */ /* 聊天设置 */
Chats: '[]', Chats: '[]',
@@ -57,7 +59,7 @@ const ChatsSetting = () => {
setLoading(true); setLoading(true);
await getOptions(); await getOptions();
} catch (error) { } catch (error) {
showError('刷新失败'); showError(t('刷新失败'));
} finally { } finally {
setLoading(false); setLoading(false);
} }
@@ -43,6 +43,7 @@ import {
import { RefreshCw, Save, ShieldAlert, TestTube2 } from 'lucide-react'; import { RefreshCw, Save, ShieldAlert, TestTube2 } from 'lucide-react';
import { API, showError, showSuccess } from '../../helpers'; import { API, showError, showSuccess } from '../../helpers';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import i18next from 'i18next';
import { import {
ENFORCE_CHECK_FIELDS, ENFORCE_CHECK_FIELDS,
normalizeContentGuardConfig, normalizeContentGuardConfig,
@@ -81,7 +82,7 @@ const DEFAULT_CONFIG = {
}; };
const errorMessage = (error) => const errorMessage = (error) =>
error?.response?.data?.message || error?.message || '请求失败'; error?.response?.data?.message || error?.message || i18next.t('请求失败');
const statusTag = (config, t) => { const statusTag = (config, t) => {
if (config.lifecycle_state === 'decommissioned') { if (config.lifecycle_state === 'decommissioned') {
@@ -351,7 +352,7 @@ export default function ContentGuardSetting() {
value === '合规' ? 'green' : value === '违规' ? 'red' : 'orange' value === '合规' ? 'green' : value === '违规' ? 'red' : 'orange'
} }
> >
{value || '-'} {value ? t(value) : '-'}
</Tag> </Tag>
), ),
}, },
+12 -10
View File
@@ -107,6 +107,8 @@ const parseChangePayload = (payload) => {
export default function DataSecuritySetting() { export default function DataSecuritySetting() {
const { t } = useTranslation(); const { t } = useTranslation();
const tOptions = (options) =>
options.map((o) => ({ ...o, label: t(o.label) }));
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
// 初始值须与后端默认一致(setting/desensitize.go),否则 loadConfig 失败时 // 初始值须与后端默认一致(setting/desensitize.go),否则 loadConfig 失败时
// 页面展示的是不真实的状态、点保存还会把这些值写进去。 // 页面展示的是不真实的状态、点保存还会把这些值写进去。
@@ -571,7 +573,7 @@ export default function DataSecuritySetting() {
? t('开启') ? t('开启')
: t('关闭') : t('关闭')
: inherited || '-'; : inherited || '-';
return `${t('继承')}(${inheritedText})`; return t('继承({{value}})', { value: inheritedText });
} }
if (field === 'anti_evasion') { if (field === 'anti_evasion') {
return String(value) === 'true' ? t('开启') : t('关闭'); return String(value) === 'true' ? t('开启') : t('关闭');
@@ -726,7 +728,7 @@ export default function DataSecuritySetting() {
<Form.Select <Form.Select
field='mode' field='mode'
label={t('工作模式')} label={t('工作模式')}
optionList={MODE_OPTIONS} optionList={tOptions(MODE_OPTIONS)}
initValue={config.mode} initValue={config.mode}
onChange={(v) => setConfig({ ...config, mode: v })} onChange={(v) => setConfig({ ...config, mode: v })}
style={{ width: 360 }} style={{ width: 360 }}
@@ -734,7 +736,7 @@ export default function DataSecuritySetting() {
<Form.Select <Form.Select
field='failure_strategy' field='failure_strategy'
label={t('失败策略')} label={t('失败策略')}
optionList={FAILURE_OPTIONS} optionList={tOptions(FAILURE_OPTIONS)}
initValue={config.failure_strategy} initValue={config.failure_strategy}
onChange={(v) => setConfig({ ...config, failure_strategy: v })} onChange={(v) => setConfig({ ...config, failure_strategy: v })}
style={{ width: 360 }} style={{ width: 360 }}
@@ -742,7 +744,7 @@ export default function DataSecuritySetting() {
<Form.Select <Form.Select
field='multimodal_strategy' field='multimodal_strategy'
label={t('多模态请求策略')} label={t('多模态请求策略')}
optionList={MULTIMODAL_OPTIONS} optionList={tOptions(MULTIMODAL_OPTIONS)}
initValue={config.multimodal_strategy} initValue={config.multimodal_strategy}
onChange={(v) => onChange={(v) =>
setConfig({ ...config, multimodal_strategy: v }) setConfig({ ...config, multimodal_strategy: v })
@@ -752,7 +754,7 @@ export default function DataSecuritySetting() {
<Form.Select <Form.Select
field='sensitive_strategy' field='sensitive_strategy'
label={t('敏感 PII 策略')} label={t('敏感 PII 策略')}
optionList={SENSITIVE_OPTIONS} optionList={tOptions(SENSITIVE_OPTIONS)}
initValue={config.sensitive_strategy} initValue={config.sensitive_strategy}
onChange={(v) => onChange={(v) =>
setConfig({ ...config, sensitive_strategy: v }) setConfig({ ...config, sensitive_strategy: v })
@@ -1292,7 +1294,7 @@ export default function DataSecuritySetting() {
<Form.Select <Form.Select
field='pii_level' field='pii_level'
label={t('PII 分级')} label={t('PII 分级')}
optionList={PII_LEVEL_OPTIONS} optionList={tOptions(PII_LEVEL_OPTIONS)}
style={{ width: '100%' }} style={{ width: '100%' }}
/> />
<Form.Switch field='enabled' label={t('启用')} /> <Form.Switch field='enabled' label={t('启用')} />
@@ -1327,7 +1329,7 @@ export default function DataSecuritySetting() {
<Form.Select.Option value=''>{t('继承全局')}</Form.Select.Option> <Form.Select.Option value=''>{t('继承全局')}</Form.Select.Option>
{MODE_OPTIONS.map((o) => ( {MODE_OPTIONS.map((o) => (
<Form.Select.Option key={o.value} value={o.value}> <Form.Select.Option key={o.value} value={o.value}>
{o.label} {t(o.label)}
</Form.Select.Option> </Form.Select.Option>
))} ))}
</Form.Select> </Form.Select>
@@ -1339,7 +1341,7 @@ export default function DataSecuritySetting() {
<Form.Select.Option value=''>{t('继承全局')}</Form.Select.Option> <Form.Select.Option value=''>{t('继承全局')}</Form.Select.Option>
{SENSITIVE_OPTIONS.map((o) => ( {SENSITIVE_OPTIONS.map((o) => (
<Form.Select.Option key={o.value} value={o.value}> <Form.Select.Option key={o.value} value={o.value}>
{o.label} {t(o.label)}
</Form.Select.Option> </Form.Select.Option>
))} ))}
</Form.Select> </Form.Select>
@@ -1351,7 +1353,7 @@ export default function DataSecuritySetting() {
<Form.Select.Option value=''>{t('继承全局')}</Form.Select.Option> <Form.Select.Option value=''>{t('继承全局')}</Form.Select.Option>
{MULTIMODAL_OPTIONS.map((o) => ( {MULTIMODAL_OPTIONS.map((o) => (
<Form.Select.Option key={o.value} value={o.value}> <Form.Select.Option key={o.value} value={o.value}>
{o.label} {t(o.label)}
</Form.Select.Option> </Form.Select.Option>
))} ))}
</Form.Select> </Form.Select>
@@ -1363,7 +1365,7 @@ export default function DataSecuritySetting() {
<Form.Select.Option value=''>{t('继承全局')}</Form.Select.Option> <Form.Select.Option value=''>{t('继承全局')}</Form.Select.Option>
{FAILURE_OPTIONS.map((o) => ( {FAILURE_OPTIONS.map((o) => (
<Form.Select.Option key={o.value} value={o.value}> <Form.Select.Option key={o.value} value={o.value}>
{o.label} {t(o.label)}
</Form.Select.Option> </Form.Select.Option>
))} ))}
</Form.Select> </Form.Select>
+3 -1
View File
@@ -21,8 +21,10 @@ import React, { useEffect, useState } from 'react';
import { Card, Spin } from '@/components/ui'; import { Card, Spin } from '@/components/ui';
import SettingsDrawing from '../../pages/Setting/Drawing/SettingsDrawing'; import SettingsDrawing from '../../pages/Setting/Drawing/SettingsDrawing';
import { API, showError, toBoolean } from '../../helpers'; import { API, showError, toBoolean } from '../../helpers';
import { useTranslation } from 'react-i18next';
const DrawingSetting = () => { const DrawingSetting = () => {
const { t } = useTranslation();
let [inputs, setInputs] = useState({ let [inputs, setInputs] = useState({
/* 绘图设置 */ /* 绘图设置 */
DrawingEnabled: false, DrawingEnabled: false,
@@ -59,7 +61,7 @@ const DrawingSetting = () => {
setLoading(true); setLoading(true);
await getOptions(); await getOptions();
} catch (error) { } catch (error) {
showError('刷新失败'); showError(t('刷新失败'));
} finally { } finally {
setLoading(false); setLoading(false);
} }
@@ -1231,9 +1231,8 @@ const LevelPolicySetting = () => {
<Modal <Modal
title={ title={
isNew isNew
? t('新增') + typeLabel(editorType) ? t('新增{{type}}', { type: typeLabel(editorType) })
: t('编辑') + : t('编辑{{type}}', { type: typeLabel(editorType) }) +
typeLabel(editorType) +
` · ${form.name || editingCode} (${editingCode})` ` · ${form.name || editingCode} (${editingCode})`
} }
visible={editorVisible} visible={editorVisible}
+3 -2
View File
@@ -30,7 +30,7 @@ import SettingVideoModel from '../../pages/Setting/Model/SettingVideoModel';
import SettingImagePricing from '../../pages/Setting/Model/SettingImagePricing'; import SettingImagePricing from '../../pages/Setting/Model/SettingImagePricing';
const ModelSetting = () => { const ModelSetting = () => {
const { t: _t } = useTranslation(); const { t } = useTranslation();
let [inputs, setInputs] = useState({ let [inputs, setInputs] = useState({
'gemini.safety_settings': '', 'gemini.safety_settings': '',
'gemini.version_settings': '', 'gemini.version_settings': '',
@@ -41,6 +41,7 @@ const ModelSetting = () => {
'claude.thinking_adapter_budget_tokens_percentage': 0.8, 'claude.thinking_adapter_budget_tokens_percentage': 0.8,
'claude.cache_creation_5m_ratio': 1.25, 'claude.cache_creation_5m_ratio': 1.25,
'claude.cache_creation_1h_ratio': 2, 'claude.cache_creation_1h_ratio': 2,
'claude.cache_ttl_override': 'off',
'global.pass_through_request_enabled': false, 'global.pass_through_request_enabled': false,
'global.thinking_model_blacklist': '[]', 'global.thinking_model_blacklist': '[]',
'general_setting.ping_interval_enabled': false, 'general_setting.ping_interval_enabled': false,
@@ -91,7 +92,7 @@ const ModelSetting = () => {
await getOptions(); await getOptions();
// showSuccess('刷新成功'); // showSuccess('刷新成功');
} catch (error) { } catch (error) {
showError('刷新失败'); showError(t('刷新失败'));
console.error(error); console.error(error);
} finally { } finally {
setLoading(false); setLoading(false);
+4 -2
View File
@@ -36,6 +36,7 @@ import SettingsTheme from '../../pages/Setting/Operation/SettingsTheme';
import SettingsAdminDelegation from '../../pages/Setting/Operation/SettingsAdminDelegation'; import SettingsAdminDelegation from '../../pages/Setting/Operation/SettingsAdminDelegation';
import SettingsSkillInject from '../../pages/Setting/Operation/SettingsSkillInject'; import SettingsSkillInject from '../../pages/Setting/Operation/SettingsSkillInject';
import { API, toBoolean } from '../../helpers'; import { API, toBoolean } from '../../helpers';
import { useTranslation } from 'react-i18next';
const ProgressiveSettingsSections = ({ children, loading }) => { const ProgressiveSettingsSections = ({ children, loading }) => {
const sections = React.Children.toArray(children); const sections = React.Children.toArray(children);
@@ -65,6 +66,7 @@ const ProgressiveSettingsSections = ({ children, loading }) => {
}; };
const OperationSetting = () => { const OperationSetting = () => {
const { t } = useTranslation();
let [inputs, setInputs] = useState({ let [inputs, setInputs] = useState({
/* 额度相关 */ /* 额度相关 */
QuotaForNewUser: 0, QuotaForNewUser: 0,
@@ -199,11 +201,11 @@ const OperationSetting = () => {
await getOptions(); await getOptions();
setOptionsLoaded(true); setOptionsLoaded(true);
} catch (error) { } catch (error) {
setLoadError(error.message || '运营设置读取失败,请重试'); setLoadError(error.message || t('运营设置读取失败,请重试'));
} finally { } finally {
setLoading(false); setLoading(false);
} }
}, [getOptions]); }, [getOptions, t]);
useEffect(() => { useEffect(() => {
onRefresh(); onRefresh();
+2 -2
View File
@@ -25,7 +25,7 @@ import { useTranslation } from 'react-i18next';
import RequestRateLimit from '../../pages/Setting/RateLimit/SettingsRequestRateLimit'; import RequestRateLimit from '../../pages/Setting/RateLimit/SettingsRequestRateLimit';
const RateLimitSetting = () => { const RateLimitSetting = () => {
const { t: _t } = useTranslation(); const { t } = useTranslation();
let [inputs, setInputs] = useState({ let [inputs, setInputs] = useState({
ModelRequestRateLimitEnabled: false, ModelRequestRateLimitEnabled: false,
ModelRequestRateLimitCount: 0, ModelRequestRateLimitCount: 0,
@@ -64,7 +64,7 @@ const RateLimitSetting = () => {
await getOptions(); await getOptions();
// showSuccess('刷新成功'); // showSuccess('刷新成功');
} catch (error) { } catch (error) {
showError('刷新失败'); showError(t('刷新失败'));
} finally { } finally {
setLoading(false); setLoading(false);
} }
+49 -7
View File
@@ -40,12 +40,13 @@ import {
toBoolean, toBoolean,
isRoot, isRoot,
} from '../../helpers'; } from '../../helpers';
import SettingsWeyAi from '../../pages/Setting/WeyAi/SettingsWeyAi'; import { useNavigate } from 'react-router-dom';
import axios from 'axios'; import axios from 'axios';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
const SystemSetting = () => { const SystemSetting = () => {
const { t } = useTranslation(); const { t } = useTranslation();
const navigate = useNavigate();
let [inputs, setInputs] = useState({ let [inputs, setInputs] = useState({
PasswordLoginEnabled: '', PasswordLoginEnabled: '',
PasswordRegisterEnabled: '', PasswordRegisterEnabled: '',
@@ -1477,7 +1478,15 @@ const SystemSetting = () => {
</Text> </Text>
<Banner <Banner
type='info' type='info'
description={`${t('主页链接填')} ${inputs.ServerAddress ? inputs.ServerAddress : t('网站地址')},${t('重定向 URL 填')} ${inputs.ServerAddress ? inputs.ServerAddress : t('网站地址')}/oauth/oidc`} description={t(
'主页链接填 {{home}},重定向 URL 填 {{callback}}',
{
home: inputs.ServerAddress
? inputs.ServerAddress
: t('网站地址'),
callback: `${inputs.ServerAddress ? inputs.ServerAddress : t('网站地址')}/oauth/oidc`,
},
)}
style={{ marginBlock: '16px' }} style={{ marginBlock: '16px' }}
/> />
<Text> <Text>
@@ -1551,7 +1560,15 @@ const SystemSetting = () => {
<Text>{t('用以支持通过 GitHub 进行登录注册')}</Text> <Text>{t('用以支持通过 GitHub 进行登录注册')}</Text>
<Banner <Banner
type='info' type='info'
description={`${t('Homepage URL 填')} ${inputs.ServerAddress ? inputs.ServerAddress : t('网站地址')},${t('Authorization callback URL 填')} ${inputs.ServerAddress ? inputs.ServerAddress : t('网站地址')}/oauth/github`} description={t(
'Homepage URL 填 {{home}},Authorization callback URL 填 {{callback}}',
{
home: inputs.ServerAddress
? inputs.ServerAddress
: t('网站地址'),
callback: `${inputs.ServerAddress ? inputs.ServerAddress : t('网站地址')}/oauth/github`,
},
)}
style={{ marginBlock: '16px' }} style={{ marginBlock: '16px' }}
/> />
<Row <Row
@@ -1582,7 +1599,15 @@ const SystemSetting = () => {
<Text>{t('用以支持通过 Discord 进行登录注册')}</Text> <Text>{t('用以支持通过 Discord 进行登录注册')}</Text>
<Banner <Banner
type='info' type='info'
description={`${t('Homepage URL 填')} ${inputs.ServerAddress ? inputs.ServerAddress : t('网站地址')},${t('Authorization callback URL 填')} ${inputs.ServerAddress ? inputs.ServerAddress : t('网站地址')}/oauth/discord`} description={t(
'Homepage URL 填 {{home}},Authorization callback URL 填 {{callback}}',
{
home: inputs.ServerAddress
? inputs.ServerAddress
: t('网站地址'),
callback: `${inputs.ServerAddress ? inputs.ServerAddress : t('网站地址')}/oauth/discord`,
},
)}
style={{ marginBlock: '16px' }} style={{ marginBlock: '16px' }}
/> />
<Row <Row
@@ -1628,7 +1653,9 @@ const SystemSetting = () => {
</Text> </Text>
<Banner <Banner
type='info' type='info'
description={`${t('回调 URL 填')} ${inputs.ServerAddress ? inputs.ServerAddress : t('网站地址')}/oauth/linuxdo`} description={t('回调 URL 填 {{callback}}', {
callback: `${inputs.ServerAddress ? inputs.ServerAddress : t('网站地址')}/oauth/linuxdo`,
})}
style={{ marginBlock: '16px' }} style={{ marginBlock: '16px' }}
/> />
<Row <Row
@@ -1872,10 +1899,25 @@ const SystemSetting = () => {
<Spin size='large' /> <Spin size='large' />
</div> </div>
)} )}
{/* WeyAi 账号接入配置:仅超级管理员可见(后端同样按 root-only 校验) */} {/* WeyAi 配置已移到「WeyAi」页签(M21);这条提示保留一个版本后删除 */}
{isLoaded && isRoot() && ( {isLoaded && isRoot() && (
<div className='settings-section'> <div className='settings-section'>
<SettingsWeyAi /> <Banner
type='info'
closeIcon={null}
description={
<span>
{t('WeyAi 配置已移到「WeyAi」页签')}
<Button
theme='borderless'
size='small'
onClick={() => navigate('/console/setting?tab=weyai')}
>
{t('前往')}
</Button>
</span>
}
/>
</div> </div>
)} )}
</div> </div>
+106
View File
@@ -0,0 +1,106 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
// 系统设置 →「WeyAi」页签(M21)。WeyAi 的所有配置项都放在这个页签下,按子页签分组;
// 子页签记在地址的 sub 参数里(如 ?tab=weyai&sub=storage),可以直接分享链接。
//
// 「账号接入」「内容存储」只对超级管理员显示,后端同样按 root-only 校验;
// 「内容管理」「版本说明」root 和被下放了「WeyAi」页签的管理员都能用。
import React, { useEffect, useMemo } from 'react';
import { Empty, TabPane, Tabs } from '@douyinfe/semi-ui';
import { useLocation, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { isAdmin, isRoot } from '../../helpers';
import SettingsWeyAi from '../../pages/Setting/WeyAi/SettingsWeyAi';
import SettingsWeyAiContent from '../../pages/Setting/WeyAi/SettingsWeyAiContent';
import SettingsWeyAiContentStorage from '../../pages/Setting/WeyAi/SettingsWeyAiContentStorage';
import SettingsWeyAiReleaseNotes from '../../pages/Setting/WeyAi/SettingsWeyAiReleaseNotes';
const WeyAiSetting = () => {
const { t } = useTranslation();
const navigate = useNavigate();
const location = useLocation();
const subTabs = useMemo(() => {
const tabs = [];
if (isRoot()) {
tabs.push({
key: 'account',
label: t('账号接入'),
content: <SettingsWeyAi />,
});
}
// 能打开这个页签的普通管理员一定是被下放了「WeyAi」页签的(见 Setting/index.jsx)
if (isRoot() || isAdmin()) {
tabs.push({
key: 'content',
label: t('内容管理'),
content: <SettingsWeyAiContent />,
});
tabs.push({
key: 'release-notes',
label: t('版本说明'),
content: <SettingsWeyAiReleaseNotes />,
});
}
if (isRoot()) {
tabs.push({
key: 'storage',
label: t('内容存储'),
content: <SettingsWeyAiContentStorage />,
});
}
return tabs;
}, [t]);
const requested = new URLSearchParams(location.search).get('sub');
const active = subTabs.some((tab) => tab.key === requested)
? requested
: subTabs[0]?.key;
// 地址里没有 sub、或 sub 不存在时改写成当前子页签,刷新和分享都落在同一处
useEffect(() => {
if (active && requested !== active) {
navigate(`?tab=weyai&sub=${active}`, { replace: true });
}
}, [active, requested, navigate]);
if (subTabs.length === 0) {
return (
<Empty className='mt-8' description={t('暂无你可以管理的 WeyAi 配置')} />
);
}
return (
<Tabs
type='line'
activeKey={active}
onChange={(key) => navigate(`?tab=weyai&sub=${key}`)}
>
{subTabs.map((tab) => (
<TabPane itemKey={tab.key} tab={tab.label} key={tab.key}>
{active === tab.key && <div className='mt-2'>{tab.content}</div>}
</TabPane>
))}
</Tabs>
);
};
export default WeyAiSetting;
@@ -118,7 +118,7 @@ const AvatarSection = ({
> >
<img <img
src={getCartoonAvatarDataUrl(preset.id, 96)} src={getCartoonAvatarDataUrl(preset.id, 96)}
alt={preset.label} alt={t(preset.label)}
/> />
<span>{t(preset.label)}</span> <span>{t(preset.label)}</span>
{selected && ( {selected && (
+1 -1
View File
@@ -42,7 +42,7 @@ const SemanticTag = ({ value, fallback, className = '' }) => {
<Tag <Tag
color={token.color} color={token.color}
className={className} className={className}
aria-label={fallback || token.label} aria-label={t(fallback || token.label)}
> >
{t(fallback || token.label)} {t(fallback || token.label)}
</Tag> </Tag>
@@ -225,7 +225,7 @@ const renderMultiKeyStatus = (status, keySize, enabledKeySize, t) => {
const renderResponseTime = (responseTime, t) => { const renderResponseTime = (responseTime, t) => {
let time = responseTime / 1000; let time = responseTime / 1000;
time = time.toFixed(2) + t(' 秒'); time = t('{{value}} 秒', { value: time.toFixed(2) });
if (responseTime === 0) { if (responseTime === 0) {
return ( return (
<Tag color='grey' shape='circle'> <Tag color='grey' shape='circle'>
@@ -497,9 +497,10 @@ export const getChannelsColumns = ({
return ( return (
<div> <div>
<Tooltip <Tooltip
content={ content={t('原因:{{reason}},时间:{{time}}', {
t('原因:') + reason + t(',时间:') + timestamp2string(time) reason,
} time: timestamp2string(time),
})}
> >
{statusControl} {statusControl}
</Tooltip> </Tooltip>
@@ -552,8 +553,10 @@ export const getChannelsColumns = ({
<Tooltip <Tooltip
content={ content={
isRoot() isRoot()
? t('剩余额度$') + record.balance + t(',点击更新') ? t('剩余额度${{balance}},点击更新', {
: t('剩余额度$') + record.balance balance: record.balance,
})
: t('剩余额度${{balance}}', { balance: record.balance })
} }
> >
<Tag <Tag
@@ -621,10 +624,9 @@ export const getChannelsColumns = ({
onBlur={(e) => { onBlur={(e) => {
Modal.warning({ Modal.warning({
title: t('修改子渠道优先级'), title: t('修改子渠道优先级'),
content: content: t('确定要修改所有子渠道优先级为 {{value}} 吗?', {
t('确定要修改所有子渠道优先级为 ') + value: e.target.value,
e.target.value + }),
t(' 吗?'),
onOk: () => { onOk: () => {
if (e.target.value === '') { if (e.target.value === '') {
return; return;
@@ -682,10 +684,9 @@ export const getChannelsColumns = ({
onBlur={(e) => { onBlur={(e) => {
Modal.warning({ Modal.warning({
title: t('修改子渠道权重'), title: t('修改子渠道权重'),
content: content: t('确定要修改所有子渠道权重为 {{value}} 吗?', {
t('确定要修改所有子渠道权重为 ') + value: e.target.value,
e.target.value + }),
t(' 吗?'),
onOk: () => { onOk: () => {
if (e.target.value === '') { if (e.target.value === '') {
return; return;
@@ -55,6 +55,7 @@ import {
selectFilter, selectFilter,
} from '../../../../helpers'; } from '../../../../helpers';
import ModelSelectModal from './ModelSelectModal'; import ModelSelectModal from './ModelSelectModal';
import { mergeChannelSettings } from '../../../../helpers/baiduChannelSettings';
import JSONEditor from '../../../common/ui/JSONEditor'; import JSONEditor from '../../../common/ui/JSONEditor';
import SecureVerificationModal from '../../../common/modals/SecureVerificationModal'; import SecureVerificationModal from '../../../common/modals/SecureVerificationModal';
import ChannelKeyDisplay from '../../../common/ui/ChannelKeyDisplay'; import ChannelKeyDisplay from '../../../common/ui/ChannelKeyDisplay';
@@ -168,6 +169,8 @@ const originInputs = {
tag: '', tag: '',
multi_key_mode: 'random', multi_key_mode: 'random',
// 渠道额外设置的默认值 // 渠道额外设置的默认值
ali_data_inspection_disabled: false,
baidu_liveness_header_mode: 'legacy',
force_format: false, force_format: false,
thinking_to_content: false, thinking_to_content: false,
proxy: '', proxy: '',
@@ -181,6 +184,10 @@ const originInputs = {
client_type_restriction: [], // 客户端类型白名单(cli/vscode),仅 type=14 生效 client_type_restriction: [], // 客户端类型白名单(cli/vscode),仅 type=14 生效
client_version_min: '', // 客户端版本下界(x.y.z),空=从最早 client_version_min: '', // 客户端版本下界(x.y.z),空=从最早
client_version_max: '', // 客户端版本上界(x.y.z),空=至最新 client_version_max: '', // 客户端版本上界(x.y.z),空=至最新
sticky_user_id_fill: false, // 为缺失的 metadata.user_id 补会话内稳定值,让上游按 user_id 哈希粘号
sticky_user_id_mode: 'native', // 注入形态:native(仿 Claude Code 原生)/ opaque
cache_breakpoint_fill: false, // 给完全没有 cache_control 的大上下文请求补一个缓存断点
cache_breakpoint_min_tokens: 0, // 注入门限(估算 prompt token),0=用后端默认 10000
settings: '', settings: '',
// 仅 Vertex: 密钥格式(存入 settings.vertex_key_type) // 仅 Vertex: 密钥格式(存入 settings.vertex_key_type)
vertex_key_type: 'json', vertex_key_type: 'json',
@@ -407,6 +414,7 @@ const EditChannelModal = (props) => {
// 渠道额外设置状态 // 渠道额外设置状态
const [channelSettings, setChannelSettings] = useState({ const [channelSettings, setChannelSettings] = useState({
ali_data_inspection_disabled: false,
force_format: false, force_format: false,
thinking_to_content: false, thinking_to_content: false,
proxy: '', proxy: '',
@@ -419,6 +427,10 @@ const EditChannelModal = (props) => {
client_type_restriction: [], client_type_restriction: [],
client_version_min: '', client_version_min: '',
client_version_max: '', client_version_max: '',
sticky_user_id_fill: false,
sticky_user_id_mode: 'native',
cache_breakpoint_fill: false,
cache_breakpoint_min_tokens: 0,
}); });
const showApiConfigCard = true; // 控制是否显示 API 配置卡片 const showApiConfigCard = true; // 控制是否显示 API 配置卡片
const getInitValues = () => ({ const getInitValues = () => ({
@@ -482,9 +494,10 @@ const EditChannelModal = (props) => {
if (name === 'base_url' && value.endsWith('/v1')) { if (name === 'base_url' && value.endsWith('/v1')) {
Modal.confirm({ Modal.confirm({
title: '警告', title: t('警告'),
content: content: t(
'不需要在末尾加/v1,New API会自动处理,添加后可能导致请求失败,是否继续?', '不需要在末尾加/v1,New API会自动处理,添加后可能导致请求失败,是否继续?',
),
onOk: () => { onOk: () => {
setInputs((inputs) => ({ ...inputs, [name]: value })); setInputs((inputs) => ({ ...inputs, [name]: value }));
}, },
@@ -592,9 +605,14 @@ const EditChannelModal = (props) => {
setMultiToSingle(false); setMultiToSingle(false);
} }
// 解析渠道额外设置并合并到data中 // 解析渠道额外设置并合并到data中
data.baidu_liveness_header_mode = 'legacy';
if (data.setting) { if (data.setting) {
try { try {
const parsedSettings = JSON.parse(data.setting); const parsedSettings = JSON.parse(data.setting);
data.baidu_liveness_header_mode =
parsedSettings.baidu_liveness_header_mode ?? 'legacy';
data.ali_data_inspection_disabled =
parsedSettings.ali_data_inspection_disabled === true;
data.force_format = parsedSettings.force_format || false; data.force_format = parsedSettings.force_format || false;
data.thinking_to_content = data.thinking_to_content =
parsedSettings.thinking_to_content || false; parsedSettings.thinking_to_content || false;
@@ -618,9 +636,18 @@ const EditChannelModal = (props) => {
: []; : [];
data.client_version_min = parsedSettings.client_version_min || ''; data.client_version_min = parsedSettings.client_version_min || '';
data.client_version_max = parsedSettings.client_version_max || ''; data.client_version_max = parsedSettings.client_version_max || '';
data.sticky_user_id_fill =
parsedSettings.sticky_user_id_fill || false;
data.sticky_user_id_mode =
parsedSettings.sticky_user_id_mode || 'native';
data.cache_breakpoint_fill =
parsedSettings.cache_breakpoint_fill || false;
data.cache_breakpoint_min_tokens =
parsedSettings.cache_breakpoint_min_tokens || 0;
} catch (error) { } catch (error) {
console.error('解析渠道设置失败:', error); console.error('解析渠道设置失败:', error);
data.force_format = false; data.force_format = false;
data.ali_data_inspection_disabled = false;
data.thinking_to_content = false; data.thinking_to_content = false;
data.proxy = ''; data.proxy = '';
data.pass_through_body_enabled = false; data.pass_through_body_enabled = false;
@@ -633,9 +660,14 @@ const EditChannelModal = (props) => {
data.client_type_restriction = []; data.client_type_restriction = [];
data.client_version_min = ''; data.client_version_min = '';
data.client_version_max = ''; data.client_version_max = '';
data.sticky_user_id_fill = false;
data.sticky_user_id_mode = 'native';
data.cache_breakpoint_fill = false;
data.cache_breakpoint_min_tokens = 0;
} }
} else { } else {
data.force_format = false; data.force_format = false;
data.ali_data_inspection_disabled = false;
data.thinking_to_content = false; data.thinking_to_content = false;
data.proxy = ''; data.proxy = '';
data.pass_through_body_enabled = false; data.pass_through_body_enabled = false;
@@ -648,6 +680,10 @@ const EditChannelModal = (props) => {
data.client_type_restriction = []; data.client_type_restriction = [];
data.client_version_min = ''; data.client_version_min = '';
data.client_version_max = ''; data.client_version_max = '';
data.sticky_user_id_fill = false;
data.sticky_user_id_mode = 'native';
data.cache_breakpoint_fill = false;
data.cache_breakpoint_min_tokens = 0;
} }
if (data.settings) { if (data.settings) {
@@ -744,6 +780,8 @@ const EditChannelModal = (props) => {
setBasicModels(getChannelModels(data.type)); setBasicModels(getChannelModels(data.type));
// 同步更新channelSettings状态显示 // 同步更新channelSettings状态显示
setChannelSettings({ setChannelSettings({
ali_data_inspection_disabled:
data.ali_data_inspection_disabled === true,
force_format: data.force_format, force_format: data.force_format,
thinking_to_content: data.thinking_to_content, thinking_to_content: data.thinking_to_content,
proxy: data.proxy, proxy: data.proxy,
@@ -762,6 +800,10 @@ const EditChannelModal = (props) => {
: [], : [],
client_version_min: data.client_version_min || '', client_version_min: data.client_version_min || '',
client_version_max: data.client_version_max || '', client_version_max: data.client_version_max || '',
sticky_user_id_fill: data.sticky_user_id_fill || false,
sticky_user_id_mode: data.sticky_user_id_mode || 'native',
cache_breakpoint_fill: data.cache_breakpoint_fill || false,
cache_breakpoint_min_tokens: data.cache_breakpoint_min_tokens || 0,
}); });
initialModelsRef.current = (data.models || []) initialModelsRef.current = (data.models || [])
.map((model) => (model || '').trim()) .map((model) => (model || '').trim())
@@ -1018,6 +1060,7 @@ const EditChannelModal = (props) => {
formApiRef.current?.reset(); formApiRef.current?.reset();
// 重置渠道设置状态 // 重置渠道设置状态
setChannelSettings({ setChannelSettings({
ali_data_inspection_disabled: false,
force_format: false, force_format: false,
thinking_to_content: false, thinking_to_content: false,
proxy: '', proxy: '',
@@ -1031,6 +1074,10 @@ const EditChannelModal = (props) => {
client_type_restriction: [], client_type_restriction: [],
client_version_min: '', client_version_min: '',
client_version_max: '', client_version_max: '',
sticky_user_id_fill: false,
sticky_user_id_mode: 'native',
cache_breakpoint_fill: false,
cache_breakpoint_min_tokens: 0,
}); });
// 重置密钥模式状态 // 重置密钥模式状态
setKeyMode('append'); setKeyMode('append');
@@ -1339,6 +1386,8 @@ const EditChannelModal = (props) => {
// 生成渠道额外设置JSON // 生成渠道额外设置JSON
const channelExtraSettings = { const channelExtraSettings = {
ali_data_inspection_disabled:
localInputs.ali_data_inspection_disabled === true,
force_format: localInputs.force_format || false, force_format: localInputs.force_format || false,
thinking_to_content: localInputs.thinking_to_content || false, thinking_to_content: localInputs.thinking_to_content || false,
proxy: localInputs.proxy || '', proxy: localInputs.proxy || '',
@@ -1363,8 +1412,31 @@ const EditChannelModal = (props) => {
: [], : [],
client_version_min: (localInputs.client_version_min || '').trim(), client_version_min: (localInputs.client_version_min || '').trim(),
client_version_max: (localInputs.client_version_max || '').trim(), client_version_max: (localInputs.client_version_max || '').trim(),
sticky_user_id_fill: localInputs.sticky_user_id_fill || false,
sticky_user_id_mode: ['native', 'opaque'].includes(
localInputs.sticky_user_id_mode,
)
? localInputs.sticky_user_id_mode
: 'native',
cache_breakpoint_fill: localInputs.cache_breakpoint_fill || false,
// 0 = 用后端默认(10000)。负数按 0 处理,低于 1024 的值后端会自己抬到 1024
// (1024 是 opus/sonnet 的最小可缓存前缀,再小注入了也产不出缓存)。
cache_breakpoint_min_tokens: Math.max(
0,
parseInt(localInputs.cache_breakpoint_min_tokens, 10) || 0,
),
}; };
localInputs.setting = JSON.stringify(channelExtraSettings); try {
localInputs.setting = mergeChannelSettings(
inputs.setting,
channelExtraSettings,
localInputs.type,
localInputs.baidu_liveness_header_mode,
);
} catch (error) {
showError(error.message);
return;
}
// 处理 settings 字段(包括企业账户设置和字段透传控制) // 处理 settings 字段(包括企业账户设置和字段透传控制)
let settings = {}; let settings = {};
@@ -1409,6 +1481,7 @@ const EditChannelModal = (props) => {
// 清理不需要发送到后端的字段 // 清理不需要发送到后端的字段
delete localInputs.force_format; delete localInputs.force_format;
delete localInputs.ali_data_inspection_disabled;
delete localInputs.thinking_to_content; delete localInputs.thinking_to_content;
delete localInputs.proxy; delete localInputs.proxy;
delete localInputs.pass_through_body_enabled; delete localInputs.pass_through_body_enabled;
@@ -1418,6 +1491,10 @@ const EditChannelModal = (props) => {
delete localInputs.client_type_restriction; delete localInputs.client_type_restriction;
delete localInputs.client_version_min; delete localInputs.client_version_min;
delete localInputs.client_version_max; delete localInputs.client_version_max;
delete localInputs.sticky_user_id_fill;
delete localInputs.sticky_user_id_mode;
delete localInputs.cache_breakpoint_fill;
delete localInputs.cache_breakpoint_min_tokens;
delete localInputs.system_prompt; delete localInputs.system_prompt;
delete localInputs.system_prompt_override; delete localInputs.system_prompt_override;
delete localInputs.is_enterprise_account; delete localInputs.is_enterprise_account;
@@ -1481,11 +1558,18 @@ const EditChannelModal = (props) => {
} }
if (isEdit) { if (isEdit) {
res = await API.put(`/api/channel/`, { res = await API.put(
`/api/channel/`,
{
...localInputs, ...localInputs,
id: parseInt(channelId), id: parseInt(channelId),
key_mode: isMultiKeyChannel ? keyMode : undefined, // 只在多key模式下传递 key_mode: isMultiKeyChannel ? keyMode : undefined, // 只在多key模式下传递
}); },
{
validateStatus: (status) =>
(status >= 200 && status < 300) || status === 409,
},
);
} else { } else {
res = await API.post(`/api/channel/`, { res = await API.post(`/api/channel/`, {
mode: mode, mode: mode,
@@ -1699,7 +1783,8 @@ const EditChannelModal = (props) => {
// 保持 label 为纯文本以支持搜索 // 保持 label 为纯文本以支持搜索
label: opt.label, label: opt.label,
})), })),
[], // label 是按当前语言取值的 getter,切换语言后需重建
[t],
); );
const renderChannelOption = (renderProps) => { const renderChannelOption = (renderProps) => {
@@ -2259,9 +2344,9 @@ const EditChannelModal = (props) => {
<Form.Input <Form.Input
field='other' field='other'
label={t('模型版本')} label={t('模型版本')}
placeholder={ placeholder={t(
'请输入星火大模型版本,注意是接口地址中的版本号,例如:v2.1' '请输入星火大模型版本,注意是接口地址中的版本号,例如:v2.1',
} )}
onChange={(value) => handleInputChange('other', value)} onChange={(value) => handleInputChange('other', value)}
showClear showClear
/> />
@@ -2292,7 +2377,7 @@ const EditChannelModal = (props) => {
<Form.Input <Form.Input
field='other' field='other'
label={t('知识库 ID')} label={t('知识库 ID')}
placeholder={'请输入知识库 ID,例如:123456'} placeholder={t('请输入知识库 ID,例如:123456')}
onChange={(value) => handleInputChange('other', value)} onChange={(value) => handleInputChange('other', value)}
showClear showClear
/> />
@@ -2302,9 +2387,9 @@ const EditChannelModal = (props) => {
<Form.Input <Form.Input
field='other' field='other'
label='Account ID' label='Account ID'
placeholder={ placeholder={t(
'请输入Account ID,例如:d6b5da8hk1awo8nap34ube6gh' '请输入Account ID,例如:d6b5da8hk1awo8nap34ube6gh',
} )}
onChange={(value) => handleInputChange('other', value)} onChange={(value) => handleInputChange('other', value)}
showClear showClear
/> />
@@ -2314,7 +2399,7 @@ const EditChannelModal = (props) => {
<Form.Input <Form.Input
field='other' field='other'
label={t('智能体ID')} label={t('智能体ID')}
placeholder={'请输入智能体ID,例如:7342866812345'} placeholder={t('请输入智能体ID,例如:7342866812345')}
onChange={(value) => handleInputChange('other', value)} onChange={(value) => handleInputChange('other', value)}
showClear showClear
/> />
@@ -3319,6 +3404,50 @@ const EditChannelModal = (props) => {
</div> </div>
</div> </div>
{inputs.type === 17 && (
<Form.Switch
field='ali_data_inspection_disabled'
label={t('阿里云关闭输入/输出绿网(DataInspection)')}
checkedText={t('开')}
uncheckedText={t('关')}
onChange={(value) =>
handleChannelSettingsChange(
'ali_data_inspection_disabled',
value,
)
}
extraText={t(
'关闭阿里云输入和输出内容安全检测。需要上游权限,生产前请先使用测试 Key 验证;默认关闭。',
)}
/>
)}
{inputs.type === 62 && (
<Form.Select
field='baidu_liveness_header_mode'
label={t('百度真人素材请求头模式')}
optionList={[
{
label: t('兼容模式(默认,发送真人请求头)'),
value: 'legacy',
},
{
label: t('不发送(供应商明确要求时选择)'),
value: 'omit',
},
]}
onChange={(value) =>
handleChannelSettingsChange(
'baidu_liveness_header_mode',
value,
)
}
extraText={t(
'根据供应商账号要求选择,与模型名称无关。已有认证、素材或未完成操作的渠道不能切换,请新建独立渠道。',
)}
/>
)}
{inputs.type === 1 && ( {inputs.type === 1 && (
<Form.Switch <Form.Switch
field='force_format' field='force_format'
@@ -3546,6 +3675,85 @@ const EditChannelModal = (props) => {
)} )}
</div> </div>
<div className='mt-4 mb-2 text-sm font-medium text-gray-700'>
{t('上游缓存优化(仅 Claude 原生渠道生效)')}
</div>
<Form.Switch
field='sticky_user_id_fill'
label={t('会话粘性 user_id 填充')}
checkedText={t('开')}
uncheckedText={t('关')}
onChange={(value) =>
handleChannelSettingsChange(
'sticky_user_id_fill',
value,
)
}
extraText={t(
'为缺失 metadata.user_id 的请求补一个「会话内稳定」的值,使按 user_id 哈希选号的上游把同一会话粘在同一账号上。仅对已确认按 user_id 粘号的上游开启。',
)}
/>
<Form.Select
field='sticky_user_id_mode'
label={t('粘性 user_id 形态')}
style={{ width: '100%' }}
optionList={[
{
label: t('native(仿 Claude Code 原生)'),
value: 'native',
},
{
label: t('opaque(wl_ 前缀不透明串)'),
value: 'opaque',
},
]}
onChange={(value) =>
handleChannelSettingsChange(
'sticky_user_id_mode',
value,
)
}
extraText={t(
'上游只做哈希,形态不影响路由;native 可避免上游按形态做白名单校验时被判成异常客户端。',
)}
/>
<Form.Switch
field='cache_breakpoint_fill'
label={t('缓存断点注入')}
checkedText={t('开')}
uncheckedText={t('关')}
onChange={(value) =>
handleChannelSettingsChange(
'cache_breakpoint_fill',
value,
)
}
extraText={t(
'给「一个 cache_control 都没有」的大上下文请求补一个缓存断点。必须同时开启上面的会话粘性填充,否则注入后每轮哈希到不同账号、只写不读,按 1h 档成本直接翻倍(未开粘性时后端会拒绝注入并记 no_sticky)。',
)}
/>
<Form.InputNumber
field='cache_breakpoint_min_tokens'
label={t('缓存断点注入门限(prompt token)')}
placeholder={t('0 = 用默认值 10000')}
min={0}
step={1000}
style={{ width: '100%' }}
onChange={(value) =>
handleChannelSettingsChange(
'cache_breakpoint_min_tokens',
value,
)
}
extraText={t(
'低于该输入规模的请求不注入。门限越低覆盖越广但边际收益递减:≥50000 覆盖 2.7%、≥10000 覆盖 7.7%、≥2000 覆盖 21.4%。0 = 用后端默认 10000;小于 1024(最小可缓存前缀)时后端自动抬到 1024。',
)}
/>
<Form.Input <Form.Input
field='proxy' field='proxy'
label={t('代理地址')} label={t('代理地址')}
@@ -198,13 +198,13 @@ const EditTagModal = (props) => {
formVals.param_override !== null formVals.param_override !== null
) { ) {
if (typeof formVals.param_override !== 'string') { if (typeof formVals.param_override !== 'string') {
showInfo('参数覆盖必须是合法的 JSON 格式!'); showInfo(t('参数覆盖必须是合法的 JSON 格式!'));
setLoading(false); setLoading(false);
return; return;
} }
const trimmedParamOverride = formVals.param_override.trim(); const trimmedParamOverride = formVals.param_override.trim();
if (trimmedParamOverride !== '' && !verifyJSON(trimmedParamOverride)) { if (trimmedParamOverride !== '' && !verifyJSON(trimmedParamOverride)) {
showInfo('参数覆盖必须是合法的 JSON 格式!'); showInfo(t('参数覆盖必须是合法的 JSON 格式!'));
setLoading(false); setLoading(false);
return; return;
} }
@@ -215,13 +215,13 @@ const EditTagModal = (props) => {
formVals.header_override !== null formVals.header_override !== null
) { ) {
if (typeof formVals.header_override !== 'string') { if (typeof formVals.header_override !== 'string') {
showInfo('请求头覆盖必须是合法的 JSON 格式!'); showInfo(t('请求头覆盖必须是合法的 JSON 格式!'));
setLoading(false); setLoading(false);
return; return;
} }
const trimmedHeaderOverride = formVals.header_override.trim(); const trimmedHeaderOverride = formVals.header_override.trim();
if (trimmedHeaderOverride !== '' && !verifyJSON(trimmedHeaderOverride)) { if (trimmedHeaderOverride !== '' && !verifyJSON(trimmedHeaderOverride)) {
showInfo('请求头覆盖必须是合法的 JSON 格式!'); showInfo(t('请求头覆盖必须是合法的 JSON 格式!'));
setLoading(false); setLoading(false);
return; return;
} }
@@ -80,10 +80,10 @@ const ModelTestModal = ({
copy(selectedModelKeys.join(',')).then((ok) => { copy(selectedModelKeys.join(',')).then((ok) => {
if (ok) { if (ok) {
showSuccess( showSuccess(
t('已复制 ${count} 个模型').replace( t('已复制 {{n}} 个模型', {
'${count}', n: selectedModelKeys.length,
selectedModelKeys.length, count: selectedModelKeys.length,
), }),
); );
} else { } else {
showError(t('复制失败,请手动复制')); showError(t('复制失败,请手动复制'));
@@ -139,10 +139,9 @@ const ModelTestModal = ({
</Tag> </Tag>
{testResult.success && ( {testResult.success && (
<Typography.Text type='secondary'> <Typography.Text type='secondary'>
{t('请求时长: ${time}s').replace( {t('请求时长: {{time}}s', {
'${time}', time: testResult.time.toFixed(2),
testResult.time.toFixed(2), })}
)}
</Typography.Text> </Typography.Text>
)} )}
</div> </div>
@@ -232,14 +232,14 @@ const MarketCatalog = ({
{filtersOpen ? t('收起筛选') : t('筛选')} {filtersOpen ? t('收起筛选') : t('筛选')}
</Button> </Button>
</div> </div>
{/* 企业作用域计价口径提示:标价含企业等级折扣,个人密钥/体验中心调用仍按个人等级计费 */} {/* 企业等级计价提示:用户属于企业时,不论以何身份登录,标价与扣费都按企业等级折扣 */}
{discountScope === 'enterprise' && !hidePrice && ( {discountScope === 'enterprise' && !hidePrice && (
<Alert <Alert
className='mm-scope-alert' className='mm-scope-alert'
type='warning' type='warning'
showIcon showIcon
message={t( message={t(
'当前为企业作用域:以下价格已按企业等级折扣展示;使用个人密钥或体验中心调用时按个人等级计费。', '以下价格已按所属企业的等级折扣展示;企业成员使用个人密钥或体验中心调用时同样按企业等级计费。',
)} )}
/> />
)} )}
@@ -93,7 +93,8 @@ const renderCategories = (categories, t, categoryNames) => {
return renderLimitedItems({ return renderLimitedItems({
items: categoriesArray, items: categoriesArray,
renderItem: (category, idx) => { renderItem: (category, idx) => {
const categoryName = categoryNames[category] || category; // 分类名按当前语言翻译;后端自定义分类名无对应键时原样展示
const categoryName = t(categoryNames[category] || category);
return ( return (
<Tag <Tag
key={idx} key={idx}
@@ -312,7 +313,11 @@ const renderNameRule = (rule, record, t) => {
let label = cfg.label; let label = cfg.label;
if (rule !== 0 && record.matched_count) { if (rule !== 0 && record.matched_count) {
label = `${cfg.label} ${record.matched_count}${t('个模型')}`; label = t('{{rule}} {{n}} 个模型', {
rule: cfg.label,
n: record.matched_count,
count: record.matched_count,
});
} }
const tagElement = ( const tagElement = (
@@ -169,13 +169,17 @@ const renderTimestamp = (timestampInSeconds) => {
); );
}; };
function renderDuration(submit_time, finishTime) { function renderDuration(submit_time, finishTime, t) {
if (!submit_time || !finishTime) return '-'; if (!submit_time || !finishTime) return '-';
const durationSec = finishTime - submit_time; const durationSec = finishTime - submit_time;
const colorKey = durationSec > 60 ? 'red' : 'green'; const colorKey = durationSec > 60 ? 'red' : 'green';
return ( return (
<CustomTag icon={Timer} label={`${durationSec} 秒`} colorKey={colorKey} /> <CustomTag
icon={Timer}
label={t('{{n}} 秒', { n: durationSec })}
colorKey={colorKey}
/>
); );
} }
@@ -419,7 +423,9 @@ export const getTaskLogsColumns = ({
title: t('花费时间'), title: t('花费时间'),
dataIndex: 'finish_time', dataIndex: 'finish_time',
render: (finish, record) => { render: (finish, record) => {
return <>{finish ? renderDuration(record.submit_time, finish) : '-'}</>; return (
<>{finish ? renderDuration(record.submit_time, finish, t) : '-'}</>
);
}, },
}, },
{ {
@@ -394,6 +394,7 @@ const EditTokenModal = (props) => {
} }
if (successCount > 0) { if (successCount > 0) {
showSuccess(t('密钥创建成功,请在列表页面点击复制获取密钥!')); showSuccess(t('密钥创建成功,请在列表页面点击复制获取密钥!'));
props.onCreated?.(successCount);
props.refresh(); props.refresh();
props.handleClose(); props.handleClose();
} }
@@ -782,7 +782,7 @@ export const getLogsColumns = ({
if (!(record.type === 2 || record.type === 5)) { if (!(record.type === 2 || record.type === 5)) {
return <></>; return <></>;
} }
let content = t('渠道') + `:${record.channel}`; let content = t('渠道:{{channel}}', { channel: record.channel });
if (record.other !== '') { if (record.other !== '') {
let other = JSON.parse(record.other); let other = JSON.parse(record.other);
if (other === null) { if (other === null) {
@@ -796,7 +796,7 @@ export const getLogsColumns = ({
) { ) {
let useChannel = other.admin_info.use_channel; let useChannel = other.admin_info.use_channel;
let useChannelStr = useChannel.join('->'); let useChannelStr = useChannel.join('->');
content = t('渠道') + `:${useChannelStr}`; content = t('渠道:{{channel}}', { channel: useChannelStr });
} }
} }
} }
@@ -121,6 +121,9 @@ const UsageBillingDetail = ({
Number(other.cache_creation_tokens_5m || 0) + Number(other.cache_creation_tokens_5m || 0) +
Number(other.cache_creation_tokens_1h || 0); Number(other.cache_creation_tokens_1h || 0);
const textTokens = inputTokens + outputTokens; const textTokens = inputTokens + outputTokens;
// 有 5m/1h 分档时只展示分档,不再重复展示未分档的总量与倍率
const hasSplitCacheCreation =
other.cache_creation_tokens_5m > 0 || other.cache_creation_tokens_1h > 0;
const effectiveGroupRatio = const effectiveGroupRatio =
Number.isFinite(Number(other.user_group_ratio)) && Number.isFinite(Number(other.user_group_ratio)) &&
Number(other.user_group_ratio) !== -1 Number(other.user_group_ratio) !== -1
@@ -134,6 +137,7 @@ const UsageBillingDetail = ({
label: t('缓存命中'), label: t('缓存命中'),
value: formatCount(other.cache_tokens), value: formatCount(other.cache_tokens),
}, },
!hasSplitCacheCreation &&
other.cache_creation_tokens > 0 && { other.cache_creation_tokens > 0 && {
label: t('缓存创建'), label: t('缓存创建'),
value: formatCount(other.cache_creation_tokens), value: formatCount(other.cache_creation_tokens),
@@ -159,6 +163,7 @@ const UsageBillingDetail = ({
label: t('缓存倍率'), label: t('缓存倍率'),
value: formatRatio(other.cache_ratio), value: formatRatio(other.cache_ratio),
}, },
!hasSplitCacheCreation &&
other.cache_creation_ratio != null && other.cache_creation_ratio != null &&
other.cache_creation_tokens > 0 && { other.cache_creation_tokens > 0 && {
label: t('缓存创建倍率'), label: t('缓存创建倍率'),
@@ -207,11 +212,17 @@ const UsageBillingDetail = ({
}, },
other.web_search && { other.web_search && {
label: t('联网搜索'), label: t('联网搜索'),
value: `${formatCount(other.web_search_call_count || 0)} ${t('次')}`, value: t('{{n}} 次', {
n: formatCount(other.web_search_call_count || 0),
count: other.web_search_call_count || 0,
}),
}, },
other.file_search && { other.file_search && {
label: t('文件搜索'), label: t('文件搜索'),
value: `${formatCount(other.file_search_call_count || 0)} ${t('次')}`, value: t('{{n}} 次', {
n: formatCount(other.file_search_call_count || 0),
count: other.file_search_call_count || 0,
}),
}, },
other.image_generation_call && { other.image_generation_call && {
label: t('图片生成'), label: t('图片生成'),
@@ -329,8 +329,8 @@ const UsageLogsExportModal = ({
</RadioGroup> </RadioGroup>
<div className='text-xs text-gray-500 dark:text-gray-400 mt-2'> <div className='text-xs text-gray-500 dark:text-gray-400 mt-2'>
{scope === 'page' {scope === 'page'
? t('本次将导出当前页 {{n}} 条', { n: pageCount }) ? t('本次将导出当前页 {{n}} 条', { n: pageCount, count: pageCount })
: t('本次将导出约 {{n}} 条', { n: logCount })} : t('本次将导出约 {{n}} 条', { n: logCount, count: logCount })}
{scope === 'all' && logCount > EXPORT_LIMIT && ( {scope === 'all' && logCount > EXPORT_LIMIT && (
<span className='text-amber-600 dark:text-amber-400'> <span className='text-amber-600 dark:text-amber-400'>
{' '} {' '}
+15 -5
View File
@@ -170,7 +170,7 @@ const TopUp = () => {
} }
if (topUpCount < minTopUp) { if (topUpCount < minTopUp) {
showError(t('充值数量不能小于') + minTopUp); showError(t('充值数量不能小于 {{min}}', { min: minTopUp }));
return; return;
} }
setOpen(true); setOpen(true);
@@ -195,7 +195,7 @@ const TopUp = () => {
} }
if (topUpCount < minTopUp) { if (topUpCount < minTopUp) {
showError('充值数量不能小于' + minTopUp); showError(t('充值数量不能小于 {{min}}', { min: minTopUp }));
return; return;
} }
setConfirmLoading(true); setConfirmLoading(true);
@@ -445,7 +445,11 @@ const TopUp = () => {
// 划转邀请额度 // 划转邀请额度
const transfer = async () => { const transfer = async () => {
if (transferAmount < getQuotaPerUnit()) { if (transferAmount < getQuotaPerUnit()) {
showError(t('划转金额最低为') + ' ' + renderQuota(getQuotaPerUnit())); showError(
t('划转金额最低为 {{amount}}', {
amount: renderQuota(getQuotaPerUnit()),
}),
);
return; return;
} }
const res = await API.post(`/api/user/aff_transfer`, { const res = await API.post(`/api/user/aff_transfer`, {
@@ -516,7 +520,10 @@ const TopUp = () => {
setAmount(parseFloat(data)); setAmount(parseFloat(data));
} else { } else {
setAmount(0); setAmount(0);
Toast.error({ content: '错误:' + data, id: 'getAmount' }); Toast.error({
content: t('错误:{{msg}}', { msg: data }),
id: 'getAmount',
});
} }
} else { } else {
showError(res); showError(res);
@@ -542,7 +549,10 @@ const TopUp = () => {
setAmount(parseFloat(data)); setAmount(parseFloat(data));
} else { } else {
setAmount(0); setAmount(0);
Toast.error({ content: '错误:' + data, id: 'getAmount' }); Toast.error({
content: t('错误:{{msg}}', { msg: data }),
id: 'getAmount',
});
} }
} else { } else {
showError(res); showError(res);
+15 -2
View File
@@ -17,7 +17,20 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
export const CHANNEL_OPTIONS = [ import i18next from 'i18next';
// label 以简体中文(或厂商英文名)为 i18n 键;读取 label 时按当前界面语言翻译,
// 因此各渲染处直接使用 option.label 即可随语言切换。
const withLocalizedLabels = (options) =>
options.map((opt) => {
const labelKey = opt.label;
return Object.defineProperty({ ...opt }, 'label', {
get: () => i18next.t(labelKey),
enumerable: true,
});
});
export const CHANNEL_OPTIONS = withLocalizedLabels([
{ value: 1, color: 'green', label: 'OpenAI' }, { value: 1, color: 'green', label: 'OpenAI' },
{ {
value: 2, value: 2,
@@ -224,6 +237,6 @@ export const CHANNEL_OPTIONS = [
color: 'green', color: 'green',
label: '百度 Seedance 视频', label: '百度 Seedance 视频',
}, },
]; ]);
export const MODEL_TABLE_PAGE_SIZE = 10; export const MODEL_TABLE_PAGE_SIZE = 10;
+195
View File
@@ -0,0 +1,195 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
// 创作台静态灵感模板(方案 §4.4,B 阶段用静态 JSON,后台配置后置)。
// title / group 为 i18n key;prompt 是直接提交给模型的内容,不翻译。
// model(可选)为推荐模型名:可用时点击模板会切过去,否则保持当前模型(见 creationDock.templateModelFor)。
// params 为推荐参数:只套用当前模型支持且合法的值(见 hooks/creation/creationDock.templateParamsFor),
// 图像的 aspect_ratio 会映射到宽高比最接近的尺寸预设。
export const CREATION_TEMPLATES = [
// ---------------- 图像 ----------------
{
id: 'img-portrait',
kind: 'image',
group: '人像',
title: '电影感人像',
prompt:
'电影感人像特写,黄昏逆光,柔和的轮廓光勾勒发丝,浅景深背景虚化,35mm 胶片质感,细腻皮肤纹理,温暖色调',
params: { aspect_ratio: '2:3' },
},
{
id: 'img-product',
kind: 'image',
group: '商业设计',
title: '产品主图',
prompt:
'高端护肤品瓶身置于大理石台面,柔和棚拍光,水珠点缀,干净浅色背景,商业产品摄影,高清细节,留白构图',
params: { aspect_ratio: '1:1' },
},
{
id: 'img-landscape',
kind: 'image',
group: '风景空间',
title: '壮丽风光',
prompt:
'雪山日出,金色阳光洒在山峰上,山脚湖面倒影清晰,薄雾缭绕,超广角镜头,国家地理风格,细节丰富',
params: { aspect_ratio: '16:9' },
},
{
id: 'img-anime',
kind: 'image',
group: '风格化',
title: '日系动漫',
prompt:
'日系动漫风格,少女站在开满樱花的校园小路上,微风吹起发梢,明亮通透的色彩,细腻线条,新海诚式天空',
params: { aspect_ratio: '9:16' },
},
{
id: 'img-poster',
kind: 'image',
group: '商业设计',
title: '海报设计',
prompt:
'极简风格活动海报,大面积留白,几何色块构成视觉中心,现代无衬线排版区域,高级感配色,平面设计',
params: { aspect_ratio: '3:4' },
},
{
id: 'img-interior',
kind: 'image',
group: '风景空间',
title: '室内设计',
prompt:
'北欧风格客厅,大落地窗引入自然光,原木家具与米白色布艺沙发,绿植点缀,温馨通透,建筑摄影视角',
params: { aspect_ratio: '4:3' },
},
{
id: 'img-food',
kind: 'image',
group: '商业设计',
title: '美食摄影',
prompt:
'热气腾腾的拉面俯拍,溏心蛋与叉烧摆放精致,木质桌面,侧逆光突出蒸汽,美食杂志风格,色彩饱满',
params: { aspect_ratio: '1:1' },
},
{
id: 'img-3d',
kind: 'image',
group: '风格化',
title: '3D 卡通角色',
prompt:
'可爱的 3D 卡通小狐狸角色,圆润造型,柔和材质,皮克斯动画风格,纯色背景,柔光渲染,细节精致',
params: { aspect_ratio: '1:1' },
},
// ---------------- 视频 ----------------
{
id: 'vid-city',
kind: 'video',
group: '风光',
title: '城市延时',
prompt:
'城市夜景延时摄影,车流形成光轨,高楼灯光逐渐亮起,镜头缓慢向前推进,电影级画质',
params: { aspect_ratio: '16:9', duration: 5 },
},
{
id: 'vid-ocean',
kind: 'video',
group: '风光',
title: '海浪航拍',
prompt:
'无人机航拍蔚蓝海面,海浪拍打礁石溅起白色浪花,镜头缓慢上升并向前平移,阳光在水面闪烁',
params: { aspect_ratio: '16:9', duration: 5 },
},
{
id: 'vid-product',
kind: 'video',
group: '商业广告',
title: '产品旋转展示',
prompt:
'一款精致腕表在黑色背景中缓慢旋转 360 度,聚光灯打亮金属表壳,反光细腻流动,商业广告质感',
params: { aspect_ratio: '1:1', duration: 5 },
},
{
id: 'vid-portrait',
kind: 'video',
group: '人物与动物',
title: '人物情绪特写',
prompt:
'女孩站在窗边,微风吹动窗帘与发丝,她缓缓转头看向镜头并露出微笑,柔和自然光,浅景深',
params: { aspect_ratio: '9:16', duration: 5 },
},
{
id: 'vid-nature',
kind: 'video',
group: '风光',
title: '森林晨雾',
prompt:
'清晨的森林,阳光穿过树叶形成丁达尔光束,薄雾缓缓流动,镜头低角度缓慢推进,鸟儿飞过',
params: { aspect_ratio: '16:9', duration: 5 },
},
{
id: 'vid-food',
kind: 'video',
group: '商业广告',
title: '美食慢动作',
prompt:
'慢动作镜头:巧克力酱浇在层层叠叠的松饼上缓缓流下,草莓落下溅起糖粉,暖色调特写',
params: { aspect_ratio: '9:16', duration: 5 },
},
{
id: 'vid-scifi',
kind: 'video',
group: '创意',
title: '科幻场景',
prompt:
'赛博朋克风格的未来都市,霓虹灯招牌闪烁,飞行汽车穿梭于高楼之间,雨夜反光路面,镜头穿越街道',
params: { aspect_ratio: '16:9', duration: 5 },
},
{
id: 'vid-animal',
kind: 'video',
group: '人物与动物',
title: '萌宠瞬间',
prompt:
'一只橘猫在阳光洒落的木地板上伸懒腰,然后好奇地拍打飘落的羽毛,温馨自然的家庭氛围',
params: { aspect_ratio: '9:16', duration: 5 },
},
];
/** 某 kind 的模板列表。 */
export const templatesOf = (kind) =>
CREATION_TEMPLATES.filter((tpl) => tpl.kind === kind);
/** 某 kind 的模板按 group 分组(保持出现顺序):[{ group, items }]。模板墙使用。 */
export const templateGroupsOf = (kind) => {
const groups = [];
templatesOf(kind).forEach((tpl) => {
const name = tpl.group || '';
let entry = groups.find((g) => g.group === name);
if (!entry) {
entry = { group: name, items: [] };
groups.push(entry);
}
entry.items.push(tpl);
});
return groups;
};
export default CREATION_TEMPLATES;
+6 -1
View File
@@ -17,6 +17,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import i18next from 'i18next';
// 图像生成模型族能力注册表 // 图像生成模型族能力注册表
// 新增模型族(如阿里云万相)只需在 FAMILIES 中追加一条 // 新增模型族(如阿里云万相)只需在 FAMILIES 中追加一条
// 表单和 hook 都从这里读,确保单一事实源 // 表单和 hook 都从这里读,确保单一事实源
@@ -91,7 +93,10 @@ const FAMILIES = [
}, },
{ {
key: 'wanx', key: 'wanx',
label: '阿里云万相', // 展示名随界面语言翻译(读取时求值)
get label() {
return i18next.t('阿里云万相');
},
// wanx-* / qwen-image / qwen-image-* // wanx-* / qwen-image / qwen-image-*
match: (m) => /^(wanx|qwen-image)/i.test(m), match: (m) => /^(wanx|qwen-image)/i.test(m),
sizes: [ sizes: [
+22 -2
View File
@@ -17,6 +17,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import i18next from 'i18next';
/** /**
* 模型分类常量 * 模型分类常量
* 用于在体验中心按照用途对模型进行分类 * 用于在体验中心按照用途对模型进行分类
@@ -59,8 +61,22 @@ export const MODEL_CATEGORY = {
OTHER: 'other', OTHER: 'other',
}; };
// 模型分类显示名称(多语言支持) // 模型分类显示名称(多语言支持):值以简体中文为 i18n 键,读取时按当前界面语言翻译,
export const MODEL_CATEGORY_NAMES = { // 因此 MODEL_CATEGORY_NAMES[key] / Object.entries() 拿到的都是当前语言的展示名。
const withLocalizedValues = (map) =>
Object.defineProperties(
{},
Object.fromEntries(
Object.entries(map).map(([key, zhName]) => [
key,
{ get: () => i18next.t(zhName), enumerable: true },
]),
),
);
// 简体中文原文(即 i18n 键)。需要拷贝/合并映射时用这份,展开 MODEL_CATEGORY_NAMES
// 会把 getter 求值成当时语言的译文,切换语言后不再刷新。
export const MODEL_CATEGORY_NAME_KEYS = {
[MODEL_CATEGORY.TEXT_GENERATION]: '文本生成', [MODEL_CATEGORY.TEXT_GENERATION]: '文本生成',
[MODEL_CATEGORY.IMAGE_GENERATION]: '图像生成', [MODEL_CATEGORY.IMAGE_GENERATION]: '图像生成',
[MODEL_CATEGORY.TEXT_TO_IMAGE]: '文生图', [MODEL_CATEGORY.TEXT_TO_IMAGE]: '文生图',
@@ -77,6 +93,10 @@ export const MODEL_CATEGORY_NAMES = {
[MODEL_CATEGORY.OTHER]: '其他', [MODEL_CATEGORY.OTHER]: '其他',
}; };
export const MODEL_CATEGORY_NAMES = withLocalizedValues(
MODEL_CATEGORY_NAME_KEYS,
);
// 根据模型名称或端点类型推断模型分类 // 根据模型名称或端点类型推断模型分类
export const inferModelCategory = (modelName = '', endpointType = '') => { export const inferModelCategory = (modelName = '', endpointType = '') => {
const lowerModelName = modelName.toLowerCase(); const lowerModelName = modelName.toLowerCase();
+2
View File
@@ -24,6 +24,8 @@ For commercial licensing, please contact support@quantumnous.com
*/ */
export const SETTING_TABS = [ export const SETTING_TABS = [
{ key: 'operation', labelKey: '运营设置' }, { key: 'operation', labelKey: '运营设置' },
// WeyAi 的所有配置项都放在这个页签下(M21,WeyAi 23 号文档第 3.3 节)
{ key: 'weyai', labelKey: 'WeyAi' },
{ key: 'data-security', labelKey: '数据安全' }, { key: 'data-security', labelKey: '数据安全' },
{ key: 'content-guard', labelKey: '大模型内容防护' }, { key: 'content-guard', labelKey: '大模型内容防护' },
{ key: 'dashboard', labelKey: '仪表盘设置' }, { key: 'dashboard', labelKey: '仪表盘设置' },
+9 -7
View File
@@ -17,11 +17,13 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com For commercial licensing, please contact support@quantumnous.com
*/ */
import i18next from 'i18next';
// 技能分类标签的展示名映射(技能超市 + 平台管理台共用)。 // 技能分类标签的展示名映射(技能超市 + 平台管理台共用)。
// //
// 标签在数据层是版本 frontmatter 里的英文 slug(skill_versions.tags_json), // 标签在数据层是版本 frontmatter 里的英文 slug(skill_versions.tags_json),
// 是过滤与统计的稳定键,绝不能翻译后写回数据库——这里只做**展示层**映射: // 是过滤与统计的稳定键,绝不能翻译后写回数据库——这里只做**展示层**映射:
// 中文界面显示中文名,未收录的 slug(含本就是中文的标签)原样展示, // 展示名以中文为 i18n 键按界面语言翻译,未收录的 slug(含本就是中文的标签)原样展示,
// 过滤请求仍然携带原始 slug。 // 过滤请求仍然携带原始 slug。
// //
// 新导入技能包引入新 slug 时在此补充即可;漏补不会出错,只是该分类 // 新导入技能包引入新 slug 时在此补充即可;漏补不会出错,只是该分类
@@ -127,12 +129,12 @@ const SKILL_CATEGORY_ZH = {
'personal-development': '个人成长', 'personal-development': '个人成长',
}; };
// 返回标签在指定语言下的展示名。 // 返回标签在当前界面语言下的展示名:已收录的 slug 以中文名为 i18n 键经
// language 取值 {zh, en}(与 NormalizeBrainLocale 同语义);en 界面直接 // i18next.t() 翻译(随界面语言切换);未收录的 slug 原样展示。
// 展示原始 slug——slug 本身就是英文,强行再造一套英文标题反而增加维护面。 // 旧调用方传入的第二个 language 参数已不再参与判断,可忽略。
export const skillTagLabel = (tag, language = 'zh') => { export const skillTagLabel = (tag) => {
if (language !== 'zh') return tag; const zhName = SKILL_CATEGORY_ZH[tag];
return SKILL_CATEGORY_ZH[tag] || tag; return zhName ? i18next.t(zhName) : tag;
}; };
export default SKILL_CATEGORY_ZH; export default SKILL_CATEGORY_ZH;
+5 -4
View File
@@ -25,6 +25,7 @@ import {
stripHistoryAttachments, stripHistoryAttachments,
} from './utils'; } from './utils';
import axios from 'axios'; import axios from 'axios';
import i18next from 'i18next';
import { MESSAGE_ROLES } from '../constants/playground.constants'; import { MESSAGE_ROLES } from '../constants/playground.constants';
import { getServerURL } from './config'; import { getServerURL } from './config';
import { buildGetRequestKey, getHeaderValue } from './requestDedupe'; import { buildGetRequestKey, getHeaderValue } from './requestDedupe';
@@ -232,7 +233,7 @@ export const extractErrorMessage = (body) => {
// 处理API错误响应 // 处理API错误响应
export const handleApiError = (error, response = null) => { export const handleApiError = (error, response = null) => {
const errorInfo = { const errorInfo = {
error: error.message || '未知错误', error: error.message || i18next.t('未知错误'),
timestamp: new Date().toISOString(), timestamp: new Date().toISOString(),
stack: error.stack, stack: error.stack,
}; };
@@ -243,9 +244,9 @@ export const handleApiError = (error, response = null) => {
} }
if (error.message.includes('HTTP error')) { if (error.message.includes('HTTP error')) {
errorInfo.details = '服务器返回了错误状态码'; errorInfo.details = i18next.t('服务器返回了错误状态码');
} else if (error.message.includes('Failed to fetch')) { } else if (error.message.includes('Failed to fetch')) {
errorInfo.details = '网络连接失败或服务器无响应'; errorInfo.details = i18next.t('网络连接失败或服务器无响应');
} }
return errorInfo; return errorInfo;
@@ -293,7 +294,7 @@ export const processGroupsData = (data, userGroup) => {
if (groupOptions.length === 0) { if (groupOptions.length === 0) {
groupOptions = [ groupOptions = [
{ {
label: '用户分组', label: i18next.t('用户分组'),
value: '', value: '',
ratio: 1, ratio: 1,
}, },
+36
View File
@@ -0,0 +1,36 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import i18next from 'i18next';
// Preserve settings unknown to this version of the channel form.
export function mergeChannelSettings(raw, edits, channelType, mode) {
const saved = raw ? JSON.parse(raw) : {};
if (!saved || Array.isArray(saved) || typeof saved !== 'object') {
throw new Error(i18next.t('渠道 setting 必须是 JSON 对象'));
}
const next = { ...saved, ...edits };
if (channelType === 62) {
const normalized = mode === undefined || mode === '' ? 'legacy' : mode;
if (!['legacy', 'omit'].includes(normalized)) {
throw new Error(i18next.t('百度真人 Header 模式必须是 legacy 或 omit'));
}
next.baidu_liveness_header_mode = normalized;
}
return JSON.stringify(next);
}
+53
View File
@@ -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 <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import test from 'node:test';
import assert from 'node:assert/strict';
import { mergeChannelSettings } from './baiduChannelSettings.js';
test('channel form preserves unknown and existing settings while changing mode', () => {
const saved = JSON.stringify({
proxy: 'http://proxy',
future_field: { value: 7 },
baidu_liveness_header_mode: 'legacy',
});
const updated = JSON.parse(
mergeChannelSettings(saved, { proxy: 'http://new-proxy' }, 62, 'omit'),
);
assert.deepEqual(updated, {
proxy: 'http://new-proxy',
future_field: { value: 7 },
baidu_liveness_header_mode: 'omit',
});
assert.equal(
JSON.parse(mergeChannelSettings('', {}, 62, undefined))
.baidu_liveness_header_mode,
'legacy',
);
assert.deepEqual(
JSON.parse(mergeChannelSettings(saved, {}, 61, 'omit')),
JSON.parse(saved),
);
});
test('invalid saved settings and mode fail without silent replacement', () => {
for (const raw of ['null', '[]', '{bad'])
assert.throws(() => mergeChannelSettings(raw, {}, 62, 'omit'));
for (const mode of ['other', false, null])
assert.throws(() => mergeChannelSettings('{}', {}, 62, mode));
});

Some files were not shown because too many files have changed in this diff Show More