diff --git a/src/App.jsx b/src/App.jsx index 60a8dbb8..16577a72 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -19,6 +19,10 @@ For commercial licensing, please contact support@quantumnous.com import React, { lazy, Suspense, useContext, useMemo } from 'react'; import { Route, Routes, Navigate, useLocation } from 'react-router-dom'; +import { + isMiniProgramPaymentPath, + isMiniProgramWebView, +} from './helpers/miniProgram'; import Loading from './components/common/ui/Loading'; import { AuthRedirect, PrivateRoute, AdminRoute, RootRoute } from './helpers'; import NotFound from './pages/NotFound'; @@ -91,7 +95,6 @@ const PersonalSetting = lazy( const Setup = lazy(() => import('./pages/Setup')); const Analytics = lazy(() => import('./pages/Analytics')); const Organization = lazy(() => import('./pages/Organization')); -const OrgCreate = lazy(() => import('./pages/Organization/OrgCreate')); const AdminOrganizations = lazy(() => import('./pages/AdminOrganizations')); const AdminOrder = lazy(() => import('./pages/AdminOrder')); const AdminInvoice = lazy(() => import('./pages/AdminInvoice')); @@ -226,6 +229,11 @@ function App() { ); } + // WeyAi 小程序的 web-view 里不出现付费页面(见 helpers/miniProgram.js),直接回到个人中心。 + if (isMiniProgramWebView() && isMiniProgramPaymentPath(location.pathname)) { + return ; + } + return ( @@ -831,13 +839,8 @@ function App() { path='/org/create' element={ - {isOrgCenterAvailable ? ( - }> - - - ) : ( - - )} + {/* 已下线的自助加入企业页:旧链接/书签统一交给企业中心入口解析 */} + } /> diff --git a/src/components/analytics/ChannelConsumption.jsx b/src/components/analytics/ChannelConsumption.jsx index a17d8a71..8153f114 100644 --- a/src/components/analytics/ChannelConsumption.jsx +++ b/src/components/analytics/ChannelConsumption.jsx @@ -140,7 +140,7 @@ const ChannelConsumption = ({ data, title, icon, t }) => { pageSize, showSizeChanger: true, pageSizeOpts: [10, 20, 30], - showTotal: (total) => `${t('共')} ${total} ${t('条')}`, + showTotal: (total) => t('共 {{total}} 条', { total, count: total }), onPageChange: (page) => setCurrentPage(page), onPageSizeChange: (size) => { setPageSize(size); diff --git a/src/components/analytics/DailyStatsTable.jsx b/src/components/analytics/DailyStatsTable.jsx index 1cd78228..5462903d 100644 --- a/src/components/analytics/DailyStatsTable.jsx +++ b/src/components/analytics/DailyStatsTable.jsx @@ -186,7 +186,7 @@ const DailyStatsTable = ({ data, title, icon, t }) => { pagination={{ pageSize: 10, showSizeChanger: true, - showTotal: (total) => `${t('共')} ${total} ${t('条')}`, + showTotal: (total) => t('共 {{total}} 条', { total, count: total }), }} scroll={{ x: 1100 }} size='small' diff --git a/src/components/analytics/OverviewCards.jsx b/src/components/analytics/OverviewCards.jsx index 35fb6b57..a56c5168 100644 --- a/src/components/analytics/OverviewCards.jsx +++ b/src/components/analytics/OverviewCards.jsx @@ -29,9 +29,9 @@ import { TrendingUp, TrendingDown, } from 'lucide-react'; -import { renderQuota } from '../../helpers'; +import { renderQuota, timestamp2string } from '../../helpers'; -const OverviewCards = ({ overview, t }) => { +const OverviewCards = ({ overview, loading = false, t }) => { if (!overview) { return (
@@ -124,31 +124,44 @@ const OverviewCards = ({ overview, t }) => { }; return ( -
- {cards.map((card, index) => ( - -
-
-

- {card.title} -

-

- {card.value} -

- {renderChange(card.change)} +
+
+ {cards.map((card, index) => ( + +
+
+

+ {card.title} +

+

+ {card.value} +

+ {renderChange(card.change)} +
+
+ {card.icon} +
-
- {card.icon} -
-
- - ))} + + ))} +
+ {/* 活跃/消耗取自汇总层时会落后一个同步周期(约 30~60 秒),把截止时间标出来, + 避免「数字和日志对不上」被当成算错;data_as_of 为 0 表示本次是实时直查。 */} + {overview.data_as_of > 0 && ( +

+ {t('活跃与消耗数据截至')} {timestamp2string(overview.data_as_of)} +

+ )}
); }; diff --git a/src/components/analytics/TopupChannelChart.jsx b/src/components/analytics/TopupChannelChart.jsx index 4900d403..f29466f0 100644 --- a/src/components/analytics/TopupChannelChart.jsx +++ b/src/components/analytics/TopupChannelChart.jsx @@ -45,7 +45,8 @@ const TopupChannelChart = ({ data, title, icon, t }) => { if (!data || data.length === 0) return null; const chartData = data.map((item) => ({ - name: item.payment_method || t('未知'), + name: item.payment_method ? t(item.payment_method) : t('未知'), + rawName: item.payment_method, value: item.amount || 0, count: item.count || 0, })); @@ -53,7 +54,7 @@ const TopupChannelChart = ({ data, title, icon, t }) => { // 根据支付渠道名称生成颜色数组 const colorList = chartData.map((item, index) => { return ( - CHANNEL_COLORS[item.name] || + CHANNEL_COLORS[item.rawName] || DEFAULT_COLORS[index % DEFAULT_COLORS.length] ); }); @@ -80,7 +81,7 @@ const TopupChannelChart = ({ data, title, icon, t }) => { }, { key: () => t('笔数'), - value: (datum) => `${datum?.count || 0} ${t('笔')}`, + value: (datum) => t('{{n}} 笔', { n: datum?.count || 0, count: datum?.count || 0 }), }, ], }, @@ -131,7 +132,7 @@ const TopupChannelChart = ({ data, title, icon, t }) => { className='flex items-center justify-between text-sm py-1 border-b border-gray-100 dark:border-gray-700 last:border-0' > - {item.payment_method} + {item.payment_method ? t(item.payment_method) : t('未知')}
diff --git a/src/components/analytics/TrendCharts.jsx b/src/components/analytics/TrendCharts.jsx index ac790133..6b40b6b6 100644 --- a/src/components/analytics/TrendCharts.jsx +++ b/src/components/analytics/TrendCharts.jsx @@ -65,7 +65,7 @@ const TrendCharts = ({ title, icon, data, type, t }) => { { key: (datum) => datum?.type, value: (datum) => - `${(datum?.value || 0).toLocaleString()} ${t('人')}`, + t('{{n}} 人', { n: (datum?.value || 0).toLocaleString(), count: datum?.value || 0 }), }, ], }, @@ -75,7 +75,7 @@ const TrendCharts = ({ title, icon, data, type, t }) => { { key: (datum) => datum?.type, value: (datum) => - `${(datum?.value || 0).toLocaleString()} ${t('人')}`, + t('{{n}} 人', { n: (datum?.value || 0).toLocaleString(), count: datum?.value || 0 }), }, ], }, diff --git a/src/components/analytics/UserSurveyStats.jsx b/src/components/analytics/UserSurveyStats.jsx index 3e80086a..59e4a226 100644 --- a/src/components/analytics/UserSurveyStats.jsx +++ b/src/components/analytics/UserSurveyStats.jsx @@ -101,7 +101,7 @@ const UserSurveyStats = ({ title, icon, t }) => { return null; const chartData = surveyStats.job_type_stats.map((item) => ({ - name: JOB_TYPE_CONFIG[item.job_type]?.label || t('未知'), + name: t(JOB_TYPE_CONFIG[item.job_type]?.label || '未知'), value: item.count, percentage: item.percentage, })); @@ -124,7 +124,7 @@ const UserSurveyStats = ({ title, icon, t }) => { content: [ { key: (datum) => datum?.name, - value: (datum) => `${datum?.value || 0} ${t('人')}`, + value: (datum) => t('{{n}} 人', { n: datum?.value || 0, count: datum?.value || 0 }), }, { key: () => t('占比'), @@ -153,7 +153,7 @@ const UserSurveyStats = ({ title, icon, t }) => { return null; const chartData = surveyStats.ai_tool_stats.map((item) => ({ - name: AI_TOOL_CONFIG[item.ai_tool_usage]?.label || t('未知'), + name: t(AI_TOOL_CONFIG[item.ai_tool_usage]?.label || '未知'), value: item.count, percentage: item.percentage, })); @@ -176,7 +176,7 @@ const UserSurveyStats = ({ title, icon, t }) => { content: [ { key: (datum) => datum?.name, - value: (datum) => `${datum?.value || 0} ${t('人')}`, + value: (datum) => t('{{n}} 人', { n: datum?.value || 0, count: datum?.value || 0 }), }, { key: () => t('占比'), @@ -238,7 +238,7 @@ const UserSurveyStats = ({ title, icon, t }) => { }, { key: () => t('新增'), - value: (datum) => `${datum?.count || 0} ${t('人')}`, + value: (datum) => t('{{n}} 人', { n: datum?.count || 0, count: datum?.count || 0 }), }, ], }, @@ -280,7 +280,7 @@ const UserSurveyStats = ({ title, icon, t }) => { {title} {totalUsers > 0 && ( - {totalUsers} {t('人已填写')} + {t('{{n}} 人已填写', { n: totalUsers, count: totalUsers })} )}
@@ -399,7 +399,7 @@ const UserSurveyStats = ({ title, icon, t }) => {
{config?.icon} - {config?.label} + {t(config?.label || '')}
@@ -464,7 +464,7 @@ const UserSurveyStats = ({ title, icon, t }) => {
{config?.icon} - {config?.label} + {t(config?.label || '')}
@@ -550,7 +550,7 @@ const UserSurveyStats = ({ title, icon, t }) => { {JOB_TYPE_CONFIG[item.job_type]?.icon} - {JOB_TYPE_CONFIG[item.job_type]?.label} + {t(JOB_TYPE_CONFIG[item.job_type]?.label || '')}
@@ -561,7 +561,7 @@ const UserSurveyStats = ({ title, icon, t }) => { } size='small' > - {AI_TOOL_CONFIG[item.ai_tool_usage]?.label} + {t(AI_TOOL_CONFIG[item.ai_tool_usage]?.label || '')} diff --git a/src/components/analytics/orgReport/ActionCenter.jsx b/src/components/analytics/orgReport/ActionCenter.jsx index 5a1b6cb6..b8da7941 100644 --- a/src/components/analytics/orgReport/ActionCenter.jsx +++ b/src/components/analytics/orgReport/ActionCenter.jsx @@ -158,7 +158,7 @@ const columnsFor = (tab, cny, t, atRisk) => { : 'var(--semi-color-warning)', }} > - {v < 1 ? t('不足 1 天') : `${v.toFixed(1)} ${t('天')}`} + {v < 1 ? t('不足 1 天') : t('{{days}} 天', { days: v.toFixed(1) })} ); }, diff --git a/src/components/analytics/orgReport/Overview.jsx b/src/components/analytics/orgReport/Overview.jsx index d1b1a0e3..41b6315a 100644 --- a/src/components/analytics/orgReport/Overview.jsx +++ b/src/components/analytics/orgReport/Overview.jsx @@ -199,7 +199,7 @@ export const KpiGrid = ({ report, lists, cny, onJump, t }) => { }, { title: t('活跃企业'), - value: `${(k.active_orgs || 0).toLocaleString()} ${t('家')}`, + value: t('{{n}} 家', { n: (k.active_orgs || 0).toLocaleString(), count: k.active_orgs || 0 }), sub: `${t('活跃率')} ${pct(k.active_orgs, servingOrgs).toFixed(1)}% · ${t('新增')} ${k.new_orgs || 0}`, compare: ( @@ -216,7 +216,7 @@ export const KpiGrid = ({ report, lists, cny, onJump, t }) => { }, { title: t('企业活跃成员'), - value: `${(k.active_members || 0).toLocaleString()} ${t('人')}`, + value: t('{{n}} 人', { n: (k.active_members || 0).toLocaleString(), count: k.active_members || 0 }), sub: `${t('渗透率')} ${Math.min(100, pct(k.active_members, k.total_members)).toFixed(1)}% · ${t('成员')} ${(k.total_members || 0).toLocaleString()}`, tip: t('本期通过企业令牌产生调用的去重成员数(按自然日统计)'), onClick: () => onJump('growth'), @@ -242,7 +242,7 @@ export const KpiGrid = ({ report, lists, cny, onJump, t }) => { { title: t('未来 30 天充值缺口'), value: formatCny(k.topup_gap_30d, cny), - sub: `${lists.renewal.length} ${t('家需续费跟进')}`, + sub: t('{{n}} 家需续费跟进', { n: lists.renewal.length, count: lists.renewal.length }), tip: t('按各企业近 7 日日均消耗覆盖 30 天所需金额,减去当前余额后累加'), accent: k.topup_gap_30d > 0 diff --git a/src/components/analytics/orgReport/Tables.jsx b/src/components/analytics/orgReport/Tables.jsx index 37b62776..1c16ec67 100644 --- a/src/components/analytics/orgReport/Tables.jsx +++ b/src/components/analytics/orgReport/Tables.jsx @@ -308,7 +308,7 @@ export const OrgDetailTable = ({ report, filter, setFilter, cny, t }) => { — ) : ( - {v < 1 ? t('不足 1 天') : `${v.toFixed(0)} ${t('天')}`} + {v < 1 ? t('不足 1 天') : t('{{days}} 天', { days: v.toFixed(0) })} ), sorter: (a, b) => diff --git a/src/components/auth/LoginForm.jsx b/src/components/auth/LoginForm.jsx index bd09cd47..ebe2dd23 100644 --- a/src/components/auth/LoginForm.jsx +++ b/src/components/auth/LoginForm.jsx @@ -23,6 +23,7 @@ import React, { useRef, useState, useCallback, + useMemo, lazy, Suspense, } from 'react'; @@ -70,6 +71,10 @@ import GlassCard from './GlassCard'; import AuthCardHeader from './AuthCardHeader'; import AuthLoginTabs from './AuthLoginTabs'; import AgreementModal from '../common/DocumentRenderer/AgreementModal'; +import { + isMiniProgramWebView, + withMiniProgramLogins, +} from '../../helpers/miniProgram'; // 懒加载 Telegram 登录组件(345KB),只在需要时加载 const TelegramLogin = lazy(() => import('./TelegramLogin')); @@ -177,7 +182,11 @@ const LoginForm = () => { // 使用 StatusContext 获取最新状态,而不是从 localStorage 读取 const [statusState] = useContext(StatusContext); - const status = statusState?.status || {}; + // WeyAi 小程序的 web-view 里只留站内能完成的登录方式(见 helpers/miniProgram.js)。 + const status = useMemo(() => { + const raw = statusState?.status || {}; + return isMiniProgramWebView() ? withMiniProgramLogins(raw) : raw; + }, [statusState?.status]); const statusLoaded = statusState?.status !== undefined; // affCode 只需在挂载时提取一次,避免每次渲染都执行 diff --git a/src/components/auth/RegisterForm.jsx b/src/components/auth/RegisterForm.jsx index c2c7e313..677ae352 100644 --- a/src/components/auth/RegisterForm.jsx +++ b/src/components/auth/RegisterForm.jsx @@ -23,6 +23,7 @@ import React, { useRef, useState, useCallback, + useMemo, lazy, Suspense, } from 'react'; @@ -65,6 +66,10 @@ import AuthCardHeader from './AuthCardHeader'; import AuthLoginTabs from './AuthLoginTabs'; import { ArrowRight, Shield, Smartphone, QrCode } from 'lucide-react'; import AgreementModal from '../common/DocumentRenderer/AgreementModal'; +import { + isMiniProgramWebView, + withMiniProgramLogins, +} from '../../helpers/miniProgram'; // 懒加载 Telegram 登录组件(345KB),只在需要时加载 const TelegramLogin = lazy(() => import('./TelegramLogin')); @@ -148,7 +153,11 @@ const RegisterForm = () => { // 使用 StatusContext 获取最新状态,而不是从 localStorage 读取 const [statusState] = useContext(StatusContext); - const status = statusState?.status || {}; + // WeyAi 小程序的 web-view 里只留站内能完成的注册方式(见 helpers/miniProgram.js)。 + const status = useMemo(() => { + const raw = statusState?.status || {}; + return isMiniProgramWebView() ? withMiniProgramLogins(raw) : raw; + }, [statusState?.status]); const statusLoaded = statusState?.status !== undefined; const [showEmailVerification, setShowEmailVerification] = useState(() => { @@ -235,7 +244,7 @@ const RegisterForm = () => { const onSubmitWeChatVerificationCode = async () => { if (turnstileEnabled && turnstileToken === '') { - showInfo('请稍后几秒重试,Turnstile 正在检查用户环境!'); + showInfo(t('请稍后几秒重试,Turnstile 正在检查用户环境!')); return; } setWechatCodeSubmitLoading(true); @@ -253,7 +262,7 @@ const RegisterForm = () => { showError(message); } } catch (error) { - showError('登录失败,请重试'); + showError(t('登录失败,请重试')); } finally { setWechatCodeSubmitLoading(false); } @@ -281,7 +290,7 @@ const RegisterForm = () => { } if (username && password) { if (turnstileEnabled && turnstileToken === '') { - showInfo('请稍后几秒重试,Turnstile 正在检查用户环境!'); + showInfo(t('请稍后几秒重试,Turnstile 正在检查用户环境!')); return; } setRegisterLoading(true); @@ -316,7 +325,7 @@ const RegisterForm = () => { const sendVerificationCode = async () => { if (inputs.email === '') return; if (turnstileEnabled && turnstileToken === '') { - showInfo('请稍后几秒重试,Turnstile 正在检查用户环境!'); + showInfo(t('请稍后几秒重试,Turnstile 正在检查用户环境!')); return; } setVerificationCodeLoading(true); @@ -445,7 +454,7 @@ const RegisterForm = () => { showError(message); } } catch (error) { - showError('登录失败,请重试'); + showError(t('登录失败,请重试')); } }; @@ -529,7 +538,7 @@ const RegisterForm = () => { loading={githubLoading} disabled={githubButtonDisabled} > - {githubButtonText} + {t(githubButtonText)} )} diff --git a/src/components/common/DocumentRenderer/index.jsx b/src/components/common/DocumentRenderer/index.jsx index ffc7fdfa..d8b6622e 100644 --- a/src/components/common/DocumentRenderer/index.jsx +++ b/src/components/common/DocumentRenderer/index.jsx @@ -344,7 +344,12 @@ const DocumentRenderer = ({ const seen = new Map(); const headings = root.querySelectorAll('h2, h3'); headings.forEach((h) => { - if (h.querySelector('.doc-anchor')) return; // 已处理 + const existing = h.querySelector('.doc-anchor'); + if (existing) { + // 已处理;切换语言时只刷新读屏文案 + existing.setAttribute('aria-label', t('复制段落链接')); + return; + } let base = h.id || slugify(h.textContent); if (!base) return; let id = base; @@ -356,7 +361,7 @@ const DocumentRenderer = ({ const a = document.createElement('a'); a.href = `#${id}`; a.className = 'doc-anchor'; - a.setAttribute('aria-label', '复制段落链接'); + a.setAttribute('aria-label', t('复制段落链接')); a.textContent = '#'; a.addEventListener('click', (e) => { e.preventDefault(); @@ -368,7 +373,7 @@ const DocumentRenderer = ({ }); h.prepend(a); }); - }, [isEmbedded, loading, content, processedHtmlContent]); + }, [isEmbedded, loading, content, processedHtmlContent, t]); // 文档内容样式(prose)—— 同时兼顾浅色与深色 const proseClass = `prose prose-base dark:prose-invert max-w-none @@ -428,7 +433,7 @@ const DocumentRenderer = ({ {t('内容正在准备中')}

- {t('管理员尚未设置') + title + t('内容')} + {t('管理员尚未设置{{title}}内容', { title })}

); @@ -456,7 +461,7 @@ const DocumentRenderer = ({ className='group inline-flex items-center gap-2 px-6 py-2.5 bg-gradient-to-r from-brand-from to-brand-to hover:shadow-lg hover:shadow-brand/30 dark:hover:shadow-brand/20 text-white text-sm font-medium rounded-lg shadow-sm transition-all hover:-translate-y-0.5' > - {t('访问') + title} + {t('访问{{title}}', { title })} diff --git a/src/components/common/markdown/MarkdownRenderer.jsx b/src/components/common/markdown/MarkdownRenderer.jsx index 6b5fe662..73a8d6aa 100644 --- a/src/components/common/markdown/MarkdownRenderer.jsx +++ b/src/components/common/markdown/MarkdownRenderer.jsx @@ -70,6 +70,7 @@ export function Mermaid(props) { // 等 setIsLoading(false) 触发重渲染时,React 找不到那些被 mermaid 删掉的节点, // 就抛 removeChild "NotFoundError"。改用 mermaid.render() 拿 svg 字符串后写进 svgRef, // React 始终认为 svgRef 这个 div 是空的,便不会与 mermaid 的 DOM 改动冲突。 + const { t } = useTranslation(); const svgRef = useRef(null); const [hasError, setHasError] = useState(false); const [isLoading, setIsLoading] = useState(true); @@ -164,7 +165,7 @@ export function Mermaid(props) { animation: 'spin 1s linear infinite', }} /> - 加载图表中... + {t('加载图表中...')}
)} {/* React 视角下这个 div 恒为空,SVG 由 effect 通过 innerHTML 注入,互不干涉 */} @@ -305,7 +306,7 @@ export function PreCode(props) { color: 'var(--semi-color-text-2)', }} > - HTML预览: + {t('HTML预览:')}
@@ -719,6 +720,7 @@ export function MarkdownRenderer(props) { previousContentLength = 0, ...otherProps } = props; + const { t } = useTranslation(); return (
- 正在渲染... + {t('正在渲染...')}
) : ( )} diff --git a/src/components/common/ui/Loading.jsx b/src/components/common/ui/Loading.jsx index a7f9cf82..827b9195 100644 --- a/src/components/common/ui/Loading.jsx +++ b/src/components/common/ui/Loading.jsx @@ -17,6 +17,7 @@ along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ import React, { useEffect, useMemo, useState } from 'react'; +import i18next from 'i18next'; // 读品牌值:localStorage → window.__WL_BRAND__(index.html 内联脚本写入)→ 空。 // 不用 getSystemName/getLogo —— 它们的终极兜底是 'Weelinking' / '/logo.svg'(老品牌), @@ -38,6 +39,7 @@ const readBrand = (key, windowKey) => { // 加载文案根据浏览器语言决定,避免 i18n 还没初始化时硬编码中文。 const getLoadingText = () => { + if (i18next.isInitialized) return i18next.t('加载中...'); const lang = ((typeof navigator !== 'undefined' && navigator.language) || 'zh').toLowerCase(); return lang.startsWith('zh') ? '加载中...' : 'Loading...'; }; diff --git a/src/components/creation/CompareSummary.jsx b/src/components/creation/CompareSummary.jsx new file mode 100644 index 00000000..88b82c77 --- /dev/null +++ b/src/components/creation/CompareSummary.jsx @@ -0,0 +1,148 @@ +/* +Copyright (C) 2025 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ + +import React from 'react'; +import { Button, Modal, Spin } from '@douyinfe/semi-ui'; +import { AlertTriangle } from 'lucide-react'; +import { useTranslation } from 'react-i18next'; +import { compareParamSummary } from '../../hooks/creation/creationCompare'; +import { formatQuoteAmount } from '../../hooks/creation/useCreationQuote'; +import { displayNameOf } from './ModelPicker'; + +const amountOf = (item) => + item && !item.error + ? formatQuoteAmount(item.display_amount, item.currency) + : ''; + +/** + * 对比生成提交前摘要(WP C-2,方案 §4.2):逐模型"模型 · 实际参数 · 价格"与合计; + * 合计超过系统阈值时显示二次确认提示,确认按钮写明合计金额。 + */ +const CompareSummary = ({ visible, compare, onCancel, onConfirm }) => { + const { t } = useTranslation(); + const { + entries, + quote, + quoteLoading, + quoteFailed, + overThreshold, + submitting, + } = compare; + const items = quote?.items || []; + const total = quote + ? formatQuoteAmount(quote.display_amount, quote.currency) + : ''; + const approximate = Boolean( + quote?.approximate || items.some((item) => item?.approximate), + ); + const totalText = total + ? approximate + ? t('约 {{amount}}', { amount: total }) + : total + : quoteLoading + ? t('正在估价...') + : t('价格以实际扣费为准'); + + return ( + + + +
+ } + > +
+

+ {t( + '将用同一提示词分别提交 {{n}} 个模型,每个模型单独计费,失败自动退还', + { + n: entries.length, + }, + )} +

+
    + {entries.map((entry, i) => { + const amount = amountOf(items[i]); + const params = compareParamSummary(entry.payload); + return ( +
  • + + {displayNameOf(entry.model)} + + + {params || '-'} + + + {amount ? ( + items[i]?.approximate ? ( + t('约 {{amount}}', { amount }) + ) : ( + amount + ) + ) : quoteLoading ? ( + + ) : ( + '-' + )} + + {entry.adjustments?.length ? ( + + {t('部分参数已按该模型调整')} + + ) : null} +
  • + ); + })} +
+
+ {t('合计')} + {totalText} +
+ {quoteFailed ? ( +

{t('估价失败,价格以实际扣费为准')}

+ ) : null} + {overThreshold ? ( +
+
+ ) : null} +
+ + ); +}; + +export default CompareSummary; diff --git a/src/components/creation/CreationDock.jsx b/src/components/creation/CreationDock.jsx new file mode 100644 index 00000000..c5d65668 --- /dev/null +++ b/src/components/creation/CreationDock.jsx @@ -0,0 +1,1657 @@ +/* +Copyright (C) 2025 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ + +import React, { + useCallback, + useContext, + useEffect, + useMemo, + useRef, + useState, + useSyncExternalStore, +} from 'react'; +import { flushSync } from 'react-dom'; +import { + Button, + Dropdown, + Popover, + SideSheet, + Skeleton, + TextArea, + Tooltip, +} from '@douyinfe/semi-ui'; +import { + AlertCircle, + ArrowLeft, + Bell, + BellOff, + ChevronDown, + ChevronUp, + Clapperboard, + History, + ImageIcon, + ImagePlus, + LayoutTemplate, + Lock, + MoreHorizontal, + Settings2, + Sparkles, + Wand2, + Wallet, + X, +} from 'lucide-react'; +import { useTranslation } from 'react-i18next'; +import { useNavigate } from 'react-router-dom'; +import { showError, showInfo, showSuccess } from '../../helpers'; +import { StatusContext } from '../../context/Status'; +import { MODEL_CATEGORY } from '../../constants'; +import { templatesOf } from '../../constants/creationTemplates'; +import { ERROR_ACTIONS } from '../../helpers/creationError'; +import { trackCreationEvent } from '../../helpers/creationEvents'; +import { useIsMobile } from '../../hooks/common/useIsMobile'; +import { useModelSelector } from '../../hooks/models/useModelSelector'; +import { useOptimizePrompt } from '../../hooks/playground/useOptimizePrompt'; +import { formatQuoteAmount } from '../../hooks/creation/useCreationQuote'; +import { adapterOf } from '../../hooks/creation/creationForm'; +import { manualSubmitDecision } from '../../hooks/creation/creationCompare'; +import { openBatchConfirm } from './batchConfirm'; +import { + maybeRequestNotifyPermission, + setNotifyEnabled, + useNotifySetting, +} from '../../hooks/creation/useCreationWatch'; +import { + ROLE_FRAMES, + backToImage2Video, + imageRefToken, + insertAt, + loadPromptHistory, + loadRoleMemory, + mappingAfterMove, + mappingAfterRemove, + missingFrameOf, + modeCapacity, + acceptsImages, + moveItem, + planImageUpload, + rememberRole, + rewriteImageRefs, + savePromptHistory, + suggestImageModel, + usesImageRefs, +} from '../../hooks/creation/creationDock'; +import { + ImageSlot, + ParamRenderer, + isRandomSeed, + optionLabel, + optionValue, + paramLabel, +} from './params'; +import ImageSizePicker from '../../pages/ExperienceCenter/components/AICreation/Image/ImageSizePicker'; +import ModelPicker, { displayNameOf } from './ModelPicker'; +import PortraitAssetPicker from '../../pages/ExperienceCenter/components/AICreation/Video/PortraitAssetPicker'; +import CompareSummary from './CompareSummary'; +import { sheetHeight } from './viewport'; +import './creation-dock.css'; + +// 升级 / 充值入口(会员与充值同在钱包页) +const TOPUP_PATH = '/console/topup'; +// 查看可用模型(模型超市) +const MARKET_PATH = '/market'; + +const IS_MAC = + typeof navigator !== 'undefined' && + /Mac|iPhone|iPad/i.test(navigator.platform || navigator.userAgent || ''); +const SHORTCUT_LABEL = IS_MAC ? '⌘↵' : 'Ctrl+Enter'; +const SHORTCUT_ARIA = IS_MAC ? 'Meta+Enter' : 'Control+Enter'; + +// 移动端(< md)与矮屏桌面(高度 < 800)使用收起 / 展开两态(方案 §4.1) +const COMPACT_QUERY = '(max-width: 767px), (max-height: 799px)'; +const useCompactDock = () => + useSyncExternalStore( + (callback) => { + const mql = window.matchMedia(COMPACT_QUERY); + mql.addEventListener('change', callback); + return () => mql.removeEventListener('change', callback); + }, + () => window.matchMedia(COMPACT_QUERY).matches, + () => false, + ); + +// 展开态期间隐藏体验中心的 MobileBottomNav(见 creation-dock.css) +const BODY_EXPANDED_CLASS = 'cs-dock-expanded'; + +// 可作为创作台 chip 的参数类型(textarea 等长内容只放在高级设置里) +const CHIP_TYPES = new Set([ + 'size', + 'ratio', + 'chips', + 'segmented', + 'select', + 'switch', + 'seed', + 'slider', +]); + +// 选完即可收起弹层的单选型控件 +const PICK_AND_CLOSE = new Set(['ratio', 'chips', 'segmented', 'size']); + +const getStorage = () => { + try { + return window.localStorage; + } catch (e) { + return null; + } +}; + +// 弹层内点击 Select 下拉等其他 portal 时不关闭弹层 +const isInsideOtherPortal = (e) => + Boolean(e?.target?.closest?.('.semi-portal, .semi-select-option-list')); + +/** 估价文案:"预计 ¥x · 约 N 秒 · 失败自动退还";估价失败 → "价格以实际扣费为准"。 */ +export const quoteText = ( + t, + { quote, quoteLoading, quoteFailed, estSeconds }, +) => { + const parts = []; + const item = quote?.items?.[0]; + const amount = + item && !item.error + ? formatQuoteAmount(item.display_amount, item.currency) + : ''; + if (quoteFailed || (quote && !amount)) { + parts.push(t('价格以实际扣费为准')); + } else if (amount) { + parts.push( + item.approximate + ? t('预计约 {{amount}}', { amount }) + : t('预计 {{amount}}', { amount }), + ); + } else if (quoteLoading) { + parts.push(t('正在估价...')); + } + if (estSeconds > 0) parts.push(t('约 {{n}} 秒', { n: estSeconds })); + if (!parts.length) return ''; + parts.push(t('失败自动退还')); + return parts.join(' · '); +}; + +/** 对比生成的估价文案:"合计 预计 ¥x · N 个模型 · 失败自动退还"。 */ +export const compareQuoteText = (t, compare) => { + const q = compare.quote; + const amount = q ? formatQuoteAmount(q.display_amount, q.currency) : ''; + const parts = []; + if (compare.quoteFailed || (q && !amount)) { + parts.push(t('价格以实际扣费为准')); + } else if (amount) { + const approximate = Boolean( + q.approximate || (q.items || []).some((i) => i?.approximate), + ); + parts.push( + approximate + ? t('合计约 {{amount}}', { amount }) + : t('合计 {{amount}}', { amount }), + ); + } else if (compare.quoteLoading) { + parts.push(t('正在估价...')); + } + parts.push(t('{{n}} 个模型', { n: compare.models.length })); + parts.push(t('失败自动退还')); + return parts.join(' · '); +}; + +/** 参数 chip 上显示的取值。 */ +const chipValueText = (t, param, value) => { + if (param.type === 'size') { + return value ? String(value).replace(/x/i, '×') : t('尺寸'); + } + if (param.type === 'switch') { + return `${paramLabel(t, param)} ${value ? t('开') : t('关')}`; + } + if (param.type === 'seed') { + return isRandomSeed(value) + ? `${paramLabel(t, param)} ${t('随机')}` + : `${paramLabel(t, param)} ${value}`; + } + if (Array.isArray(param.options) && param.options.length) { + const hit = param.options.find( + (o) => String(optionValue(o)) === String(value), + ); + if (hit !== undefined) return optionLabel(t, param, hit); + } + if (value === undefined || value === null || value === '') { + return paramLabel(t, param); + } + return optionLabel(t, param, value); +}; + +/** + * 弹层:桌面 Popover,< md 底部 SideSheet。trigger 由调用方渲染并负责 onClick 切换。 + */ +const DockPopover = ({ + open, + onClose, + title, + isMobile, + sheetHeight = 'auto', + className = '', + children, + trigger, +}) => { + if (isMobile) { + return ( + <> + {trigger} + + {open ?
{children}
: null} +
+ + ); + } + return ( + { + if (!isInsideOtherPortal(e)) onClose(); + }} + onEscKeyDown={onClose} + contentClassName={`cs-popover ${className}`} + content={ + open ? ( +
+ {title ?
{title}
: null} + {children} +
+ ) : null + } + > + {trigger} +
+ ); +}; + +/** 单个参数 chip:点击在弹层 / 底部抽屉中打开 ParamRenderer(或尺寸选择器)。 */ +const ParamChip = ({ + param, + params, + values, + onChange, + constraints, + isMobile, +}) => { + const { t } = useTranslation(); + const [open, setOpen] = useState(false); + const label = paramLabel(t, param); + const value = values?.[param.key]; + const handleChange = (key, v) => { + onChange(key, v); + if (PICK_AND_CLOSE.has(param.type)) setOpen(false); + }; + // 只渲染当前参数,其余参数仍传入以便约束说明引用它们的名称 + const scoped = useMemo( + () => + params.map((p) => + p.key === param.key + ? { ...p, placement: 'dock' } + : { ...p, placement: 'hidden' }, + ), + [params, param.key], + ); + const text = chipValueText(t, param, value); + return ( + setOpen(false)} + title={label} + isMobile={isMobile} + trigger={ + + } + > + {param.type === 'size' ? ( +
+ handleChange('size', v)} + /> +
+ ) : ( + + )} +
+ ); +}; + +/** 模板选择:静态模板,选中后填入提示词并套用推荐参数。 */ +const TemplatePicker = ({ kind, isMobile, onApply }) => { + const { t } = useTranslation(); + const [open, setOpen] = useState(false); + const list = useMemo(() => templatesOf(kind), [kind]); + const Icon = kind === 'video' ? Clapperboard : ImageIcon; + if (!list.length) return null; + return ( + setOpen(false)} + title={t('灵感模板')} + isMobile={isMobile} + sheetHeight={sheetHeight(70)} + className='cs-templates-pop' + trigger={ + + } + > +
    + {list.map((tpl) => ( +
  • + +
  • + ))} +
+
+ ); +}; + +/** + * 底部创作台(WP B-3,方案 §4.1 / §4.3 / §4.4 / §4.6)。 + * + * - 桌面(≥ md 且高度 ≥ 800):常驻完整创作台; + * - 移动端与矮屏桌面:收起态(一行提示词 + 模型 chip + 生成,约 56px)/ 展开态(覆盖作品流、 + * 不挤压;展开期间隐藏 MobileBottomNav;弹层用底部抽屉;键盘弹起时跟随可视视口)。 + * + * @param {{ form: ReturnType }} props + */ +const CreationDock = ({ form, compare = null }) => { + const { t } = useTranslation(); + const navigate = useNavigate(); + const [statusState] = useContext(StatusContext); + const notify = useNotifySetting(); + const [summaryOpen, setSummaryOpen] = useState(false); + // 对比生成(WP C-2,仅图像):创作台只显示所选模型的共同参数,生成前展示逐模型摘要 + const comparing = Boolean(compare?.active); + const isMobile = useIsMobile(); + const promptFocusedRef = useRef(false); + const compact = useCompactDock(); + const [expanded, setExpanded] = useState(false); + const [advancedOpen, setAdvancedOpen] = useState(false); + const [pending, setPending] = useState(null); + const [roleMemory, setRoleMemory] = useState(() => + loadRoleMemory(getStorage(), form.kind), + ); + const [promptHistory, setPromptHistory] = useState(() => + loadPromptHistory(getStorage(), form.kind), + ); + const dockRef = useRef(null); + const promptWrapRef = useRef(null); + const switchPendingRef = useRef(null); + + const { + kind, + form: state, + creationData, + models, + modelsLoading, + modelsError, + reloadModels, + selectedModel, + selectModel, + mode, + modeOptions, + setMode, + prompt, + setPrompt, + params, + visibleParams, + setParam, + imageSlots, + pickImage, + removeImage, + retryImage, + setImages, + setImageRef, + submitBlock, + submitting, + submit, + budgetShortfall, + lastError, + clearError, + adjustments, + clearAdjustments, + applyTemplate, + allLocked, + } = form; + + const { models: textModels } = useModelSelector( + MODEL_CATEGORY.TEXT_GENERATION, + ); + const { optimizing, optimize } = useOptimizePrompt(); + + const modeLabels = adapterOf(kind).modeLabels; + const constraints = selectedModel?.constraints || []; + const images = state.images; + const refs = images.reference_images || []; + const showExpanded = !compact || expanded; + // 估价对应当前参数且已返回;参数刚变化(防抖 / 加载中)时旧估价不作数 + const quoteFresh = form.quoteFresh !== false; + // 估价 dry-run 预算不足:个人钱包 → 按钮变"去充值";企业 / 令牌预算 → 说明是哪一级(不阻止提交) + // 估价未更新时保持中性状态,不按上一次参数的结果切换按钮 + const needTopUp = + !submitBlock && quoteFresh && budgetShortfall?.personal === true; + const orgShortfall = + !submitBlock && quoteFresh && budgetShortfall && !budgetShortfall.personal + ? budgetShortfall + : null; + // 内容审核指明了触发的输入时,高亮对应槽位 + const flaggedInput = + lastError?.category === 'moderation' ? lastError.input : null; + const priceText = comparing + ? compareQuoteText(t, compare) + : quoteText(t, form); + const blockText = comparing ? compare.blockReason : submitBlock; + const refMode = usesImageRefs(mode); + const missingFrame = missingFrameOf(kind, selectedModel, mode, images); + const canBackToI2V = + Boolean(missingFrame) && Boolean(backToImage2Video(selectedModel, images)); + const modeHasImages = modeCapacity(kind, selectedModel, mode).max > 0; + const modelAcceptsImages = acceptsImages(kind, selectedModel); + // COS 关闭时视频不能上传本地图片(来自生成结果的引用仍可用,方案 §4.6) + const localUploadBlocked = + kind === 'video' && creationData?.image_input_enabled === false; + const uploadBlockedReason = localUploadBlocked + ? t('对象存储(COS)未开启,暂不支持上传图片') + : ''; + const hasUnused = imageSlots.some((s) => s.slot && !s.active); + + // 对比模式:参数取所选模型的交集,取值由对比状态维护,不做单模型约束联动 + const chipParams = comparing ? compare.shared : visibleParams; + const chipValues = comparing ? compare.values : params; + const onChipChange = comparing ? compare.setValue : setParam; + const chipConstraints = comparing ? [] : constraints; + const dockParams = chipParams.filter( + (p) => (p.placement || 'dock') === 'dock' && CHIP_TYPES.has(p.type), + ); + const hasAdvanced = chipParams.some((p) => p.placement === 'advanced'); + + // --------------------------------------------------------------------------- + // 收起 / 展开 + // --------------------------------------------------------------------------- + const focusPrompt = useCallback(() => { + const el = promptWrapRef.current?.querySelector('textarea'); + if (el) { + el.focus(); + const len = el.value.length; + try { + el.setSelectionRange(len, len); + } catch (e) { + // 部分浏览器不支持 + } + } + }, []); + + const expand = useCallback(() => { + // 同步渲染后立即聚焦,保证移动端在同一手势内弹出键盘 + flushSync(() => setExpanded(true)); + focusPrompt(); + }, [focusPrompt]); + + const collapse = useCallback(() => { + setExpanded(false); + setAdvancedOpen(false); + }, []); + + useEffect(() => { + if (!compact) setExpanded(false); + }, [compact]); + + // 作品流的复用参数 / 编辑此图等操作后:展开创作台并聚焦提示词(WP B-6) + const focusTick = form.focusTick || 0; + const lastFocusTickRef = useRef(focusTick); + useEffect(() => { + if (focusTick === lastFocusTickRef.current) return; + lastFocusTickRef.current = focusTick; + if (compact) { + setExpanded(true); + requestAnimationFrame(focusPrompt); + } else { + focusPrompt(); + } + }, [focusTick, compact, focusPrompt]); + + useEffect(() => { + if (!(compact && expanded)) return undefined; + document.body.classList.add(BODY_EXPANDED_CLASS); + return () => document.body.classList.remove(BODY_EXPANDED_CLASS); + }, [compact, expanded]); + + // 键盘弹起时可视视口变矮:展开态底部跟随可视视口,创作台与生成按钮保持可见 + useEffect(() => { + if (!(compact && expanded)) return undefined; + const vv = window.visualViewport; + const el = dockRef.current; + if (!vv || !el) return undefined; + const update = () => { + const offset = Math.max(0, window.innerHeight - vv.height - vv.offsetTop); + el.style.setProperty('--cs-kb-offset', `${Math.round(offset)}px`); + }; + update(); + vv.addEventListener('resize', update); + vv.addEventListener('scroll', update); + return () => { + vv.removeEventListener('resize', update); + vv.removeEventListener('scroll', update); + }; + }, [compact, expanded]); + + // --------------------------------------------------------------------------- + // 提交 + // --------------------------------------------------------------------------- + const confirmThreshold = + statusState?.status?.experience_center_batch_confirm_threshold; + const runSubmit = useCallback(async () => { + const submitted = prompt; + const ok = await submit(); + if (ok) { + setPromptHistory((prev) => + savePromptHistory(getStorage(), kind, prev, submitted), + ); + } + if (ok && compact) collapse(); + }, [submit, prompt, kind, compact, collapse]); + + // 点了生成但估价尚未对应当前参数:等估价返回后再提交(见下方 effect) + const pendingSubmitRef = useRef(false); + const handleSubmit = useCallback(async () => { + if (comparing) { + if (compare.blockReason) { + showError(compare.blockReason); + return; + } + setSummaryOpen(true); + return; + } + if (needTopUp) { + navigate(TOPUP_PATH); + return; + } + // 开启了完成通知:首次提交时在用户手势内请求浏览器通知权限(WP C-4) + maybeRequestNotifyPermission(); + // 多张生成合计超过系统阈值时二次确认(方案 §4.4 / 决策 3)。 + // 估价仍是上一次参数的结果(如刚把张数从 1 改成 4)时不能据此跳过确认:等估价返回后再决定 + const n = Number(form.payload?.n) || 1; + const quote = form.quote; + const decision = manualSubmitDecision({ + n, + threshold: confirmThreshold, + quote, + quoteFresh, + quoteFailed: form.quoteFailed, + }); + if (decision === 'wait') { + pendingSubmitRef.current = true; + showInfo(t('正在估价...')); + return; + } + pendingSubmitRef.current = false; + if (decision === 'confirm') { + openBatchConfirm({ t, n, quote, onOk: runSubmit }); + return; + } + runSubmit(); + }, [ + comparing, + compare, + needTopUp, + navigate, + form.payload, + form.quote, + form.quoteFailed, + quoteFresh, + confirmThreshold, + runSubmit, + t, + ]); + + // 等估价时点了生成:估价返回(对应当前参数)后按最新估价重新走一遍提交决策 + useEffect(() => { + if (!pendingSubmitRef.current || !quoteFresh) return; + pendingSubmitRef.current = false; + if (comparing) return; + if (blockText) { + showError(blockText); + return; + } + handleSubmit(); + }, [quoteFresh, comparing, blockText, handleSubmit]); + + const confirmCompare = useCallback(async () => { + maybeRequestNotifyPermission(); + const submitted = prompt; + const ok = await compare.submit(); + setSummaryOpen(false); + if (ok) { + setPromptHistory((prev) => + savePromptHistory(getStorage(), kind, prev, submitted), + ); + if (compact) collapse(); + } + }, [compare, prompt, kind, compact, collapse]); + + const onPromptKeyDown = (e) => { + if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) { + e.preventDefault(); + if (!blockText) handleSubmit(); + else showError(blockText); + } + }; + + // --------------------------------------------------------------------------- + // 图片:先传图的模式推断 / 角色选择 / 不支持图片时建议换模型(方案 §4.4) + // --------------------------------------------------------------------------- + const placeFiles = useCallback( + async (plan, files) => { + // 已在图片模式但空槽不够时重新推断的模式:先按新模式重新排布已有图片 + if (plan.images) setImages(plan.images); + if (plan.mode && plan.mode !== mode) setMode(plan.mode); + if (plan.truncated > 0) { + showInfo( + plan.targets.length + ? t('当前模式最多再放 {{n}} 张图片,其余 {{m}} 张未添加', { + n: plan.targets.length, + m: plan.truncated, + }) + : t('当前模式的图片槽已满'), + ); + } + for (let i = 0; i < plan.targets.length; i += 1) { + const target = plan.targets[i]; + // eslint-disable-next-line no-await-in-loop + await pickImage(target.key, target.index, files[i]); + } + }, + [mode, setMode, setImages, pickImage, t], + ); + + const handleFiles = useCallback( + (fileList) => { + const files = Array.from(fileList || []).filter( + (f) => f && (!f.type || f.type.startsWith('image/')), + ); + if (!files.length || !selectedModel) return; + if (localUploadBlocked) { + showError(uploadBlockedReason); + return; + } + setPending(null); + const plan = planImageUpload({ + kind, + model: selectedModel, + mode, + images, + count: files.length, + rememberedRole: roleMemory[selectedModel.model] || '', + }); + if (plan.type === 'place') { + placeFiles(plan, files); + } else if (plan.type === 'choose') { + setPending({ type: 'choose', files, choices: plan.choices }); + } else { + setPending({ + type: 'unsupported', + files, + suggestion: suggestImageModel( + kind, + models, + selectedModel, + files.length, + ), + }); + } + }, + [ + selectedModel, + localUploadBlocked, + uploadBlockedReason, + kind, + mode, + images, + roleMemory, + placeFiles, + models, + ], + ); + const handleFilesRef = useRef(handleFiles); + handleFilesRef.current = handleFiles; + + const chooseRole = (choice) => { + if (!pending || !selectedModel) return; + const files = pending.files; + setRoleMemory((prev) => + rememberRole(getStorage(), kind, prev, selectedModel.model, choice.role), + ); + setPending(null); + const plan = planImageUpload({ + kind, + model: selectedModel, + mode, + images, + count: files.length, + rememberedRole: choice.role, + }); + if (plan.type === 'place') placeFiles(plan, files); + }; + + // "切换到 X?":只在用户确认后换模型(换模型会改变价格),换完再放图 + const acceptSuggestion = () => { + const target = pending?.suggestion; + if (!target) return; + switchPendingRef.current = { model: target.model, files: pending.files }; + setPending(null); + if (!selectModel(target)) switchPendingRef.current = null; + }; + + useEffect(() => { + const p = switchPendingRef.current; + if (!p || selectedModel?.model !== p.model) return; + switchPendingRef.current = null; + handleFilesRef.current(p.files); + }, [selectedModel]); + + // 视频真人人像认证素材(asset://)放入首帧槽(保留旧视频页能力,方案 §1.3) + const firstFrameRef = String(images.first_frame?.ref || ''); + const portraitRef = firstFrameRef.startsWith('asset://') ? firstFrameRef : ''; + const selectPortrait = (asset) => { + if (!asset?.id) return; + setImageRef('first_frame', undefined, { + ref: `asset://${asset.id}`, + previewUrl: asset.preview_url || null, + source: 'asset', + }); + }; + + const handleRemove = (entry) => { + if (entry.key === 'reference_images' && refMode) { + const next = rewriteImageRefs( + prompt, + mappingAfterRemove(refs.length, entry.index), + ); + if (next !== prompt) setPrompt(next); + } + removeImage(entry.key, entry.index); + }; + + const handleMoveRef = (from, to) => { + if (refMode) { + const next = rewriteImageRefs( + prompt, + mappingAfterMove(refs.length, from, to), + ); + if (next !== prompt) setPrompt(next); + } + setImages({ ...images, reference_images: moveItem(refs, from, to) }); + }; + + const insertRef = (n) => { + const el = promptWrapRef.current?.querySelector('textarea'); + const caret = el ? el.selectionStart : undefined; + const r = insertAt(prompt, caret, imageRefToken(n)); + setPrompt(r.text); + requestAnimationFrame(() => { + const ta = promptWrapRef.current?.querySelector('textarea'); + if (!ta) return; + ta.focus(); + try { + ta.setSelectionRange(r.caret, r.caret); + } catch (e) { + // ignore + } + }); + }; + + const backToI2V = () => { + const r = backToImage2Video(selectedModel, images); + if (!r) return; + setImages(r.images); + setMode(r.mode); + }; + + const onDockDragOver = (e) => { + if (e.dataTransfer?.types?.includes?.('Files')) e.preventDefault(); + }; + const onDockDrop = (e) => { + // 图片槽自己处理过的拖放不再重复放置 + if (e.defaultPrevented || !e.dataTransfer?.files?.length) return; + e.preventDefault(); + handleFiles(e.dataTransfer.files); + }; + const onPromptPaste = (e) => { + const files = Array.from(e.clipboardData?.files || []).filter((f) => + f.type.startsWith('image/'), + ); + if (!files.length) return; + e.preventDefault(); + handleFiles(files); + }; + + const addInputRef = useRef(null); + + // --------------------------------------------------------------------------- + // 模板 / 优化提示词 + // --------------------------------------------------------------------------- + const handleTemplate = (tpl) => { + if (applyTemplate(tpl)) { + showSuccess(t('已套用模板:{{title}}', { title: t(tpl.title) })); + } + }; + + const onPromptFocus = () => { + // 每次进入创作页只记一次 + if (promptFocusedRef.current) return; + promptFocusedRef.current = true; + trackCreationEvent('prompt_focus', { kind }); + }; + + // 错误行的下一步动作 + const runErrorAction = (action) => { + if (action === ERROR_ACTIONS.TOPUP) { + navigate(TOPUP_PATH); + return; + } + if (action === ERROR_ACTIONS.RETRY) { + handleSubmit(); + return; + } + if (action === ERROR_ACTIONS.REPLACE_IMAGE) { + const el = dockRef.current?.querySelector( + '.cs-slot.is-flagged, .cp-slot.is-expired, .cs-slot', + ); + if (el) { + el.focus(); + return; + } + } + focusPrompt(); + }; + + const handleOptimize = async () => { + if (optimizing) return; + if (!prompt.trim()) { + showInfo(t('请先输入提示词')); + return; + } + const modelName = textModels?.[0]?.model_name; + if (!modelName) { + showInfo(t('未配置文本模型,无法 AI 优化。请联系管理员开通文本模型权限')); + return; + } + const result = await optimize(prompt, modelName); + if (result?.content) { + setPrompt(result.content); + showSuccess(t('已优化提示词')); + } else if (result?.error) { + showError(result.error); + } + }; + + // --------------------------------------------------------------------------- + // 渲染 + // --------------------------------------------------------------------------- + if (modelsLoading && !models.length) { + return ( +
+ } + /> +
+ ); + } + if (modelsError && !models.length) { + return ( +
+ {t('模型列表加载失败')} + +
+ ); + } + if (!models.length) { + return ( +
+ {t('当前分组暂无可用模型,请联系管理员开通')} + +
+ ); + } + + const modelPicker = ( + selectModel(m)} + params={params} + mode={mode} + loading={modelsLoading} + error={modelsError} + onRetry={reloadModels} + compare={compare?.supported ? compare : null} + /> + ); + + const generateButton = (collapsedBar) => { + if (allLocked) { + return ( + + ); + } + if (needTopUp && !comparing) { + return ( + + ); + } + // 收起态下被阻断时点击展开,让用户看到原因 + const blocked = Boolean(blockText); + const button = ( + + ); + return blocked && !collapsedBar ? ( + + {button} + + ) : ( + button + ); + }; + + const compareSummary = comparing ? ( + { + if (!compare.submitting) setSummaryOpen(false); + }} + onConfirm={confirmCompare} + /> + ) : null; + + // 收起态:一行提示词 + 模型 chip + 生成 + if (!showExpanded) { + return ( +
+ +
{modelPicker}
+ {generateButton(true)} + {compareSummary} +
+ ); + } + + const slotLabel = (entry) => + entry.labelIndex ? `${t(entry.label)} ${entry.labelIndex}` : t(entry.label); + + const modeChip = + modeOptions.length > 1 ? ( + + {modeOptions.map((o) => ( + { + if (!o.disabled) setMode(o.mode); + }} + > + + {t(modeLabels[o.mode] || o.mode)} + {o.disabled && o.reason ? ( + {t(o.reason)} + ) : null} + + + ))} + + } + > + + + ) : modeOptions.length === 1 ? ( + + {t(modeLabels[mode] || mode)} + + ) : null; + + const pendingBox = pending ? ( +
+ {pending.type === 'choose' ? ( + <> + + {t('已选 {{n}} 张图片,用作:', { n: pending.files.length })} + + {pending.choices.map((c) => ( + + ))} + + ) : ( + <> + + {pending.suggestion + ? t('该模型不支持图片输入,切换到 {{name}}?', { + name: displayNameOf(pending.suggestion), + }) + : t('该模型不支持图片输入,请先选择支持图片的模型')} + + {pending.suggestion ? ( + + ) : null} + + )} + +
+ ) : null; + + const showInputsRow = + modeChip || imageSlots.length || modelAcceptsImages || pending; + + return ( + <> + {compact ? ( + <> +
+
+ + ) : null} +
{ + if (compact && e.key === 'Escape' && !e.defaultPrevented) { + collapse(); + } + }} + > + {compact ? ( +
+ {t('创作')} + +
+ ) : null} + + {showInputsRow ? ( +
+ {modeChip} + {imageSlots.length ? ( +
+ {imageSlots.map((entry) => { + const slot = entry.slot; + const value = slot + ? { + previewUrl: slot.previewUrl, + status: entry.active + ? slot.status || 'ready' + : 'unused', + error: slot.error, + } + : null; + const isMissing = !slot && entry.key === missingFrame; + const isFlagged = Boolean( + slot && + flaggedInput && + entry.key === flaggedInput.key && + (flaggedInput.index === undefined || + entry.index === flaggedInput.index), + ); + const movable = + entry.key === 'reference_images' && slot && entry.index > 0; + return ( +
+ + pickImage(entry.key, entry.index, file) + } + onRemove={() => handleRemove(entry)} + onRetry={() => retryImage(entry.key, entry.index, slot)} + /> + {movable ? ( + + ) : null} +
+ ); + })} +
+ ) : null} + {kind === 'video' && + imageSlots.some((s) => s.key === 'first_frame' && s.active) ? ( +
+ { + if (portraitRef) removeImage('first_frame'); + }} + /> +
+ ) : null} + {modelAcceptsImages && !modeHasImages ? ( + <> + + { + handleFiles(e.target.files); + e.target.value = ''; + }} + /> + + ) : null} + {pendingBox} + {missingFrame ? ( + + {missingFrame === 'last_frame' ? t('缺少尾帧') : t('缺少首帧')} + {canBackToI2V ? ( + + ) : null} + + ) : null} + {hasUnused ? ( + + {t('置灰的图片当前不会提交,切回支持的模型或模式后自动恢复')} + + ) : null} +
+ ) : null} + + {refMode && refs.length ? ( +
+ {t('在提示词中引用:')} + {refs.map((r, i) => ( + + ))} +
+ ) : null} + +
+