sync: 同步总仓库 luoguang/monkey-ai weiyuan@bfdfb339 的 web/ 改动

同步基准:总仓库 a2ca13cb(= 本仓库初始导入 d8f3aee2)
范围:a2ca13cb..bfdfb339 中触及 web/ 的提交(不含 web/.claude/settings.local.json)

- 8490ac02 feat(aliyun): integrate Wan 3 and Qwen Image models
- 2aff08ec perf(analytics): 运营看板概览改读汇总表,首屏从 19s 降到 0.4s
- dc69335e feat(experience): 体验中心图像/视频创作升级(能力 schema、估价、新创作台)
- b059c657 fix(org): 下线 /org/create 自助加入企业页与 POST /api/org/join
- 4fcf47e6 fix(i18n): 修复中/英/韩/繁体多语言错乱,补齐日/越/泰译文
- e4c301d5 fix: merge enterprise task record date filters
- c9369b95 feat: expose enterprise image and video task records
- a410fee5 feat(claude): 无断点请求自动注入 cache_control 断点(方案 2)
- 521b3376 feat(claude): 缓存命中率优化——上游粘性路由 + 缓存时长强制改写
- 73b615dd feat(pricing): 企业成员不论登录身份均按所属企业等级计价与扣费
- f73f55c3 feat(client): 新增 WeyAi 版本说明管理与公开读取接口
- 8cdf1994 fix(topup): reset amount when switching from PayPal
- 93a4ac34 feat(baidu): configure Seedance liveness header by channel
- cb1818c5 fix(weyai): 按评审修正内容清理竞态、默认适用端与中文退回(M21)
- 04214d83 feat(weyai): WeyAi 内容管理与客户端内容接口(M21 第二部分)
- e3c4a57c feat(weyai): 设置页新增 WeyAi 页签与内容专用 COS 桶(M21 第一部分)
- b5ee8e70 fix(auth): 会话角色/状态以 DB 为准,修复提升管理员后管理接口报权限不足
- e4618fc2 fix: 修复企业看板日志聚合死循环导致 CPU 打满,并降低看板查询开销
- 584aad52 style(web): 个人中心侧边栏按 prettier 换行
- b8d87064 fix: 小程序教程隐藏充值后保留原步骤编号,企业充值判断直接用 isMiniProgramWebView
- eee7f5b2 fix: 小程序里企业首页不落到充值页,隐藏钱包入口与教程充值步骤
- 8b254d49 fix: 小程序里隐藏企业充值入口与页面
- a67661b4 fix(web): 小程序里个人中心默认页跳过充值和发票,避免来回跳转
- cff6c543 feat(web): WeyAi 小程序里打开个人中心时不出现充值和开票
- c6c99eb6 feat(billing): Claude 全部缓存写入统一按 1h 倍率计费
- 0699d1bf fix(web): 小程序 web-view 里注册页同样只显示站内方式
- 04853331 feat(web): WeyAi 小程序 web-view 里登录页只显示站内登录方式
This commit is contained in:
qiubaishen
2026-11-10 11:05:34 +08:00
parent d8f3aee261
commit 6160a23117
275 changed files with 38656 additions and 7694 deletions
@@ -0,0 +1,53 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import { useTranslation } from 'react-i18next';
import OptionGroup from './OptionGroup';
import { optionLabel, paramLabel } from './labels';
/**
* 胶囊单选(schema type = 'chips'),如分辨率、画质。
* props: { param, value, onChange(value), optionDisabledReasons?, disabledReason? }
*/
const ChipGroup = ({
param,
value,
onChange,
optionDisabledReasons,
disabledReason,
}) => {
const { t } = useTranslation();
return (
<OptionGroup
variant='chips'
options={param?.options || []}
value={value}
onChange={onChange}
ariaLabel={paramLabel(t, param)}
optionDisabledReasons={optionDisabledReasons}
disabledReason={disabledReason}
renderOption={(opt) => (
<span className='cp-option-label'>{optionLabel(t, param, opt)}</span>
)}
/>
);
};
export default ChipGroup;
@@ -0,0 +1,58 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import { useTranslation } from 'react-i18next';
import OptionGroup from './OptionGroup';
import { optionValue } from './constraints';
import { optionLabel, paramLabel } from './labels';
/**
* 分段选择(schema type = 'segmented'),主要用于时长,按 unit 显示"5s"。
* props: { param, value, onChange(value), optionDisabledReasons?, disabledReason? }
*/
const DurationSegmented = ({
param,
value,
onChange,
optionDisabledReasons,
disabledReason,
}) => {
const { t } = useTranslation();
const unitWord = param?.unit === 's' ? t('秒') : param?.unit || '';
return (
<OptionGroup
variant='segmented'
options={param?.options || []}
value={value}
onChange={onChange}
ariaLabel={paramLabel(t, param)}
optionDisabledReasons={optionDisabledReasons}
disabledReason={disabledReason}
getOptionAriaLabel={(opt) => `${optionValue(opt)} ${unitWord}`.trim()}
renderOption={(opt) => (
<span className='cp-option-label tabular-nums'>
{optionLabel(t, param, opt)}
</span>
)}
/>
);
};
export default DurationSegmented;
@@ -0,0 +1,252 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useRef, useState } from 'react';
import { Spin, Tooltip } from '@douyinfe/semi-ui';
import { ImagePlus, RotateCcw, X } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import './creation-params.css';
const pickImageFile = (files, accept) => {
const list = Array.from(files || []);
if (!accept || accept === '*') return list[0] || null;
const wantsImage = accept.includes('image/');
return (
list.find((f) => (wantsImage ? f.type.startsWith('image/') : true)) || null
);
};
/**
* 带标签的单张图片槽(首帧 / 尾帧 / 参考图)。纯展示:上传逻辑由父组件在 onPick 中完成,
* 并通过 value.status 回传状态。
*
* props:
* label 槽位名称(已翻译或 i18n key,均会过 t())
* value { previewUrl?, status: 'uploading'|'ready'|'error'|'expired'|'unused', error? } | null
* onPick(file) 选择 / 拖入 / 粘贴图片
* onRemove() 移除
* onRetry() 上传失败后重试
* disabledReason 非空时整个槽位禁用,并以 Tooltip 说明原因
* accept 默认 'image/*'
* hint 空态下的辅助说明
*/
const ImageSlot = ({
label,
value,
onPick,
onRemove,
onRetry,
disabledReason = '',
accept = 'image/*',
hint,
className = '',
}) => {
const { t } = useTranslation();
const inputRef = useRef(null);
const [dragOver, setDragOver] = useState(false);
const status = value ? value.status || 'ready' : 'empty';
const disabled = Boolean(disabledReason);
const labelText = label ? t(label) : t('图片');
// 可以(重新)选择图片的状态
const canPick =
!disabled &&
(status === 'empty' || status === 'expired' || status === 'error');
const canDrop = !disabled && status !== 'uploading' && status !== 'unused';
const openPicker = () => {
if (canPick && inputRef.current) inputRef.current.click();
};
const handleFile = (file) => {
if (file && onPick) onPick(file);
};
const onInputChange = (e) => {
handleFile(pickImageFile(e.target.files, accept));
e.target.value = '';
};
const onDragOver = (e) => {
if (!canDrop) return;
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
if (!dragOver) setDragOver(true);
};
const onDragLeave = (e) => {
if (e.currentTarget.contains(e.relatedTarget)) return;
setDragOver(false);
};
const onDrop = (e) => {
setDragOver(false);
if (!canDrop) return;
e.preventDefault();
handleFile(pickImageFile(e.dataTransfer.files, accept));
};
const onPaste = (e) => {
if (!canDrop) return;
const file = pickImageFile(
e.clipboardData && e.clipboardData.files,
accept,
);
if (file) {
e.preventDefault();
handleFile(file);
}
};
const onKeyDown = (e) => {
if (e.target !== e.currentTarget) return;
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
openPicker();
}
};
const statusText = {
empty: t('点击、拖入或粘贴图片'),
uploading: t('上传中'),
ready: '',
error: (value && value.error) || t('上传失败'),
expired: t('原图已失效'),
unused: t('当前模型不使用'),
}[status];
const preview =
value && value.previewUrl && status !== 'expired' ? (
<img
className='cp-slot-img'
src={value.previewUrl}
alt={labelText}
draggable={false}
/>
) : null;
const ariaLabel = [
labelText,
disabled ? disabledReason : statusText,
canPick ? t('按回车选择图片') : '',
]
.filter(Boolean)
.join(',');
const slot = (
<div
className={`cp-slot is-${status}${dragOver ? ' is-dragover' : ''}${
disabled ? ' is-disabled' : ''
} ${className}`}
role={canPick ? 'button' : 'group'}
tabIndex={0}
aria-label={ariaLabel}
aria-disabled={disabled || undefined}
aria-busy={status === 'uploading' || undefined}
onClick={canPick ? openPicker : undefined}
onKeyDown={onKeyDown}
onDragOver={onDragOver}
onDragLeave={onDragLeave}
onDrop={onDrop}
onPaste={onPaste}
>
<input
ref={inputRef}
type='file'
accept={accept}
className='cp-slot-input'
tabIndex={-1}
aria-hidden='true'
onChange={onInputChange}
/>
{preview}
{status === 'empty' || status === 'expired' ? (
<div className='cp-slot-empty'>
<ImagePlus size={20} aria-hidden='true' />
<span className='cp-slot-status'>{statusText}</span>
{status === 'empty' && hint ? (
<span className='cp-slot-hint'>{t(hint)}</span>
) : null}
{status === 'expired' ? (
<span className='cp-slot-hint'>{t('请重新上传')}</span>
) : null}
</div>
) : null}
{status === 'uploading' ? (
<div className='cp-slot-overlay'>
<Spin size='small' />
<span className='cp-slot-status'>{statusText}</span>
</div>
) : null}
{status === 'error' ? (
<div className='cp-slot-overlay is-error'>
<span className='cp-slot-status'>{statusText}</span>
{onRetry ? (
<button
type='button'
className='cp-slot-action'
onClick={(e) => {
e.stopPropagation();
onRetry();
}}
>
<RotateCcw size={14} aria-hidden='true' />
<span>{t('重试')}</span>
</button>
) : null}
</div>
) : null}
{status === 'unused' ? (
<span className='cp-slot-badge'>{statusText}</span>
) : null}
{status !== 'empty' && onRemove && !disabled ? (
<button
type='button'
className='cp-slot-remove'
aria-label={t('移除{{label}}', { label: labelText })}
title={t('移除')}
onClick={(e) => {
e.stopPropagation();
onRemove();
}}
>
<X size={14} aria-hidden='true' />
</button>
) : null}
<span className='cp-slot-label'>{labelText}</span>
</div>
);
return disabled ? (
<Tooltip content={disabledReason} position='top'>
{slot}
</Tooltip>
) : (
slot
);
};
export default ImageSlot;
@@ -0,0 +1,155 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useRef } from 'react';
import { Tooltip } from '@douyinfe/semi-ui';
import { optionKey, optionValue } from './constraints';
import './creation-params.css';
/**
* 通用单选按钮组(radiogroup 语义 + roving tabindex),供 RatioPicker /
* ChipGroup / DurationSegmented 复用。
*
* - 方向键在可用选项间移动并选中,Home / End 跳到首尾;
* - 被禁用的选项用 aria-disabled(而非 disabled),以便悬停 / 聚焦时仍能看到原因 Tooltip;
* - 整组禁用(disabledReason)时所有选项不可选,原因挂在组外层 Tooltip 上。
*/
const OptionGroup = ({
options = [],
value,
onChange,
ariaLabel,
optionDisabledReasons = {},
disabledReason = '',
renderOption,
getOptionAriaLabel,
variant = 'chips',
className = '',
}) => {
const refs = useRef([]);
const groupDisabled = Boolean(disabledReason);
const selectedKey =
value === undefined || value === null ? null : optionKey(value);
const isDisabled = (opt) =>
groupDisabled || Boolean(optionDisabledReasons[optionKey(opt)]);
const selectedIndex = options.findIndex((o) => optionKey(o) === selectedKey);
const firstEnabled = options.findIndex((o) => !isDisabled(o));
const tabStop =
selectedIndex >= 0 ? selectedIndex : firstEnabled >= 0 ? firstEnabled : 0;
const select = (opt) => {
if (isDisabled(opt)) return;
if (optionKey(opt) === selectedKey) return;
onChange && onChange(optionValue(opt));
};
const moveTo = (from, step) => {
const n = options.length;
for (let i = 1; i <= n; i += 1) {
const idx = (from + step * i + n * n) % n;
if (!isDisabled(options[idx])) {
refs.current[idx] && refs.current[idx].focus();
select(options[idx]);
return;
}
}
};
const onKeyDown = (e, idx) => {
switch (e.key) {
case 'ArrowRight':
case 'ArrowDown':
e.preventDefault();
moveTo(idx, 1);
break;
case 'ArrowLeft':
case 'ArrowUp':
e.preventDefault();
moveTo(idx, -1);
break;
case 'Home':
e.preventDefault();
moveTo(-1, 1);
break;
case 'End':
e.preventDefault();
moveTo(options.length, -1);
break;
default:
}
};
const group = (
<div
role='radiogroup'
aria-label={ariaLabel}
aria-disabled={groupDisabled || undefined}
className={`cp-option-group cp-option-group--${variant} ${className}`}
>
{options.map((opt, idx) => {
const key = optionKey(opt);
const selected = key === selectedKey;
const reason = groupDisabled ? '' : optionDisabledReasons[key] || '';
const disabled = isDisabled(opt);
const btn = (
<button
key={key}
ref={(el) => {
refs.current[idx] = el;
}}
type='button'
role='radio'
aria-checked={selected}
aria-disabled={disabled || undefined}
aria-label={
getOptionAriaLabel ? getOptionAriaLabel(opt) : undefined
}
tabIndex={idx === tabStop ? 0 : -1}
className={`cp-option${selected ? ' is-selected' : ''}${
disabled ? ' is-disabled' : ''
}`}
onClick={() => select(opt)}
onKeyDown={(e) => onKeyDown(e, idx)}
>
{renderOption ? renderOption(opt, { selected, disabled }) : key}
</button>
);
return reason ? (
<Tooltip key={key} content={reason} position='top'>
{btn}
</Tooltip>
) : (
btn
);
})}
</div>
);
return groupDisabled ? (
<Tooltip content={disabledReason} position='top'>
{group}
</Tooltip>
) : (
group
);
};
export default OptionGroup;
@@ -0,0 +1,152 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import RatioPicker from './RatioPicker';
import ChipGroup from './ChipGroup';
import DurationSegmented from './DurationSegmented';
import ParamSwitch from './ParamSwitch';
import ParamSelect from './ParamSelect';
import ParamTextArea from './ParamTextArea';
import ParamSlider from './ParamSlider';
import SeedInput from './SeedInput';
import { applyConstraints, optionKey } from './constraints';
import { formatConstraintReason, paramLabel } from './labels';
import './creation-params.css';
/** schema type → 控件。未知 type 不渲染(前向兼容后端新增类型)。 */
export const PARAM_CONTROLS = {
ratio: RatioPicker,
chips: ChipGroup,
segmented: DurationSegmented,
switch: ParamSwitch,
select: ParamSelect,
textarea: ParamTextArea,
slider: ParamSlider,
seed: SeedInput,
};
const INLINE_TYPES = new Set(['switch']);
/**
* schema 驱动的参数渲染器(纯展示,不发请求)。
*
* props:
* params schema.params[]
* values { [key]: value }
* onChange(key, value)
* placement 'dock' | 'advanced':只渲染 placement 匹配的参数(hidden 永不渲染;
* 缺省 placement 视为 'dock')
* constraints schema.constraints[],命中时禁用选项并在控件下说明原因
* disabledReasons { [key]: string } 整个参数禁用的原因(如"当前模式不支持")
* showLabels 默认 true
* className
*/
const ParamRenderer = ({
params = [],
values = {},
onChange,
placement = 'dock',
constraints = [],
disabledReasons = {},
showLabels = true,
className = '',
}) => {
const { t } = useTranslation();
const visible = useMemo(
() =>
(params || []).filter(
(p) =>
p &&
p.key &&
PARAM_CONTROLS[p.type] &&
(p.placement || 'dock') !== 'hidden' &&
(p.placement || 'dock') === placement,
),
[params, placement],
);
const { disabledOptions, reasons } = useMemo(
() => applyConstraints(values, constraints, params),
[values, constraints, params],
);
if (visible.length === 0) return null;
return (
<div
className={`creation-params cp-renderer cp-renderer--${placement} ${className}`}
>
{visible.map((param) => {
const Control = PARAM_CONTROLS[param.type];
const dis = disabledOptions[param.key] || {};
const optionDisabledReasons = {};
Object.keys(dis).forEach((k) => {
optionDisabledReasons[k] = formatConstraintReason(
t,
dis[k],
param,
params,
);
});
const wholeReason = disabledReasons[param.key]
? t(disabledReasons[param.key])
: '';
const paramReasons = reasons[param.key] || [];
const currentInvalid = Boolean(dis[optionKey(values[param.key])]);
// 有选项被约束禁用、当前值不合法或无选项参数被约束时,在控件下方给出说明
const hint =
!wholeReason &&
paramReasons.length > 0 &&
(Object.keys(dis).length > 0 || currentInvalid || !param.options)
? formatConstraintReason(t, paramReasons[0], param, params)
: '';
const label = paramLabel(t, param);
const inline = INLINE_TYPES.has(param.type);
return (
<div
key={param.key}
className={`cp-row${inline ? ' cp-row--inline' : ''}`}
data-param={param.key}
>
{showLabels ? <div className='cp-row-label'>{label}</div> : null}
<div className='cp-row-control'>
<Control
param={param}
value={values[param.key]}
onChange={(v) => onChange && onChange(param.key, v)}
optionDisabledReasons={optionDisabledReasons}
disabledReason={wholeReason}
/>
</div>
{hint ? (
<div className='cp-row-hint' role='note'>
{hint}
</div>
) : null}
</div>
);
})}
</div>
);
};
export default ParamRenderer;
@@ -0,0 +1,107 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useMemo } from 'react';
import { Select, Tooltip } from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import { optionKey, optionValue } from './constraints';
import { optionLabel, paramLabel } from './labels';
import './creation-params.css';
/**
* 下拉选择(schema type = 'select'),也用于运镜预设:
* options 可为原始值,或 { value, label, description } 对象(description 作为说明文字显示)。
* 被约束禁用的选项置灰,并以说明行展示原因(下拉内不依赖 Tooltip,键盘用户同样可见)。
*
* props: { param, value, onChange(value), optionDisabledReasons?, disabledReason? }
*/
const ParamSelect = ({
param,
value,
onChange,
optionDisabledReasons = {},
disabledReason,
}) => {
const { t } = useTranslation();
const options = useMemo(() => param?.options || [], [param]);
const optionList = useMemo(
() =>
options.map((opt) => {
const reason = optionDisabledReasons[optionKey(opt)] || '';
const desc =
opt && typeof opt === 'object' && opt.description
? t(opt.description)
: '';
const text = optionLabel(t, param, opt);
return {
value: optionValue(opt),
disabled: Boolean(reason),
showTick: true,
label: (
<span className='cp-select-option'>
<span className='cp-select-option-label'>{text}</span>
{reason || desc ? (
<span className='cp-select-option-desc'>{reason || desc}</span>
) : null}
</span>
),
};
}),
[options, optionDisabledReasons, param, t],
);
// 选项可能是数字,取值可能是字符串:映射到选项的规范值,保证 Select 能命中
const hit = options.find((o) => optionKey(o) === optionKey(value));
const current = hit !== undefined ? optionValue(hit) : undefined;
const sel = (
<Select
className='cp-select'
size='small'
value={current}
optionList={optionList}
disabled={Boolean(disabledReason)}
onChange={(v) => onChange && onChange(v)}
aria-label={paramLabel(t, param)}
placeholder={t('请选择')}
dropdownClassName='cp-select-dropdown'
renderSelectedItem={(item) =>
item && item.value !== undefined
? optionLabel(
t,
param,
options.find((o) => optionKey(o) === optionKey(item.value)) ??
item.value,
)
: ''
}
/>
);
return disabledReason ? (
<Tooltip content={disabledReason} position='top'>
<span className='cp-inline-trigger cp-inline-trigger--block'>{sel}</span>
</Tooltip>
) : (
sel
);
};
export default ParamSelect;
@@ -0,0 +1,61 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import { Slider, Tooltip } from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import { paramLabel } from './labels';
import './creation-params.css';
/**
* 滑块(schema type = 'slider'):param.min / max / step / unit。
* props: { param, value, onChange(number), disabledReason? }
*/
const ParamSlider = ({ param, value, onChange, disabledReason }) => {
const { t } = useTranslation();
const min = typeof param?.min === 'number' ? param.min : 0;
const max = typeof param?.max === 'number' ? param.max : 100;
const step = typeof param?.step === 'number' ? param.step : 1;
const v = typeof value === 'number' ? value : (param?.default ?? min);
const unit = param?.unit || '';
const body = (
<div className='cp-slider'>
<Slider
min={min}
max={max}
step={step}
value={v}
disabled={Boolean(disabledReason)}
onChange={(n) => onChange && onChange(n)}
tipFormatter={(n) => `${n}${unit}`}
aria-label={paramLabel(t, param)}
/>
<span className='cp-slider-value tabular-nums'>{`${v}${unit}`}</span>
</div>
);
return disabledReason ? (
<Tooltip content={disabledReason} position='top'>
{body}
</Tooltip>
) : (
body
);
};
export default ParamSlider;
@@ -0,0 +1,51 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import { Switch, Tooltip } from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import { paramLabel } from './labels';
import './creation-params.css';
/**
* 开关(schema type = 'switch'),如生成音频、水印、智能扩写。
* props: { param, value, onChange(boolean), disabledReason? }
*/
const ParamSwitch = ({ param, value, onChange, disabledReason }) => {
const { t } = useTranslation();
const sw = (
<Switch
size='small'
checked={Boolean(value)}
disabled={Boolean(disabledReason)}
onChange={(checked) => onChange && onChange(checked)}
aria-label={paramLabel(t, param)}
className='cp-switch'
/>
);
return disabledReason ? (
<Tooltip content={disabledReason} position='top'>
<span className='cp-inline-trigger'>{sw}</span>
</Tooltip>
) : (
sw
);
};
export default ParamSwitch;
@@ -0,0 +1,56 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import { TextArea, Tooltip } from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import { paramLabel } from './labels';
import './creation-params.css';
/**
* 多行文本(schema type = 'textarea'),如反向提示词。
* props: { param, value, onChange(string), disabledReason? };param.max_length 限制字数。
*/
const ParamTextArea = ({ param, value, onChange, disabledReason }) => {
const { t } = useTranslation();
const max =
Number(param?.max_length) > 0 ? Number(param.max_length) : undefined;
const area = (
<TextArea
className='cp-textarea app-scrollbar'
value={value ?? ''}
onChange={(v) => onChange && onChange(v)}
maxCount={max}
maxLength={max}
autosize={{ minRows: 2, maxRows: 5 }}
disabled={Boolean(disabledReason)}
aria-label={paramLabel(t, param)}
placeholder={param?.placeholder ? t(param.placeholder) : ''}
/>
);
return disabledReason ? (
<Tooltip content={disabledReason} position='top'>
<span className='cp-inline-trigger cp-inline-trigger--block'>{area}</span>
</Tooltip>
) : (
area
);
};
export default ParamTextArea;
@@ -0,0 +1,78 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import { useTranslation } from 'react-i18next';
import OptionGroup from './OptionGroup';
import { optionValue, parseRatio } from './constraints';
import { optionLabel, paramLabel } from './labels';
const BOX = 18;
const MIN_SIDE = 5;
/** 按宽高比绘制的小矩形图标(尺寸来自数值计算,颜色走 CSS token)。 */
export const RatioShape = ({ ratio }) => {
const r = parseRatio(ratio);
let w = BOX;
let h = BOX;
if (!Number.isNaN(r) && r > 0) {
if (r >= 1) h = Math.max(MIN_SIDE, Math.round(BOX / r));
else w = Math.max(MIN_SIDE, Math.round(BOX * r));
}
return (
<span className='cp-ratio-shape-box' aria-hidden='true'>
<span className='cp-ratio-shape' style={{ width: w, height: h }} />
</span>
);
};
/**
* 比例选择(schema type = 'ratio')。
* props: { param, value, onChange(value), optionDisabledReasons?, disabledReason? }
*/
const RatioPicker = ({
param,
value,
onChange,
optionDisabledReasons,
disabledReason,
}) => {
const { t } = useTranslation();
return (
<OptionGroup
variant='ratio'
options={param?.options || []}
value={value}
onChange={onChange}
ariaLabel={paramLabel(t, param)}
optionDisabledReasons={optionDisabledReasons}
disabledReason={disabledReason}
renderOption={(opt) => (
<>
<RatioShape ratio={optionValue(opt)} />
<span className='cp-option-label tabular-nums'>
{optionLabel(t, param, opt)}
</span>
</>
)}
/>
);
};
export default RatioPicker;
@@ -0,0 +1,104 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useRef } from 'react';
import { InputNumber, Switch, Tooltip } from '@douyinfe/semi-ui';
import { Dices } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { paramLabel } from './labels';
import './creation-params.css';
const DEFAULT_MAX_SEED = 2147483647;
export const isRandomSeed = (v) =>
v === undefined || v === null || v === '' || Number.isNaN(Number(v));
export const randomSeed = (max = DEFAULT_MAX_SEED) =>
Math.floor(Math.random() * (max + 1));
/**
* 随机种子(schema type = 'seed')。
* 取值约定:null / undefined → 随机(不传给后端);整数 → 锁定该种子。
* props: { param, value, onChange(number|null), disabledReason? }
*/
const SeedInput = ({ param, value, onChange, disabledReason }) => {
const { t } = useTranslation();
const min = typeof param?.min === 'number' ? param.min : 0;
const max = typeof param?.max === 'number' ? param.max : DEFAULT_MAX_SEED;
const random = isRandomSeed(value);
const lastLocked = useRef(random ? null : Number(value));
if (!random) lastLocked.current = Number(value);
const disabled = Boolean(disabledReason);
const label = paramLabel(t, param);
const emit = (v) => onChange && onChange(v);
const body = (
<div className='cp-seed' role='group' aria-label={label}>
<label className='cp-seed-toggle'>
<Switch
size='small'
checked={random}
disabled={disabled}
aria-label={t('随机种子开关')}
onChange={(checked) => {
if (checked) emit(null);
else emit(lastLocked.current ?? randomSeed(max));
}}
/>
<span className='cp-seed-toggle-text'>{t('随机')}</span>
</label>
<InputNumber
className='cp-seed-input tabular-nums'
size='small'
min={min}
max={max}
precision={0}
hideButtons
value={random ? undefined : Number(value)}
placeholder={t('随机')}
disabled={disabled || random}
aria-label={t('种子数值')}
onNumberChange={(n) => {
if (typeof n === 'number' && !Number.isNaN(n)) emit(n);
}}
/>
<button
type='button'
className='cp-icon-btn'
disabled={disabled}
aria-label={t('随机生成一个种子并锁定')}
title={t('随机生成一个种子并锁定')}
onClick={() => emit(randomSeed(max))}
>
<Dices size={16} aria-hidden='true' />
</button>
</div>
);
return disabledReason ? (
<Tooltip content={disabledReason} position='top'>
{body}
</Tooltip>
) : (
body
);
};
export default SeedInput;
@@ -0,0 +1,300 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
// 创作参数 schema 的纯函数工具(无 React / 无 i18n 依赖,可直接 node --test)。
//
// schema 约定见 docs/11-前端与体验中心/12-体验中心图像与视频生成升级改造方案.md §3.1:
// params[]: { key, type, options?, default?, unit?, placement?, min?, max?, step?, modes? }
// constraints[]: { when: { [key]: value | value[] }, limit: { [key]: allowedValue[] }, message? }
/** 选项的规范化 key:数字 5 与字符串 "5" 视为同一选项。 */
export function optionKey(v) {
if (v && typeof v === 'object' && 'value' in v) return String(v.value);
return String(v);
}
/**
* 参数是否适用于当前生成模式:schema 参数可带 modes: string[](缺省 / 空数组 = 所有模式)。
* 不适用的参数不渲染、不提交(如 gpt-image 的 background 只在文生图可用,图生图不可用)。
* mode 为空时不过滤。
*/
export function paramSupportsMode(param, mode) {
if (!param || !mode) return true;
const modes = param.modes;
if (!Array.isArray(modes) || modes.length === 0) return true;
return modes.includes(mode);
}
/** 按当前模式过滤参数列表(见 paramSupportsMode)。 */
export function paramsForMode(params, mode) {
return (params || []).filter((p) => paramSupportsMode(p, mode));
}
/** 选项的取值(兼容 { value, label } 对象形式的选项)。 */
export function optionValue(v) {
if (v && typeof v === 'object' && 'value' in v) return v.value;
return v;
}
function matchesWhen(values, when) {
if (!when || typeof when !== 'object') return false;
const entries = Object.entries(when);
if (entries.length === 0) return false;
return entries.every(([k, expected]) => {
const actual = values ? values[k] : undefined;
if (actual === undefined || actual === null) return false;
if (Array.isArray(expected)) {
return expected.some((e) => optionKey(e) === optionKey(actual));
}
return optionKey(expected) === optionKey(actual);
});
}
/**
* 根据当前取值计算被约束禁用的选项。
*
* @param {Record<string, any>} values 当前参数取值
* @param {Array<{when:object, limit:object, message?:string}>} constraints
* @param {Array<{key:string, options?:any[]}>} [params] 传入时才能算出"被禁用的具体选项";
* 不传时只返回 allowed 白名单与 reasons。
* @returns {{
* disabledOptions: Record<string, Record<string, {when:object, allowed:any[], message?:string}>>,
* allowed: Record<string, any[]>,
* reasons: Record<string, Array<{when:object, allowed:any[], message?:string}>>,
* }}
* - disabledOptions[key][optionKey] → 禁用原因(命中的那条约束)
* - allowed[key] → 多条约束命中时取交集后的合法值
* - reasons[key] → 命中的约束列表(用于控件下方说明)
*/
export function applyConstraints(values, constraints, params) {
const disabledOptions = {};
const allowed = {};
const reasons = {};
if (!Array.isArray(constraints)) return { disabledOptions, allowed, reasons };
const paramMap = {};
if (Array.isArray(params)) {
params.forEach((p) => {
if (p && p.key) paramMap[p.key] = p;
});
}
constraints.forEach((c) => {
if (!c || !c.limit || !matchesWhen(values, c.when)) return;
Object.entries(c.limit).forEach(([key, list]) => {
if (!Array.isArray(list)) return;
const reason = { when: c.when, allowed: list };
if (c.message) reason.message = c.message;
(reasons[key] = reasons[key] || []).push(reason);
const listKeys = new Set(list.map(optionKey));
allowed[key] = allowed[key]
? allowed[key].filter((v) => listKeys.has(optionKey(v)))
: list.slice();
const param = paramMap[key];
if (param && Array.isArray(param.options)) {
param.options.forEach((opt) => {
const k = optionKey(opt);
if (listKeys.has(k)) return;
disabledOptions[key] = disabledOptions[key] || {};
if (!disabledOptions[key][k]) disabledOptions[key][k] = reason;
});
}
});
});
return { disabledOptions, allowed, reasons };
}
/** 解析 "16:9" / "16x9" / "16/9" 为宽高比数值;无法解析返回 NaN。 */
export function parseRatio(v) {
if (typeof v === 'number') return v;
if (typeof v !== 'string') return NaN;
const m = v.trim().match(/^(\d+(?:\.\d+)?)\s*[:x×/*]\s*(\d+(?:\.\d+)?)$/i);
if (!m) return NaN;
const w = Number(m[1]);
const h = Number(m[2]);
if (!w || !h) return NaN;
return w / h;
}
function toNumber(v) {
if (typeof v === 'number') return v;
if (typeof v === 'string') {
// 允许带单位后缀:"5"、"5s"、"720P"
const m = v.trim().match(/^(-?\d+(?:\.\d+)?)\s*[a-z]*$/i);
return m ? Number(m[1]) : NaN;
}
return NaN;
}
/** 参数默认值:schema default 合法时用它,否则取第一个选项。 */
export function getParamDefault(param) {
if (!param) return undefined;
const opts = Array.isArray(param.options) ? param.options : null;
if (opts && opts.length > 0) {
if (param.default !== undefined) {
const hit = opts.find((o) => optionKey(o) === optionKey(param.default));
if (hit !== undefined) return optionValue(hit);
}
return optionValue(opts[0]);
}
if (param.default !== undefined) return param.default;
if (param.type === 'switch') return false;
return undefined;
}
/** 由 params 生成默认取值表(跳过无默认值的参数,如 seed)。 */
export function getDefaultValues(params) {
const out = {};
(params || []).forEach((p) => {
if (!p || !p.key) return;
const d = getParamDefault(p);
if (d !== undefined) out[p.key] = d;
});
return out;
}
/**
* 将取值吸附到该参数最近的合法选项。
*
* - ratio:按宽高比的对数距离取最接近者(16:10 → 16:9)
* - 数值选项(时长等):取数值最接近者,距离相同取较小值
* - 其他(chips/select 字符串):取默认值,否则第一个选项
* - 无 options 的参数(switch/seed/textarea/slider):
* slider 夹到 [min,max];其余原样返回
*
* @param {object} param schema 中的单个参数
* @param {any} value 当前取值
* @param {Record<string, any>} [disabled] 该参数被约束禁用的选项(applyConstraints().disabledOptions[key])
* @returns {{ value: any, changed: boolean }}
* value 为 null/undefined 时返回默认值且 changed=false(不是用户值被改,不需要提示)。
*/
export function snapToNearest(param, value, disabled) {
if (!param) return { value, changed: false };
const opts = Array.isArray(param.options) ? param.options : null;
if (!opts || opts.length === 0) {
if (param.type === 'slider' && value !== undefined && value !== null) {
const n = toNumber(value);
if (Number.isNaN(n)) {
return { value: getParamDefault(param), changed: true };
}
let clamped = n;
if (typeof param.min === 'number') clamped = Math.max(param.min, clamped);
if (typeof param.max === 'number') clamped = Math.min(param.max, clamped);
return { value: clamped, changed: clamped !== n };
}
if (value === undefined || value === null) {
return { value: getParamDefault(param), changed: false };
}
return { value, changed: false };
}
const usable = opts.filter((o) => !(disabled && disabled[optionKey(o)]));
const pool = usable.length > 0 ? usable : opts;
if (value === undefined || value === null || value === '') {
const d = getParamDefault(param);
const inPool = pool.find((o) => optionKey(o) === optionKey(d));
return {
value: inPool !== undefined ? optionValue(inPool) : optionValue(pool[0]),
changed: false,
};
}
const exact = pool.find((o) => optionKey(o) === optionKey(value));
if (exact !== undefined) return { value: optionValue(exact), changed: false };
if (param.type === 'ratio') {
const target = parseRatio(value);
if (!Number.isNaN(target)) {
let best = null;
let bestDist = Infinity;
pool.forEach((o) => {
const r = parseRatio(optionValue(o));
if (Number.isNaN(r)) return;
const d = Math.abs(Math.log(r) - Math.log(target));
if (d < bestDist - 1e-9) {
bestDist = d;
best = o;
}
});
if (best !== null) return { value: optionValue(best), changed: true };
}
}
const target = toNumber(value);
const numericPool = pool.filter(
(o) => !Number.isNaN(toNumber(optionValue(o))),
);
if (!Number.isNaN(target) && numericPool.length === pool.length) {
let best = numericPool[0];
let bestDist = Infinity;
numericPool.forEach((o) => {
const n = toNumber(optionValue(o));
const d = Math.abs(n - target);
if (d < bestDist || (d === bestDist && n < toNumber(optionValue(best)))) {
bestDist = d;
best = o;
}
});
return { value: optionValue(best), changed: true };
}
const d = getParamDefault(param);
const inPool = pool.find((o) => optionKey(o) === optionKey(d));
return {
value: inPool !== undefined ? optionValue(inPool) : optionValue(pool[0]),
changed: true,
};
}
/**
* 对整张取值表做吸附(切换模型时用)。
*
* @returns {{ values: Record<string, any>, adjustments: Array<{key:string, from:any, to:any}> }}
* adjustments 只包含"用户原有值被改掉"的项,可用于轻提示。
*/
export function snapValues(params, values, constraints) {
const out = { ...(values || {}) };
const adjustments = [];
const list = (params || []).filter((p) => p && p.key);
list.forEach((p) => {
const r = snapToNearest(p, out[p.key]);
if (r.changed)
adjustments.push({ key: p.key, from: out[p.key], to: r.value });
if (r.value !== undefined) out[p.key] = r.value;
});
// 约束可能使某些已吸附的值失效,再按约束吸附一轮
if (Array.isArray(constraints) && constraints.length > 0) {
const { disabledOptions } = applyConstraints(out, constraints, list);
list.forEach((p) => {
const dis = disabledOptions[p.key];
if (!dis || !dis[optionKey(out[p.key])]) return;
const r = snapToNearest(p, out[p.key], dis);
if (r.changed) {
adjustments.push({ key: p.key, from: out[p.key], to: r.value });
out[p.key] = r.value;
}
});
}
return { values: out, adjustments };
}
@@ -0,0 +1,195 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import assert from 'node:assert/strict';
import test from 'node:test';
import {
applyConstraints,
getDefaultValues,
parseRatio,
snapToNearest,
snapValues,
} from './constraints.js';
const params = [
{
key: 'aspect_ratio',
type: 'ratio',
options: ['16:9', '9:16', '1:1', '4:3', '3:4', '21:9'],
default: '16:9',
placement: 'dock',
},
{
key: 'resolution',
type: 'chips',
options: ['480P', '720P', '1080P'],
default: '720P',
placement: 'dock',
},
{
key: 'duration',
type: 'segmented',
options: [5, 10],
default: 5,
unit: 's',
placement: 'dock',
},
{
key: 'generate_audio',
type: 'switch',
default: true,
placement: 'advanced',
},
{ key: 'seed', type: 'seed', placement: 'advanced' },
];
const constraints = [
{ when: { resolution: '1080P' }, limit: { duration: [5] } },
];
test('applyConstraints disables options outside the limit when matched', () => {
const r = applyConstraints(
{ resolution: '1080P', duration: 10 },
constraints,
params,
);
assert.deepEqual(Object.keys(r.disabledOptions.duration), ['10']);
assert.deepEqual(r.allowed.duration, [5]);
assert.equal(r.reasons.duration.length, 1);
assert.deepEqual(r.disabledOptions.duration['10'].when, {
resolution: '1080P',
});
});
test('applyConstraints ignores unmatched constraints and bad input', () => {
assert.deepEqual(
applyConstraints({ resolution: '720P' }, constraints, params),
{
disabledOptions: {},
allowed: {},
reasons: {},
},
);
assert.deepEqual(applyConstraints({}, null).disabledOptions, {});
});
test('applyConstraints supports array conditions and intersects limits', () => {
const r = applyConstraints(
{ resolution: '1080P' },
[
{
when: { resolution: ['720P', '1080P'] },
limit: { aspect_ratio: ['16:9', '9:16', '1:1'] },
},
{
when: { resolution: '1080P' },
limit: { aspect_ratio: ['16:9', '1:1'] },
},
],
params,
);
assert.deepEqual(r.allowed.aspect_ratio, ['16:9', '1:1']);
assert.deepEqual(Object.keys(r.disabledOptions.aspect_ratio).sort(), [
'21:9',
'3:4',
'4:3',
'9:16',
]);
});
test('parseRatio', () => {
assert.equal(parseRatio('16:9'), 16 / 9);
assert.equal(parseRatio('4x3'), 4 / 3);
assert.ok(Number.isNaN(parseRatio('auto')));
});
test('snapToNearest: ratio picks closest aspect', () => {
const p = params[0];
assert.deepEqual(snapToNearest(p, '16:9'), { value: '16:9', changed: false });
assert.deepEqual(snapToNearest(p, '16:10'), { value: '16:9', changed: true });
assert.deepEqual(snapToNearest(p, '2:3'), { value: '3:4', changed: true });
assert.deepEqual(snapToNearest(p, '5:2'), { value: '21:9', changed: true });
});
test('snapToNearest: numbers pick nearest, ties go lower', () => {
const p = params[2];
assert.deepEqual(snapToNearest(p, 8), { value: 10, changed: true });
assert.deepEqual(snapToNearest(p, 6), { value: 5, changed: true });
assert.deepEqual(snapToNearest(p, 7.5), { value: 5, changed: true });
assert.deepEqual(snapToNearest(p, '10'), { value: 10, changed: false });
});
test('snapToNearest: strings fall back to default, missing value is not a change', () => {
const p = {
key: 'style',
type: 'select',
options: ['vivid', 'natural'],
default: 'natural',
};
assert.deepEqual(snapToNearest(p, 'anime'), {
value: 'natural',
changed: true,
});
assert.deepEqual(snapToNearest(p, undefined), {
value: 'natural',
changed: false,
});
assert.deepEqual(snapToNearest(params[3], undefined), {
value: true,
changed: false,
});
assert.deepEqual(snapToNearest(params[4], 42), { value: 42, changed: false });
});
test('snapToNearest respects disabled options', () => {
const { disabledOptions } = applyConstraints(
{ resolution: '1080P' },
constraints,
params,
);
assert.deepEqual(snapToNearest(params[2], 10, disabledOptions.duration), {
value: 5,
changed: true,
});
});
test('snapToNearest clamps slider values', () => {
const p = { key: 'strength', type: 'slider', min: 0, max: 1, step: 0.1 };
assert.deepEqual(snapToNearest(p, 3), { value: 1, changed: true });
assert.deepEqual(snapToNearest(p, 0.5), { value: 0.5, changed: false });
});
test('getDefaultValues and snapValues', () => {
assert.deepEqual(getDefaultValues(params), {
aspect_ratio: '16:9',
resolution: '720P',
duration: 5,
generate_audio: true,
});
const r = snapValues(
params,
{ aspect_ratio: '3:2', resolution: '1080P', duration: 10 },
constraints,
);
assert.equal(r.values.aspect_ratio, '4:3');
assert.equal(r.values.duration, 5);
assert.deepEqual(
r.adjustments.map((a) => a.key),
['aspect_ratio', 'duration'],
);
});
@@ -0,0 +1,494 @@
/*
* 创作参数控件库(WP B-1)样式。
* 配色全部从主题 token 派生(frontend-design skill 铁律一),禁止裸色值。
* 局部变量挂在每个可独立使用的控件根上,单独引用某个控件时同样生效。
*/
.creation-params,
.cp-option-group,
.cp-slot,
.cp-seed,
.cp-slider,
.cp-select,
.cp-select-dropdown {
--cp-ink: var(--text-primary);
--cp-muted: var(--text-secondary);
--cp-line: var(--border-subtle);
--cp-surface: var(--surface-card);
--cp-accent: var(--semi-color-primary);
--cp-accent-tint: color-mix(
in srgb,
var(--semi-color-primary) 10%,
transparent
);
--cp-accent-line: color-mix(
in srgb,
var(--semi-color-primary) 45%,
transparent
);
--cp-fill: color-mix(in srgb, var(--text-primary) 4%, var(--surface-card));
--cp-fill-hover: color-mix(
in srgb,
var(--semi-color-primary) 6%,
var(--surface-card)
);
--cp-danger: var(--semi-color-danger);
--cp-danger-tint: color-mix(
in srgb,
var(--semi-color-danger) 10%,
var(--surface-card)
);
--cp-warning: var(--semi-color-warning);
--cp-ring: color-mix(in srgb, var(--semi-color-primary) 55%, transparent);
--cp-overlay: color-mix(in srgb, var(--surface-card) 78%, transparent);
--cp-dur: var(--motion-fast, 150ms);
}
/* ---------- 渲染器布局 ---------- */
.cp-renderer {
display: flex;
flex-direction: column;
gap: 14px;
min-width: 0;
}
.cp-row {
display: flex;
flex-direction: column;
gap: 6px;
min-width: 0;
}
.cp-row--inline {
flex-direction: row;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
}
.cp-row--inline .cp-row-hint {
flex-basis: 100%;
}
.cp-row-label {
font-size: 12px;
font-weight: 600;
color: var(--cp-muted);
line-height: 18px;
}
.cp-row-control {
min-width: 0;
}
.cp-row-hint {
font-size: 12px;
line-height: 18px;
color: var(--cp-warning);
}
/* ---------- 单选按钮组 ---------- */
.cp-option-group {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.cp-option {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 6px;
min-height: 30px;
padding: 4px 12px;
border: 1px solid var(--cp-line);
border-radius: 8px;
background: var(--cp-fill);
color: var(--cp-ink);
font-size: 13px;
line-height: 20px;
cursor: pointer;
transition:
background-color var(--cp-dur) ease,
border-color var(--cp-dur) ease,
color var(--cp-dur) ease;
}
.cp-option:hover:not(.is-disabled):not(.is-selected) {
background: var(--cp-fill-hover);
border-color: var(--cp-accent-line);
}
.cp-option.is-selected {
background: var(--cp-accent-tint);
border-color: var(--cp-accent);
color: var(--cp-accent);
font-weight: 600;
}
.cp-option.is-disabled {
cursor: not-allowed;
opacity: 0.45;
}
.cp-option-group[aria-disabled='true'] .cp-option {
cursor: not-allowed;
}
.creation-params button:focus-visible,
.cp-option:focus-visible,
.cp-icon-btn:focus-visible,
.cp-slot:focus-visible,
.cp-slot button:focus-visible {
outline: 2px solid var(--cp-ring);
outline-offset: 2px;
}
/* 分段:紧凑连体外观 */
.cp-option-group--segmented {
gap: 0;
display: inline-flex;
padding: 2px;
border: 1px solid var(--cp-line);
border-radius: 9px;
background: var(--cp-fill);
}
.cp-option-group--segmented .cp-option {
min-width: 48px;
border-color: transparent;
background: transparent;
border-radius: 7px;
}
.cp-option-group--segmented .cp-option.is-selected {
background: var(--cp-surface);
border-color: var(--cp-accent-line);
}
/* 比例:形状图标 + 文字,纵向排布 */
.cp-option-group--ratio .cp-option {
flex-direction: column;
gap: 4px;
min-width: 52px;
padding: 6px 8px;
}
.cp-ratio-shape-box {
display: inline-flex;
align-items: center;
justify-content: center;
width: 18px;
height: 18px;
}
.cp-ratio-shape {
display: block;
border: 1.5px solid currentColor;
border-radius: 3px;
opacity: 0.85;
}
.cp-option-label {
white-space: nowrap;
}
.tabular-nums,
.cp-option-group--segmented .cp-option-label,
.cp-option-group--ratio .cp-option-label {
font-variant-numeric: tabular-nums;
}
/* ---------- Select / TextArea / Slider ---------- */
.cp-select {
width: 100%;
}
.cp-select-option {
display: flex;
flex-direction: column;
min-width: 0;
}
.cp-select-option-label {
color: var(--cp-ink);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.cp-select-option-desc {
font-size: 12px;
line-height: 16px;
color: var(--cp-muted);
white-space: normal;
}
.cp-inline-trigger {
display: inline-flex;
}
.cp-inline-trigger--block {
display: flex;
width: 100%;
}
.cp-textarea {
width: 100%;
}
.cp-slider {
display: flex;
align-items: center;
gap: 10px;
}
.cp-slider > :first-child {
flex: 1;
min-width: 0;
}
.cp-slider-value {
min-width: 40px;
text-align: right;
font-size: 13px;
color: var(--cp-ink);
}
/* ---------- 种子 ---------- */
.cp-seed {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
}
.cp-seed-toggle {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 13px;
color: var(--cp-ink);
cursor: pointer;
}
.cp-seed-input {
width: 140px;
}
.cp-icon-btn {
display: inline-flex;
align-items: center;
justify-content: center;
width: 30px;
height: 30px;
border: 1px solid var(--cp-line);
border-radius: 8px;
background: var(--cp-fill);
color: var(--cp-muted);
cursor: pointer;
transition:
color var(--cp-dur) ease,
border-color var(--cp-dur) ease,
background-color var(--cp-dur) ease;
}
.cp-icon-btn:hover:not(:disabled) {
color: var(--cp-accent);
border-color: var(--cp-accent-line);
background: var(--cp-fill-hover);
}
.cp-icon-btn:disabled {
cursor: not-allowed;
opacity: 0.45;
}
/* ---------- 图片槽 ---------- */
.cp-slot {
position: relative;
display: flex;
align-items: center;
justify-content: center;
width: 112px;
height: 112px;
border: 1px dashed var(--cp-line);
border-radius: 12px;
background: var(--cp-fill);
color: var(--cp-muted);
overflow: hidden;
transition:
border-color var(--cp-dur) ease,
background-color var(--cp-dur) ease;
}
.cp-slot[role='button'] {
cursor: pointer;
}
.cp-slot[role='button']:hover,
.cp-slot.is-dragover {
border-color: var(--cp-accent);
background: var(--cp-fill-hover);
color: var(--cp-accent);
}
.cp-slot.is-ready,
.cp-slot.is-uploading,
.cp-slot.is-unused {
border-style: solid;
}
.cp-slot.is-error {
border-color: var(--cp-danger);
}
.cp-slot.is-expired {
border-color: var(--cp-warning);
}
.cp-slot.is-disabled {
cursor: not-allowed;
opacity: 0.5;
}
.cp-slot-input {
display: none;
}
.cp-slot-img {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
object-fit: cover;
}
.cp-slot.is-unused .cp-slot-img {
filter: grayscale(1);
opacity: 0.4;
}
.cp-slot.is-error .cp-slot-img {
opacity: 0.35;
}
.cp-slot-empty {
display: flex;
flex-direction: column;
align-items: center;
gap: 4px;
padding: 18px 8px 22px;
text-align: center;
}
.cp-slot-status {
font-size: 12px;
line-height: 16px;
word-break: break-all;
}
.cp-slot.is-expired .cp-slot-status {
color: var(--cp-warning);
font-weight: 600;
}
.cp-slot-hint {
font-size: 11px;
line-height: 14px;
color: var(--cp-muted);
}
.cp-slot-overlay {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 6px;
padding: 8px 8px 22px;
background: var(--cp-overlay);
color: var(--cp-ink);
text-align: center;
}
.cp-slot-overlay.is-error {
background: var(--cp-danger-tint);
color: var(--cp-danger);
}
.cp-slot-action {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 2px 10px;
border: 1px solid currentColor;
border-radius: 999px;
background: var(--cp-surface);
color: inherit;
font-size: 12px;
cursor: pointer;
}
.cp-slot-remove {
position: absolute;
top: 4px;
right: 4px;
z-index: 2;
display: inline-flex;
align-items: center;
justify-content: center;
width: 22px;
height: 22px;
border: 1px solid var(--cp-line);
border-radius: 999px;
background: var(--cp-overlay);
color: var(--cp-ink);
cursor: pointer;
}
.cp-slot-remove:hover {
color: var(--cp-danger);
border-color: var(--cp-danger);
}
.cp-slot-badge {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
max-width: calc(100% - 12px);
padding: 2px 8px;
border-radius: 999px;
background: var(--cp-overlay);
border: 1px solid var(--cp-line);
color: var(--cp-muted);
font-size: 11px;
line-height: 16px;
text-align: center;
}
.cp-slot-label {
position: absolute;
left: 0;
right: 0;
bottom: 0;
z-index: 1;
padding: 2px 6px;
background: var(--cp-overlay);
color: var(--cp-ink);
font-size: 11px;
line-height: 16px;
text-align: center;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
@media (prefers-reduced-motion: reduce) {
.cp-option,
.cp-icon-btn,
.cp-slot {
transition: none;
}
}
+46
View File
@@ -0,0 +1,46 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
export { default as ParamRenderer, PARAM_CONTROLS } from './ParamRenderer';
export { default as OptionGroup } from './OptionGroup';
export { default as RatioPicker, RatioShape } from './RatioPicker';
export { default as ChipGroup } from './ChipGroup';
export { default as DurationSegmented } from './DurationSegmented';
export { default as ParamSwitch } from './ParamSwitch';
export { default as ParamSelect } from './ParamSelect';
export { default as ParamTextArea } from './ParamTextArea';
export { default as ParamSlider } from './ParamSlider';
export { default as SeedInput, isRandomSeed, randomSeed } from './SeedInput';
export { default as ImageSlot } from './ImageSlot';
export {
applyConstraints,
snapToNearest,
snapValues,
getParamDefault,
getDefaultValues,
parseRatio,
optionKey,
optionValue,
} from './constraints';
export {
PARAM_LABEL_KEYS,
paramLabel,
optionLabel,
formatConstraintReason,
} from './labels';
+97
View File
@@ -0,0 +1,97 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { optionKey, optionValue } from './constraints';
// 已知参数 key 的中文标签(作为 i18n key)。schema 下发了 label 时优先用 label。
export const PARAM_LABEL_KEYS = {
aspect_ratio: '画面比例',
ratio: '画面比例',
resolution: '分辨率',
duration: '时长',
generate_audio: '生成音频',
audio: '生成音频',
seed: '随机种子',
watermark: '水印',
return_last_frame: '返回尾帧',
camera_motion: '运镜',
camera_fixed: '固定镜头',
negative_prompt: '反向提示词',
prompt_extend: '智能扩写提示词',
quality: '画质',
n: '生成数量',
size: '尺寸',
style: '风格',
mode: '生成模式',
};
/** 参数显示名。 */
export function paramLabel(t, param) {
if (!param) return '';
if (param.label) return t(param.label);
const k = PARAM_LABEL_KEYS[param.key];
return k ? t(k) : param.key;
}
/** 单个选项的显示文本:对象选项取 label,否则拼接单位(5 + "s" → "5s")。 */
export function optionLabel(t, param, opt) {
if (opt && typeof opt === 'object' && opt.label) return t(opt.label);
const v = optionValue(opt);
if (typeof v === 'boolean') return v ? t('是') : t('否');
const unit = param && param.unit ? param.unit : '';
return `${v}${unit}`;
}
function describeWhen(t, when, params) {
const byKey = {};
(params || []).forEach((p) => {
if (p && p.key) byKey[p.key] = p;
});
return Object.entries(when || {})
.map(([k, v]) => {
const p = byKey[k] || { key: k };
const vs = Array.isArray(v) ? v : [v];
return `${paramLabel(t, p)} ${vs.map((x) => optionLabel(t, p, x)).join('/')}`;
})
.join('、');
}
/**
* 约束原因 → 一句人话,如"分辨率 1080P 时,时长仅支持 5s"。
* reason 为 applyConstraints 返回的 { when, allowed, message? }。
*/
export function formatConstraintReason(t, reason, param, params) {
if (!reason) return '';
if (reason.message) return t(reason.message);
const allowed = (reason.allowed || [])
.map((v) => optionLabel(t, param, v))
.join(' / ');
return t('{{cond}} 时,{{name}}仅支持 {{allowed}}', {
cond: describeWhen(t, reason.when, params),
name: paramLabel(t, param),
allowed,
});
}
/** 判断选项是否被禁用;返回原因文本或空串。 */
export function disabledReasonOf(t, disabledMap, opt, param, params) {
if (!disabledMap) return '';
const r = disabledMap[optionKey(opt)];
return r ? formatConstraintReason(t, r, param, params) : '';
}