/* 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 { LayoutTemplate as ActionLayoutTemplate } from '@/components/common/icons/ActionIcons'; import { Image as TemplateImageIcon } from '@/components/common/icons/ActionIcons'; import { ChevronDown as ActionChevronDown, Lock as ActionLock, Wallet as ActionWallet, ChevronUp as ActionChevronUp, ArrowLeft as ActionArrowLeft, Settings2 as ActionSettings2, History as ActionHistory, MoreHorizontal as ActionMoreHorizontal, X as ActionX, } from '@/components/common/icons/ActionIcons'; 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 '@/components/ui'; import { AlertCircle, Bell, BellOff, Clapperboard, ImagePlus, Lock, Sparkles, Wand2, } 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; } }; /** 估价文案:"预计 ¥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 (!next) onClose(); }} classNames={{ body: `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 : TemplateImageIcon; if (!list.length) return null; return ( setOpen(false)} title={t('灵感模板')} isMobile={isMobile} sheetHeight={sheetHeight(70)} className='cs-templates-pop' trigger={ } > ); }; /** * 底部创作台(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 ? ( ({ key: o.mode, disabled: o.disabled, onClick: () => { if (!o.disabled) setMode(o.mode); }, label: ( {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}