cb9d836227
集中保留原版权声明,移除文件头检查和全局测试忽略规则。验证:全量单测、受影响用例复测及静态检查通过。
579 lines
20 KiB
JavaScript
579 lines
20 KiB
JavaScript
// 创作台(CreationDock,WP B-3)的纯函数:先传图时的模式推断、图片角色记忆、
|
||
// 「图N」引用改写、模板参数套用。无 React / i18n 依赖,可直接 node --test。
|
||
|
||
import * as video from '../video/videoCreation.js';
|
||
import * as image from '../image/imageCreation.js';
|
||
import { optionValue } from '../../components/creation/params/constraints.js';
|
||
|
||
/** 图片角色:首帧 / 首尾帧(frames)或参考图 / 编辑(reference)。 */
|
||
export const ROLE_FRAMES = 'frames';
|
||
export const ROLE_REFERENCE = 'reference';
|
||
|
||
const MODE_ROLES = {
|
||
image2video: ROLE_FRAMES,
|
||
first_last_frame: ROLE_FRAMES,
|
||
reference2video: ROLE_REFERENCE,
|
||
edit: ROLE_REFERENCE,
|
||
};
|
||
|
||
/** 模式对应的图片角色;文生模式返回 ''。 */
|
||
export const roleOfMode = (mode) => MODE_ROLES[mode] || '';
|
||
|
||
/** 「图1」「图2」指代只在参考图 / 编辑模式下使用(方案 §4.4)。 */
|
||
export const usesImageRefs = (mode) => roleOfMode(mode) === ROLE_REFERENCE;
|
||
|
||
const modelModes = (model) => (model && model.modes) || [];
|
||
|
||
/**
|
||
* 某模式可接收的图片张数:{ min, max }。文生模式 { 0, 0 }。
|
||
* 首尾帧必须两张都有;参考图 / 编辑至少一张。
|
||
*/
|
||
export const modeCapacity = (kind, model, mode) => {
|
||
if (kind === 'image') {
|
||
const max = image.referenceMaxOf(model, mode);
|
||
return { min: max > 0 ? 1 : 0, max };
|
||
}
|
||
const a = video.activeInputsOf(model, mode);
|
||
const frames = (a.first_frame ? 1 : 0) + (a.last_frame ? 1 : 0);
|
||
if (frames > 0) return { min: frames, max: frames + a.reference_max };
|
||
return { min: a.reference_max > 0 ? 1 : 0, max: a.reference_max };
|
||
};
|
||
|
||
/** 模型是否接受图片输入(任一可用模式)。 */
|
||
export const acceptsImages = (kind, model) =>
|
||
modelModes(model).some((m) => modeCapacity(kind, model, m).max > 0);
|
||
|
||
/** 对 count 张图片合法的模式(按模型 modes 顺序)。 */
|
||
export const legalModesForCount = (kind, model, count) => {
|
||
if (!model || !(count > 0)) return [];
|
||
return modelModes(model).filter((m) => {
|
||
const c = modeCapacity(kind, model, m);
|
||
return c.max > 0 && count >= c.min && count <= c.max;
|
||
});
|
||
};
|
||
|
||
/**
|
||
* 当前模式下按顺序放置 count 张新图的目标槽(只用空着的、当前模式会提交的槽)。
|
||
* @returns {Array<{ key: string, index?: number }>}
|
||
*/
|
||
export const emptyTargetsOf = (kind, model, mode, images, count) => {
|
||
const imgs = images || {};
|
||
const out = [];
|
||
if (kind === 'video') {
|
||
const a = video.activeInputsOf(model, mode);
|
||
if (a.first_frame && !imgs.first_frame) out.push({ key: 'first_frame' });
|
||
if (a.last_frame && !imgs.last_frame) out.push({ key: 'last_frame' });
|
||
const refs = (imgs.reference_images || []).length;
|
||
for (let i = refs; i < a.reference_max; i += 1) {
|
||
out.push({ key: 'reference_images' });
|
||
}
|
||
} else {
|
||
const max = image.referenceMaxOf(model, mode);
|
||
const refs = (imgs.reference_images || []).length;
|
||
for (let i = refs; i < max; i += 1) out.push({ key: 'reference_images' });
|
||
}
|
||
return out.slice(0, Math.max(0, count));
|
||
};
|
||
|
||
const freshTargets = (kind, model, mode, count) =>
|
||
emptyTargetsOf(kind, model, mode, {}, count);
|
||
|
||
/** 当前模式会提交的已有图片,按 首帧 → 尾帧 → 参考图 顺序。 */
|
||
export const activeImagesOf = (kind, model, mode, images) => {
|
||
const imgs = images || {};
|
||
const refs = imgs.reference_images || [];
|
||
if (kind !== 'video') {
|
||
return refs.slice(0, image.referenceMaxOf(model, mode)).filter(Boolean);
|
||
}
|
||
const a = video.activeInputsOf(model, mode);
|
||
const out = [];
|
||
if (a.first_frame && imgs.first_frame) out.push(imgs.first_frame);
|
||
if (a.last_frame && imgs.last_frame) out.push(imgs.last_frame);
|
||
return out.concat(refs.slice(0, a.reference_max)).filter(Boolean);
|
||
};
|
||
|
||
/** 不同角色的候选模式(同一角色只保留第一个)。 */
|
||
const roleChoicesOf = (modes) => {
|
||
const choices = [];
|
||
modes.forEach((m) => {
|
||
const role = roleOfMode(m);
|
||
if (role && !choices.some((c) => c.role === role)) {
|
||
choices.push({ role, mode: m });
|
||
}
|
||
});
|
||
return choices;
|
||
};
|
||
|
||
/**
|
||
* 切到 newMode 后重新排布已有图片:已有图片按顺序占据新模式的前几个槽,
|
||
* 返回新的 images 与留给新图片的目标槽。当前模式不提交的旧图片保留在原位(新模式用到参考图时
|
||
* 其中的旧参考图不再保留,避免超出上限)。
|
||
*/
|
||
const relayoutImages = (kind, model, newMode, images, existing, total) => {
|
||
const imgs = images || {};
|
||
const targets = freshTargets(kind, model, newMode, total);
|
||
const moved = new Set(existing);
|
||
const usesRefs = targets.some((tg) => tg.key === 'reference_images');
|
||
const next = {
|
||
first_frame:
|
||
imgs.first_frame && !moved.has(imgs.first_frame)
|
||
? imgs.first_frame
|
||
: null,
|
||
last_frame:
|
||
imgs.last_frame && !moved.has(imgs.last_frame) ? imgs.last_frame : null,
|
||
reference_images: usesRefs
|
||
? []
|
||
: (imgs.reference_images || []).filter((r) => r && !moved.has(r)),
|
||
};
|
||
existing.forEach((slot, i) => {
|
||
const target = targets[i];
|
||
if (!target) return;
|
||
if (target.key === 'reference_images') next.reference_images.push(slot);
|
||
else next[target.key] = slot;
|
||
});
|
||
return { images: next, targets: targets.slice(existing.length) };
|
||
};
|
||
|
||
/**
|
||
* 已在图片模式但空槽不够时,按"已有 + 新增"总张数重新推断(WP B-7):
|
||
* 唯一合法模式 → 切换并重新排布;多种 → 沿用记住的角色,否则 choose;没有 → null。
|
||
*/
|
||
const planRegroup = ({ kind, model, mode, images, count, rememberedRole }) => {
|
||
const existing = activeImagesOf(kind, model, mode, images);
|
||
const total = existing.length + count;
|
||
const legal = legalModesForCount(kind, model, total).filter(
|
||
(m) => m !== mode,
|
||
);
|
||
if (!legal.length) return null;
|
||
const pick = (m, extra = {}) => ({
|
||
type: 'place',
|
||
mode: m,
|
||
...relayoutImages(kind, model, m, images, existing, total),
|
||
regrouped: true,
|
||
...extra,
|
||
});
|
||
const choices = roleChoicesOf(legal);
|
||
if (choices.length <= 1) return pick(choices[0] ? choices[0].mode : legal[0]);
|
||
const hit = choices.find((c) => c.role === rememberedRole);
|
||
if (hit) return pick(hit.mode, { remembered: true });
|
||
return { type: 'choose', choices, regroup: true };
|
||
};
|
||
|
||
/**
|
||
* 先上传图片时决定模式与放置位置(方案 §4.4)。
|
||
*
|
||
* - 当前已是图片模式且空槽够用 → 按槽位放置,模式不变;
|
||
* - 否则按图片张数推断:只有一种合法模式 → 直接切换;多种 → 沿用该模型记住的角色,
|
||
* 没有记忆则返回 choose 让界面弹出小选择器;
|
||
* - 模型不接受图片 → unsupported(界面提示换模型,绝不自动换);
|
||
* - 张数超过所有模式上限 → 选上限最大的模式放置前 max 张(truncated)。
|
||
*
|
||
* @returns {{ type: 'place', mode: string, targets: Array<{key, index?}>,
|
||
* remembered?: boolean, truncated?: number,
|
||
* images?: object, regrouped?: boolean } images:重新推断时已有图片的新排布,先写入再放新图
|
||
* | { type: 'choose', choices: Array<{ role: string, mode: string }> }
|
||
* | { type: 'unsupported' }}
|
||
*/
|
||
export const planImageUpload = ({
|
||
kind,
|
||
model,
|
||
mode,
|
||
images,
|
||
count,
|
||
rememberedRole = '',
|
||
}) => {
|
||
if (!model || !(count > 0)) return { type: 'unsupported' };
|
||
if (!acceptsImages(kind, model)) return { type: 'unsupported' };
|
||
|
||
const current = modeCapacity(kind, model, mode);
|
||
if (current.max > 0 && video.isModeEnabled(model, mode)) {
|
||
// 已在图片模式:空槽够用 → 按槽位放置(用户先选模式再上传,不会有歧义)
|
||
const empties = emptyTargetsOf(kind, model, mode, images, count);
|
||
const rest = count - empties.length;
|
||
if (rest <= 0) return { type: 'place', mode, targets: empties };
|
||
// 空槽不够(WP B-7):按"已有 + 新增"的总张数重新推断模式,规则与先传图相同
|
||
const regroup = planRegroup({
|
||
kind,
|
||
model,
|
||
mode,
|
||
images,
|
||
count,
|
||
rememberedRole,
|
||
});
|
||
if (regroup) return regroup;
|
||
// 没有能容纳全部图片的模式:能放多少放多少,余下的提示超出上限(targets 可能为空)
|
||
return { type: 'place', mode, targets: empties, truncated: rest };
|
||
}
|
||
|
||
const legal = legalModesForCount(kind, model, count);
|
||
if (legal.length === 1) {
|
||
return {
|
||
type: 'place',
|
||
mode: legal[0],
|
||
targets: freshTargets(kind, model, legal[0], count),
|
||
};
|
||
}
|
||
if (legal.length > 1) {
|
||
const choices = [];
|
||
legal.forEach((m) => {
|
||
const role = roleOfMode(m);
|
||
if (role && !choices.some((c) => c.role === role)) {
|
||
choices.push({ role, mode: m });
|
||
}
|
||
});
|
||
if (choices.length === 1) {
|
||
return {
|
||
type: 'place',
|
||
mode: choices[0].mode,
|
||
targets: freshTargets(kind, model, choices[0].mode, count),
|
||
};
|
||
}
|
||
const hit = choices.find((c) => c.role === rememberedRole);
|
||
if (hit) {
|
||
return {
|
||
type: 'place',
|
||
mode: hit.mode,
|
||
targets: freshTargets(kind, model, hit.mode, count),
|
||
remembered: true,
|
||
};
|
||
}
|
||
return { type: 'choose', choices };
|
||
}
|
||
|
||
// 超过所有模式的上限:取上限最大的模式
|
||
let best = '';
|
||
let bestMax = 0;
|
||
modelModes(model).forEach((m) => {
|
||
const c = modeCapacity(kind, model, m);
|
||
if (c.max > bestMax) {
|
||
best = m;
|
||
bestMax = c.max;
|
||
}
|
||
});
|
||
return {
|
||
type: 'place',
|
||
mode: best,
|
||
targets: freshTargets(kind, model, best, bestMax),
|
||
truncated: count - bestMax,
|
||
};
|
||
};
|
||
|
||
/**
|
||
* 模型不接受图片时建议切换的模型:未锁定、对 count 张图有合法模式;同系列优先。
|
||
* 返回 null 表示没有可建议的模型。
|
||
*/
|
||
export const suggestImageModel = (kind, models, current, count = 1) => {
|
||
const list = (Array.isArray(models) ? models : []).filter(
|
||
(m) =>
|
||
m &&
|
||
!m.level_locked &&
|
||
m.model !== (current && current.model) &&
|
||
(legalModesForCount(kind, m, count).length > 0 || acceptsImages(kind, m)),
|
||
);
|
||
if (!list.length) return null;
|
||
const series = current && (current.series || current.vendor);
|
||
const exact = list.filter(
|
||
(m) => legalModesForCount(kind, m, count).length > 0,
|
||
);
|
||
const pool = exact.length ? exact : list;
|
||
return (
|
||
(series && pool.find((m) => (m.series || m.vendor) === series)) || pool[0]
|
||
);
|
||
};
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// 首尾帧:缺图状态与一键切回图生
|
||
// ---------------------------------------------------------------------------
|
||
|
||
/** 首尾帧模式下缺失的槽('first_frame' | 'last_frame'),两张都缺或不在首尾帧模式返回 ''。 */
|
||
export const missingFrameOf = (kind, model, mode, images) => {
|
||
if (kind !== 'video' || mode !== 'first_last_frame') return '';
|
||
const a = video.activeInputsOf(model, mode);
|
||
if (!a.first_frame || !a.last_frame) return '';
|
||
const imgs = images || {};
|
||
if (imgs.first_frame && !imgs.last_frame) return 'last_frame';
|
||
if (!imgs.first_frame && imgs.last_frame) return 'first_frame';
|
||
return '';
|
||
};
|
||
|
||
/**
|
||
* 首尾帧只剩一张时切回图生视频:剩下的那张作为首帧。模型不支持图生返回 null。
|
||
* @returns {{ mode: 'image2video', images: object } | null}
|
||
*/
|
||
export const backToImage2Video = (model, images) => {
|
||
if (!video.isModeEnabled(model, 'image2video')) return null;
|
||
const imgs = images || {};
|
||
const first = imgs.first_frame || imgs.last_frame || null;
|
||
if (!first) return null;
|
||
return {
|
||
mode: 'image2video',
|
||
images: {
|
||
first_frame: first,
|
||
last_frame: imgs.first_frame ? imgs.last_frame || null : null,
|
||
reference_images: imgs.reference_images || [],
|
||
},
|
||
};
|
||
};
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// 角色记忆:按模型记住上次选择的图片角色(creation.<kind>.imageRoles)
|
||
// ---------------------------------------------------------------------------
|
||
|
||
export const roleMemoryKeyOf = (kind) => `creation.${kind}.imageRoles`;
|
||
|
||
const ROLES = new Set([ROLE_FRAMES, ROLE_REFERENCE]);
|
||
|
||
export const loadRoleMemory = (storage, kind) => {
|
||
if (!storage) return {};
|
||
try {
|
||
const raw = JSON.parse(storage.getItem(roleMemoryKeyOf(kind)) || '{}');
|
||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};
|
||
const out = {};
|
||
Object.keys(raw).forEach((k) => {
|
||
if (ROLES.has(raw[k])) out[k] = raw[k];
|
||
});
|
||
return out;
|
||
} catch (e) {
|
||
return {};
|
||
}
|
||
};
|
||
|
||
/** 记住角色并返回新的记忆对象(存储失败时仍返回内存中的新值)。 */
|
||
export const rememberRole = (storage, kind, memory, modelName, role) => {
|
||
if (!modelName || !ROLES.has(role)) return memory || {};
|
||
const next = { ...(memory || {}), [modelName]: role };
|
||
if (storage) {
|
||
try {
|
||
storage.setItem(roleMemoryKeyOf(kind), JSON.stringify(next));
|
||
} catch (e) {
|
||
// 存储不可用时只保留内存中的记忆
|
||
}
|
||
}
|
||
return next;
|
||
};
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// 「图N」引用:编号稳定,删除 / 调整顺序时改写提示词
|
||
// ---------------------------------------------------------------------------
|
||
|
||
const REF_PATTERN = /(「?)图\s?(\d+)(」?)/g;
|
||
|
||
/** 第 n 张参考图(从 1 开始)在提示词中的写法。 */
|
||
export const imageRefToken = (n) => `「图${n}」`;
|
||
|
||
/**
|
||
* 按映射改写提示词中的「图N」。mapping[oldN] = newN(相同则不变)或 null(已删除,去掉该引用)。
|
||
* 映射中没有的编号保持原样。
|
||
*/
|
||
export const rewriteImageRefs = (prompt, mapping) => {
|
||
if (!prompt || !mapping) return prompt || '';
|
||
let removed = false;
|
||
const out = String(prompt).replace(REF_PATTERN, (all, open, num, close) => {
|
||
const n = Number(num);
|
||
if (!Object.prototype.hasOwnProperty.call(mapping, n)) return all;
|
||
const next = mapping[n];
|
||
if (next === null || next === undefined) {
|
||
removed = true;
|
||
return '';
|
||
}
|
||
if (next === n) return all;
|
||
return open || close ? `「图${next}」` : `图${next}`;
|
||
});
|
||
return removed ? out.replace(/ {2,}/g, ' ') : out;
|
||
};
|
||
|
||
/** 删除第 removedIndex(从 0 开始)张后的编号映射。 */
|
||
export const mappingAfterRemove = (count, removedIndex) => {
|
||
const map = {};
|
||
for (let i = 0; i < count; i += 1) {
|
||
if (i === removedIndex) map[i + 1] = null;
|
||
else map[i + 1] = i < removedIndex ? i + 1 : i;
|
||
}
|
||
return map;
|
||
};
|
||
|
||
/** 把第 from 张移动到 to(均从 0 开始)后的编号映射。 */
|
||
export const mappingAfterMove = (count, from, to) => {
|
||
const order = Array.from({ length: count }, (_, i) => i);
|
||
if (from < 0 || from >= count || to < 0 || to >= count) {
|
||
const same = {};
|
||
order.forEach((i) => {
|
||
same[i + 1] = i + 1;
|
||
});
|
||
return same;
|
||
}
|
||
const [moved] = order.splice(from, 1);
|
||
order.splice(to, 0, moved);
|
||
const map = {};
|
||
order.forEach((oldIndex, newIndex) => {
|
||
map[oldIndex + 1] = newIndex + 1;
|
||
});
|
||
return map;
|
||
};
|
||
|
||
/** 数组中把 from 移到 to(返回新数组)。 */
|
||
export const moveItem = (list, from, to) => {
|
||
const arr = [...(list || [])];
|
||
if (from < 0 || from >= arr.length || to < 0 || to >= arr.length) return arr;
|
||
const [item] = arr.splice(from, 1);
|
||
arr.splice(to, 0, item);
|
||
return arr;
|
||
};
|
||
|
||
/** 在光标处插入文本,返回 { text, caret }。 */
|
||
export const insertAt = (text, caret, insert) => {
|
||
const src = String(text || '');
|
||
const pos =
|
||
Number.isInteger(caret) && caret >= 0 && caret <= src.length
|
||
? caret
|
||
: src.length;
|
||
const before = src.slice(0, pos);
|
||
const after = src.slice(pos);
|
||
return { text: before + insert + after, caret: pos + insert.length };
|
||
};
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// 模板推荐参数:只套用当前模型支持且合法的值
|
||
// ---------------------------------------------------------------------------
|
||
|
||
const parseRatioText = (v) => {
|
||
const m = String(v || '').match(
|
||
/^(\d+(?:\.\d+)?)\s*[::/]\s*(\d+(?:\.\d+)?)$/,
|
||
);
|
||
if (!m) return 0;
|
||
const w = Number(m[1]);
|
||
const h = Number(m[2]);
|
||
return w > 0 && h > 0 ? w / h : 0;
|
||
};
|
||
|
||
/**
|
||
* 模板推荐参数 → 当前模型可用的参数取值。
|
||
* - 有 options 的参数:只接受选项中存在的值;
|
||
* - 图像 size:推荐 aspect_ratio 时取宽高比最接近的尺寸预设(误差 ≤ 3%);
|
||
* - 其他类型(switch / textarea / seed / slider)原样套用同类型的值。
|
||
* @returns {object} { [key]: value }
|
||
*/
|
||
export const templateParamsFor = (params, recommended) => {
|
||
const out = {};
|
||
const rec = recommended || {};
|
||
const byKey = {};
|
||
(params || []).forEach((p) => {
|
||
if (p && p.key) byKey[p.key] = p;
|
||
});
|
||
Object.keys(rec).forEach((key) => {
|
||
const p = byKey[key];
|
||
if (!p) return;
|
||
const want = rec[key];
|
||
if (Array.isArray(p.options) && p.options.length) {
|
||
const hit = p.options.find(
|
||
(o) => String(optionValue(o)) === String(want),
|
||
);
|
||
if (hit !== undefined) out[key] = optionValue(hit);
|
||
return;
|
||
}
|
||
if (p.type === 'switch' && typeof want === 'boolean') out[key] = want;
|
||
else if (p.type === 'textarea' && typeof want === 'string') {
|
||
out[key] = want;
|
||
}
|
||
});
|
||
const sizeParam = byKey.size;
|
||
const ratio = parseRatioText(rec.aspect_ratio);
|
||
if (sizeParam && ratio && out.size === undefined) {
|
||
let best = null;
|
||
let bestDiff = Infinity;
|
||
image.sizePresetsOf(sizeParam).forEach((s) => {
|
||
const diff = Math.abs(s.width / s.height - ratio) / ratio;
|
||
if (diff < bestDiff) {
|
||
best = s;
|
||
bestDiff = diff;
|
||
}
|
||
});
|
||
if (best && bestDiff <= 0.03) out.size = best.value;
|
||
}
|
||
return out;
|
||
};
|
||
|
||
/**
|
||
* 模板的推荐模型(WP B-7 模板墙):
|
||
* 1. 模板指定的 model 可用(未锁定)→ 它;
|
||
* 2. 当前模型可用且支持该 kind 的文生模式 → 保持当前模型(不悄悄改变价格);
|
||
* 3. 否则:带"推荐"徽标且支持文生的模型 → 任一支持文生的模型 → 任一可用模型。
|
||
* 返回 null 表示没有可用模型。
|
||
*/
|
||
export const templateModelFor = (kind, tpl, models, current) => {
|
||
const list = (Array.isArray(models) ? models : []).filter(
|
||
(m) => m && !m.level_locked,
|
||
);
|
||
if (!list.length) return null;
|
||
const textMode = kind === 'video' ? 'text2video' : 'text2image';
|
||
const supportsText = (m) => (m.modes || []).includes(textMode);
|
||
if (tpl && tpl.model) {
|
||
const hit = list.find((m) => m.model === tpl.model);
|
||
if (hit) return hit;
|
||
}
|
||
if (current && !current.level_locked && supportsText(current)) {
|
||
const stillThere = list.find((m) => m.model === current.model);
|
||
if (stillThere) return stillThere;
|
||
}
|
||
return (
|
||
list.find(
|
||
(m) => supportsText(m) && (m.badges || []).includes('recommended'),
|
||
) ||
|
||
list.find(supportsText) ||
|
||
list[0]
|
||
);
|
||
};
|
||
|
||
/** 模板推荐参数的简短说明("16:9 · 5s"),模板卡片上展示。 */
|
||
export const templateParamsSummary = (tpl) => {
|
||
const p = (tpl && tpl.params) || {};
|
||
const parts = [];
|
||
if (p.aspect_ratio) parts.push(String(p.aspect_ratio));
|
||
if (p.duration) parts.push(`${p.duration}s`);
|
||
return parts.join(' · ');
|
||
};
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// 提示词历史(WP B-6 补齐旧图像表单的"提示词历史",按 kind 分开,最多 10 条)
|
||
// ---------------------------------------------------------------------------
|
||
|
||
export const PROMPT_HISTORY_MAX = 10;
|
||
|
||
export const promptHistoryKeyOf = (kind) => `creation.${kind}.promptHistory`;
|
||
|
||
/** 读取提示词历史(无效数据返回 [])。 */
|
||
export const loadPromptHistory = (storage, kind) => {
|
||
if (!storage) return [];
|
||
try {
|
||
const list = JSON.parse(storage.getItem(promptHistoryKeyOf(kind)) || '[]');
|
||
return Array.isArray(list)
|
||
? list
|
||
.filter((p) => typeof p === 'string' && p.trim())
|
||
.slice(0, PROMPT_HISTORY_MAX)
|
||
: [];
|
||
} catch (e) {
|
||
return [];
|
||
}
|
||
};
|
||
|
||
/** 把提示词放到最前(去重、去首尾空白、截断到上限)。 */
|
||
export const pushPromptHistory = (list, prompt, max = PROMPT_HISTORY_MAX) => {
|
||
const text = typeof prompt === 'string' ? prompt.trim() : '';
|
||
const prev = Array.isArray(list) ? list : [];
|
||
if (!text) return prev;
|
||
return [text, ...prev.filter((p) => p !== text)].slice(0, max);
|
||
};
|
||
|
||
/** 写入并返回新的历史(存储失败时仍返回内存中的新值)。 */
|
||
export const savePromptHistory = (storage, kind, list, prompt) => {
|
||
const next = pushPromptHistory(list, prompt);
|
||
if (storage) {
|
||
try {
|
||
storage.setItem(promptHistoryKeyOf(kind), JSON.stringify(next));
|
||
} catch (e) {
|
||
// 存储不可用时只保留在内存
|
||
}
|
||
}
|
||
return next;
|
||
};
|