Files
monkey-ai-web/src/components/creation/params/constraints.js
T
qiubaishen 6160a23117 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 里登录页只显示站内登录方式
2026-11-10 11:05:34 +08:00

301 lines
11 KiB
JavaScript
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
*/
// 创作参数 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 };
}