Files
monkey-ai-web/src/components/creation/CreationDock.jsx
T

1676 lines
52 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { 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}
<SideSheet
visible={open}
placement='bottom'
height={sheetHeight}
title={title}
onCancel={onClose}
className={`cs-sheet ${className}`}
closeOnEsc
>
{open ? <div className='cs-pop-body'>{children}</div> : null}
</SideSheet>
</>
);
}
return (
<Popover
open={open}
trigger='click'
position='topLeft'
showArrow={false}
onOpenChange={(next) => {
if (!next) onClose();
}}
classNames={{ body: `cs-popover ${className}` }}
content={
open ? (
<div className='cs-pop-body' role='dialog' aria-label={title}>
{title ? <div className='cs-pop-title'>{title}</div> : null}
{children}
</div>
) : null
}
>
{trigger}
</Popover>
);
};
/** 单个参数 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 (
<DockPopover
open={open}
onClose={() => setOpen(false)}
title={label}
isMobile={isMobile}
trigger={
<button
type='button'
className={[
'app-action-button',
`cs-chip cs-param-chip${open ? ' is-active' : ''}`,
]
.filter(Boolean)
.join(' ')}
aria-haspopup='dialog'
aria-expanded={open}
aria-label={`${label}:${text}`}
title={label}
onClick={() => setOpen((v) => !v)}
>
<span className='cs-chip-text'>{text}</span>
<ActionChevronDown size={12} aria-hidden />
</button>
}
>
{param.type === 'size' ? (
<div className='cs-size'>
<ImageSizePicker
param={param}
value={value}
onChange={(v) => handleChange('size', v)}
/>
</div>
) : (
<ParamRenderer
params={scoped}
values={values}
onChange={handleChange}
placement='dock'
constraints={constraints}
showLabels={false}
/>
)}
</DockPopover>
);
};
/** 模板选择:静态模板,选中后填入提示词并套用推荐参数。 */
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 (
<DockPopover
open={open}
onClose={() => setOpen(false)}
title={t('灵感模板')}
isMobile={isMobile}
sheetHeight={sheetHeight(70)}
className='cs-templates-pop'
trigger={
<button
type='button'
className={[
'app-action-button',
`cs-chip cs-tool${open ? ' is-active' : ''}`,
]
.filter(Boolean)
.join(' ')}
aria-haspopup='dialog'
aria-expanded={open}
onClick={() => setOpen((v) => !v)}
>
<ActionLayoutTemplate size={14} aria-hidden />
<span>{t('模板')}</span>
</button>
}
>
<ul className='cs-templates app-scrollbar'>
{list.map((tpl) => (
<li key={tpl.id}>
<button
type='button'
className='cs-template'
onClick={() => {
onApply(tpl);
setOpen(false);
}}
>
<span className='cs-template-icon' aria-hidden>
<Icon size={18} />
</span>
<span className='cs-template-main'>
<span className='cs-template-title'>{t(tpl.title)}</span>
<span className='cs-template-prompt'>{tpl.prompt}</span>
</span>
</button>
</li>
))}
</ul>
</DockPopover>
);
};
/**
* 底部创作台(WP B-3,方案 §4.1 / §4.3 / §4.4 / §4.6)。
*
* - 桌面(≥ md 且高度 ≥ 800):常驻完整创作台;
* - 移动端与矮屏桌面:收起态(一行提示词 + 模型 chip + 生成,约 56px)/ 展开态(覆盖作品流、
* 不挤压;展开期间隐藏 MobileBottomNav;弹层用底部抽屉;键盘弹起时跟随可视视口)。
*
* @param {{ form: ReturnType<import('../../hooks/creation/useCreationForm').useCreationForm> }} 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 (
<div className='cs-dock' aria-busy='true'>
<Skeleton
active
loading
placeholder={<Skeleton.Paragraph rows={compact ? 1 : 3} />}
/>
</div>
);
}
if (modelsError && !models.length) {
return (
<div className='cs-dock cs-dock--state' role='alert'>
<span>{t('模型列表加载失败')}</span>
<Button size='small' onClick={() => reloadModels()}>
{t('重试')}
</Button>
</div>
);
}
if (!models.length) {
return (
<div className='cs-dock cs-dock--state' role='status'>
<span>{t('当前分组暂无可用模型,请联系管理员开通')}</span>
<Button size='small' onClick={() => navigate(MARKET_PATH)}>
{t('查看可用模型')}
</Button>
</div>
);
}
const modelPicker = (
<ModelPicker
kind={kind}
models={models}
value={selectedModel?.model || ''}
onChange={(m) => selectModel(m)}
params={params}
mode={mode}
loading={modelsLoading}
error={modelsError}
onRetry={reloadModels}
compare={compare?.supported ? compare : null}
/>
);
const generateButton = (collapsedBar) => {
if (allLocked) {
return (
<Button
type='warning'
theme='solid'
icon={<ActionLock size={16} aria-hidden />}
onClick={() => navigate(TOPUP_PATH)}
>
{t('升级')}
</Button>
);
}
if (needTopUp && !comparing) {
return (
<Button
type='warning'
theme='solid'
icon={<ActionWallet size={16} aria-hidden />}
onClick={() => navigate(TOPUP_PATH)}
>
{t('去充值')}
</Button>
);
}
// 收起态下被阻断时点击展开,让用户看到原因
const blocked = Boolean(blockText);
const button = (
<Button
type='primary'
theme='solid'
className={`cs-generate${blocked ? ' is-blocked' : ''}`}
icon={<Sparkles size={16} />}
disabled={blocked && !collapsedBar}
aria-disabled={blocked || undefined}
loading={comparing ? compare.submitting : submitting}
data-guide='generate'
onClick={() => {
if (blocked) {
if (collapsedBar) expand();
return;
}
handleSubmit();
}}
aria-keyshortcuts={SHORTCUT_ARIA}
>
{comparing ? t('对比生成') : t('生成')}
{!collapsedBar ? (
<span className='cs-kbd' aria-hidden>
{SHORTCUT_LABEL}
</span>
) : null}
</Button>
);
return blocked && !collapsedBar ? (
<Tooltip content={blockText} position='top'>
<span className='cs-generate-wrap'>{button}</span>
</Tooltip>
) : (
button
);
};
const compareSummary = comparing ? (
<CompareSummary
visible={summaryOpen}
compare={compare}
onCancel={() => {
if (!compare.submitting) setSummaryOpen(false);
}}
onConfirm={confirmCompare}
/>
) : null;
// 收起态:一行提示词 + 模型 chip + 生成
if (!showExpanded) {
return (
<div className='cs-dock cs-dock--collapsed' ref={dockRef}>
<button
type='button'
className={[
'app-action-button',
`cs-collapsed-prompt${prompt ? '' : ' is-placeholder'}`,
]
.filter(Boolean)
.join(' ')}
data-guide='prompt'
onClick={expand}
aria-label={t('展开创作台')}
aria-expanded='false'
>
<span className='cs-collapsed-text'>
{prompt ||
(kind === 'image'
? t('描述你想要的画面…')
: t('描述你想要的视频画面与运动…'))}
</span>
<ActionChevronUp size={14} aria-hidden />
</button>
<div className='cs-collapsed-model'>{modelPicker}</div>
{generateButton(true)}
{compareSummary}
</div>
);
}
const slotLabel = (entry) =>
entry.labelIndex ? `${t(entry.label)} ${entry.labelIndex}` : t(entry.label);
const modeChip =
modeOptions.length > 1 ? (
<Dropdown
trigger='click'
position='topLeft'
menu={{
selectable: true,
selectedKeys: [mode],
items: modeOptions.map((o) => ({
key: o.mode,
disabled: o.disabled,
onClick: () => {
if (!o.disabled) setMode(o.mode);
},
label: (
<span className='cs-mode-item'>
<span>{t(modeLabels[o.mode] || o.mode)}</span>
{o.disabled && o.reason ? (
<span className='cs-mode-reason'>{t(o.reason)}</span>
) : null}
</span>
),
})),
}}
>
<button
type='button'
className='app-action-button cs-chip cs-mode-chip'
aria-haspopup='menu'
aria-label={t('生成模式:{{mode}}', {
mode: t(modeLabels[mode] || mode),
})}
>
<span>{t(modeLabels[mode] || mode)}</span>
<ActionChevronDown size={12} aria-hidden />
</button>
</Dropdown>
) : modeOptions.length === 1 ? (
<span className='cs-chip cs-mode-chip is-static'>
{t(modeLabels[mode] || mode)}
</span>
) : null;
const pendingBox = pending ? (
<div className='cs-pending' role='group' aria-live='polite'>
{pending.type === 'choose' ? (
<>
<span className='cs-pending-text'>
{t('已选 {{n}} 张图片,用作:', { n: pending.files.length })}
</span>
{pending.choices.map((c) => (
<button
key={c.role}
type='button'
className='cs-chip is-active'
onClick={() => chooseRole(c)}
>
{c.role === ROLE_FRAMES
? c.mode === 'image2video'
? t('作为首帧')
: t('作为首尾帧')
: t('作为参考图')}
</button>
))}
</>
) : (
<>
<span className='cs-pending-text'>
{pending.suggestion
? t('该模型不支持图片输入,切换到 {{name}}?', {
name: displayNameOf(pending.suggestion),
})
: t('该模型不支持图片输入,请先选择支持图片的模型')}
</span>
{pending.suggestion ? (
<button
type='button'
className='cs-chip is-active'
onClick={acceptSuggestion}
>
{t('切换')}
</button>
) : null}
</>
)}
<button
type='button'
className='cs-chip'
onClick={() => setPending(null)}
>
{t('取消')}
</button>
</div>
) : null;
const showInputsRow =
modeChip || imageSlots.length || modelAcceptsImages || pending;
return (
<>
{compact ? (
<>
<div className='cs-dock-placeholder' aria-hidden />
<div
className='cs-dock-scrim'
aria-hidden
onClick={collapse}
role='presentation'
/>
</>
) : null}
<div
ref={dockRef}
className={`cs-dock${compact ? ' is-expanded app-scrollbar' : ''}`}
onDragOver={onDockDragOver}
onDrop={onDockDrop}
onKeyDown={(e) => {
if (compact && e.key === 'Escape' && !e.defaultPrevented) {
collapse();
}
}}
>
{compact ? (
<div className='cs-dock-head'>
<span className='cs-dock-head-title'>{t('创作')}</span>
<button
type='button'
className='app-action-button cs-icon-btn'
onClick={collapse}
aria-label={t('收起创作台')}
>
<ActionChevronDown size={16} aria-hidden />
</button>
</div>
) : null}
{showInputsRow ? (
<div className='cs-dock-row cs-dock-inputs'>
{modeChip}
{imageSlots.length ? (
<div className='cs-slots'>
{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 (
<div
key={`${entry.key}-${entry.index ?? 0}-${slot?.id || 'empty'}`}
className='cs-slot-cell'
>
<ImageSlot
className={`cs-slot${isMissing ? ' is-missing' : ''}${isFlagged ? ' is-flagged' : ''}`}
label={slotLabel(entry)}
value={value}
disabledReason={!slot ? uploadBlockedReason : ''}
hint={isMissing ? '请补充这张图片' : undefined}
onPick={(file) =>
pickImage(entry.key, entry.index, file)
}
onRemove={() => handleRemove(entry)}
onRetry={() => retryImage(entry.key, entry.index, slot)}
/>
{movable ? (
<button
type='button'
className='app-action-button cs-slot-move'
onClick={() =>
handleMoveRef(entry.index, entry.index - 1)
}
aria-label={t('将{{label}}前移', {
label: slotLabel(entry),
})}
title={t('前移')}
>
<ActionArrowLeft size={12} aria-hidden />
</button>
) : null}
</div>
);
})}
</div>
) : null}
{kind === 'video' &&
imageSlots.some((s) => s.key === 'first_frame' && s.active) ? (
<div className='cs-portrait'>
<PortraitAssetPicker
onSelect={selectPortrait}
selectedAssetId={
portraitRef ? portraitRef.slice('asset://'.length) : ''
}
onClearSelection={() => {
if (portraitRef) removeImage('first_frame');
}}
/>
</div>
) : null}
{modelAcceptsImages && !modeHasImages ? (
<>
<button
type='button'
className='app-action-button cs-chip cs-tool'
disabled={localUploadBlocked}
title={uploadBlockedReason || undefined}
onClick={() => addInputRef.current?.click()}
>
<ImagePlus size={14} aria-hidden />
<span>{t('添加图片')}</span>
</button>
<input
ref={addInputRef}
type='file'
accept='image/*'
multiple
className='cs-hidden-input'
tabIndex={-1}
aria-hidden='true'
onChange={(e) => {
handleFiles(e.target.files);
e.target.value = '';
}}
/>
</>
) : null}
{pendingBox}
{missingFrame ? (
<span className='cs-note is-warn' role='note'>
{missingFrame === 'last_frame' ? t('缺少尾帧') : t('缺少首帧')}
{canBackToI2V ? (
<button type='button' className='cs-link' onClick={backToI2V}>
{t('改用图生视频')}
</button>
) : null}
</span>
) : null}
{hasUnused ? (
<span className='cs-note' role='note'>
{t('置灰的图片当前不会提交,切回支持的模型或模式后自动恢复')}
</span>
) : null}
</div>
) : null}
{refMode && refs.length ? (
<div className='cs-dock-row cs-refs' aria-label={t('插入图片引用')}>
<span className='cs-note'>{t('在提示词中引用:')}</span>
{refs.map((r, i) => (
<button
key={r?.id || i}
type='button'
className='cs-ref-token'
onClick={() => insertRef(i + 1)}
>
{imageRefToken(i + 1)}
</button>
))}
</div>
) : null}
<div ref={promptWrapRef} className='cs-prompt-wrap' data-guide='prompt'>
<TextArea
className='cs-prompt'
value={prompt}
onChange={setPrompt}
autosize={{ minRows: 2, maxRows: compact ? 5 : 8 }}
maxCount={4000}
placeholder={
kind === 'image'
? t('描述你想要的画面…')
: t('描述你想要的视频画面与运动…')
}
aria-label={t('提示词')}
aria-keyshortcuts={SHORTCUT_ARIA}
onKeyDown={onPromptKeyDown}
onPaste={onPromptPaste}
onFocus={onPromptFocus}
/>
</div>
<div className='cs-dock-row cs-dock-controls'>
{modelPicker}
{dockParams.map((p) => (
<ParamChip
key={p.key}
param={p}
params={chipParams}
values={chipValues}
onChange={onChipChange}
constraints={chipConstraints}
isMobile={isMobile}
/>
))}
{hasAdvanced ? (
<DockPopover
open={advancedOpen}
onClose={() => setAdvancedOpen(false)}
title={t('高级设置')}
isMobile={isMobile}
sheetHeight={sheetHeight(70)}
className='cs-advanced-pop'
trigger={
<button
type='button'
className={[
'app-action-button',
`cs-chip${advancedOpen ? ' is-active' : ''}`,
]
.filter(Boolean)
.join(' ')}
aria-haspopup='dialog'
aria-expanded={advancedOpen}
onClick={() => setAdvancedOpen((v) => !v)}
>
<ActionSettings2 size={14} aria-hidden />
{t('高级')}
</button>
}
>
<ParamRenderer
params={chipParams}
values={chipValues}
onChange={onChipChange}
placement='advanced'
constraints={chipConstraints}
/>
</DockPopover>
) : null}
<span className='cs-dock-spacer' aria-hidden />
{promptHistory.length ? (
<Dropdown
trigger='click'
position='topRight'
menu={{
items: [
{
type: 'group',
key: 'prompt-history',
label: t('最近使用的提示词'),
children: promptHistory.map((item) => ({
key: item,
label: (
<span className='cs-history-item' title={item}>
{item}
</span>
),
onClick: () => {
setPrompt(item);
requestAnimationFrame(focusPrompt);
},
})),
},
],
}}
>
<button
type='button'
className='app-action-button cs-chip cs-tool'
aria-haspopup='menu'
title={t('提示词历史')}
>
<ActionHistory size={14} aria-hidden />
<span>{t('历史')}</span>
</button>
</Dropdown>
) : null}
<TemplatePicker
kind={kind}
isMobile={isMobile}
onApply={handleTemplate}
/>
<button
type='button'
className='app-action-button cs-chip cs-tool'
onClick={handleOptimize}
aria-busy={optimizing || undefined}
title={
textModels?.length
? t('AI 优化提示词 (使用 {{m}})', {
m: textModels[0].model_name,
})
: t('AI 优化提示词')
}
>
<Wand2
size={14}
aria-hidden
className={optimizing ? 'cs-pulse' : ''}
/>
<span>{optimizing ? t('优化中...') : t('优化')}</span>
</button>
{notify.supported ? (
<Dropdown
trigger='click'
position='topRight'
render={
<Dropdown.Menu>
<Dropdown.Item
icon={
notify.enabled ? (
<BellOff size={14} aria-hidden />
) : (
<Bell size={14} aria-hidden />
)
}
onClick={() => {
const next = !notify.enabled;
setNotifyEnabled(next);
if (next && notify.permission === 'denied') {
showInfo(
t('浏览器已禁止本站通知,请在浏览器设置中允许后再试'),
);
} else if (next) {
showSuccess(
t(
'已开启:生成完成后发送浏览器通知(需保持标签页打开)',
),
);
}
}}
>
{notify.enabled ? t('关闭完成通知') : t('完成后浏览器通知')}
</Dropdown.Item>
</Dropdown.Menu>
}
>
<button
type='button'
className='app-action-button cs-chip cs-tool cs-icon-chip'
aria-haspopup='menu'
aria-label={t('更多')}
title={t('更多')}
>
<ActionMoreHorizontal size={14} aria-hidden />
{notify.enabled ? (
<span className='cs-dot' aria-hidden />
) : null}
</button>
</Dropdown>
) : null}
</div>
{allLocked ? (
<div className='cs-dock-row cs-alert is-warn' role='note'>
<Lock size={14} aria-hidden />
<span className='cs-alert-text'>
{t('当前等级暂无可用模型,升级后即可使用')}
</span>
</div>
) : null}
{orgShortfall ? (
<div className='cs-dock-row cs-alert is-warn' role='note'>
<AlertCircle size={14} aria-hidden />
<span className='cs-alert-text'>
{t('{{budget}},提交可能失败,请联系企业管理员', {
budget: t(orgShortfall.labelKey),
})}
</span>
</div>
) : null}
{adjustments?.length ? (
<div className='cs-dock-row cs-alert' role='status'>
<span className='cs-alert-text'>
{t('已按当前模型调整:{{list}}', {
list: adjustments.join(';'),
})}
</span>
<button
type='button'
className='app-action-button cs-icon-btn'
onClick={clearAdjustments}
aria-label={t('关闭提示')}
>
<ActionX size={14} aria-hidden />
</button>
</div>
) : null}
{lastError ? (
<div className='cs-dock-row cs-alert is-error' role='alert'>
<AlertCircle size={14} aria-hidden />
<span className='cs-alert-text'>
<strong>{lastError.title}</strong>
{lastError.detail ? <span>{lastError.detail}</span> : null}
</span>
{lastError.actionLabel ? (
<Button
size='small'
type={
lastError.action === ERROR_ACTIONS.TOPUP
? 'warning'
: 'tertiary'
}
onClick={() => runErrorAction(lastError.action)}
>
{lastError.actionLabel}
</Button>
) : null}
<button
type='button'
className='app-action-button cs-icon-btn'
onClick={clearError}
aria-label={t('关闭提示')}
>
<ActionX size={14} aria-hidden />
</button>
</div>
) : null}
<div className='cs-dock-row cs-dock-submit'>
<span className='cs-price' aria-live='polite'>
{blockText ? (
<span className='cs-block'>{blockText}</span>
) : (
priceText
)}
</span>
{generateButton(false)}
</div>
</div>
{compareSummary}
</>
);
};
export default CreationDock;