12 个视觉参考图库与浏览器无限画布 AI 创作台(5,700+ 素材、中英提示词、多图对比、ComfyUI & MCP)· Visual reference library & infinite-canvas AI studio in the browser
JavaScript ai-artai-try-onchinesecloudflare-pagescomfyuidrawing-referencefashiongeminigpt-imageimage-generationinfinite-canvasmcpmoodboardoutfit-referencepose-referencepromptpwareference-boardseedreamvirtual-try-on
'use strict';
(() => {
// Named Character & Scene Recipes (造型方案 / 角色档案) stored in localStorage['wbRecipes'].
// Lets artists save, load, keep-pose-swap, and JSON-backup reusable character/outfit/scene sets.
const C = window.PoseWearCatalog;
if (!C) return;
const { $, esc, readLS: LS, writeLS: SV } = C;
const KEY = 'wbRecipes';
const MAX_RECIPES = 60;
let studioApi = null;
let prevFocus = null;
let recipes = [];
function loadStore() {
const raw = LS(KEY);
recipes = Array.isArray(raw) ? raw.filter(r => r && typeof r.id === 'string' && typeof r.name === 'string') : [];
}
function saveStore() {
SV(KEY, recipes.slice(0, MAX_RECIPES));
updateBadge();
}
function updateBadge() {
const badge = $('#wbRecipeN');
if (!badge) return;
badge.hidden = !recipes.length;
badge.textContent = recipes.length ? String(recipes.length) : '';
}
function allKeysOf(refs) {
if (!refs) return [];
const list = [
...(refs.r || []),
...(refs.g || []),
...(refs.p || []),
...(refs.e || []),
...(refs.x || []),
];
return list.map(entry => (Array.isArray(entry) ? entry[0] : entry)).filter(k => typeof k === 'string');
}
function refCount(refs) {
return allKeysOf(refs).length;
}
function refEntries(refs) {
if (!refs) return [];
const out = [];
for (const key of refs.r || []) out.push({ k: key });
for (const g of refs.g || []) out.push(Array.isArray(g) ? { k: g[0], ai: g[1] } : { k: g });
for (const p of refs.p || []) out.push(Array.isArray(p) ? { k: p[0], ai: p[1] } : { k: p });
for (const e of refs.e || []) out.push(Array.isArray(e) ? { k: e[0], ai: e[1] } : { k: e });
for (const x of refs.x || []) out.push(Array.isArray(x) ? { k: x[0], ai: x[1] } : { k: x });
return out;
}
function suggestName(snap) {
const A = window.APP;
if (!A) return '我的造型方案';
const entries = refEntries(snap.refs);
const names = [];
for (const ref of entries) {
const it = A.ITEMS[ref.k];
if (!it) continue;
const t = A.title(it);
if (t && !names.includes(t)) names.push(t);
if (names.length >= 2) break;
}
return names.length ? names.join(' · ') : '我的造型方案';
}
function renderList() {
const listEl = $('#rcpList');
const emptyEl = $('#rcpEmpty');
const countEl = $('#rcpCount');
if (!listEl) return;
const A = window.APP;
if (countEl) countEl.textContent = recipes.length ? `${recipes.length} / ${MAX_RECIPES}` : '';
if (!recipes.length) {
listEl.innerHTML = '';
if (emptyEl) emptyEl.hidden = false;
return;
}
if (emptyEl) emptyEl.hidden = true;
const hasCurrentPose = !!(studioApi && studioApi.hasPoses());
listEl.innerHTML = recipes
.map(r => {
const entries = refEntries(r.refs);
const thumbs = entries
.slice(0, 4)
.map(ref => {
const it = A?.ITEMS[ref.k];
if (!it) return '';
const src = it.angles ? A.ath(it.angles[ref.ai ?? it.ai]?.t || it.angles[0].t) : A.thumb(it);
return `<img src="${esc(src)}" alt=""${it.ref ? ` referrerpolicy="${esc(it.ref)}"` : ''}>`;
})
.filter(Boolean)
.join('');
const count = refCount(r.refs);
const dt = new Date(r.t || Date.now());
const stamp = `${dt.getMonth() + 1}/${dt.getDate()} ${String(dt.getHours()).padStart(2, '0')}:${String(dt.getMinutes()).padStart(2, '0')}`;
const hasChar = (r.refs?.r?.length || 0) + (r.refs?.g?.length || 0) + (r.refs?.e?.length || 0) + (r.refs?.x?.length || 0) > 0;
const keepPoseBtn = hasCurrentPose && hasChar
? `<button type="button" class="sm ghost" data-rcp-keep="${esc(r.id)}" title="保留当前工作台姿势,只换角色与服饰">保留当前姿势</button>`
: '';
return (
`<article class="rcp-item" data-rcp="${esc(r.id)}">` +
`<div class="rcp-thumbs">${thumbs || '<span class="rcp-ph">Aa</span>'}</div>` +
`<div class="rcp-meta">` +
`<b class="recipe-name" title="${esc(r.name)}">${esc(r.name)}</b>` +
`<small><span>${count ? `${count} 项参考` : '纯提示词'}</span>${r.ar && r.ar !== 'auto' ? ' · ' + esc(r.ar) : ''} · ${esc(stamp)}</small>` +
`</div>` +
`<div class="rcp-act">` +
`<button type="button" class="sm pri" data-rcp-load="${esc(r.id)}">载入</button>` +
`${keepPoseBtn}` +
`<button type="button" class="sm ghost rcp-del" data-rcp-del="${esc(r.id)}" aria-label="删除" title="删除">×</button>` +
`</div></article>`
);
})
.join('');
}
async function open(opener = document.activeElement) {
const box = $('#recipeBox');
if (!box || !studioApi) return;
loadStore();
prevFocus = opener;
const snap = studioApi.snapshot();
const input = $('#rcpName');
if (input) {
input.value = '';
input.placeholder = suggestName(snap);
}
const localNote = $('#rcpLocalNote');
if (localNote) localNote.hidden = !snap.hasLocalUploads;
const saveBtn = $('#rcpSave');
if (saveBtn) saveBtn.disabled = !refCount(snap.refs) && !snap.prompt && !snap.extra;
box.hidden = false;
document.body.style.overflow = 'hidden';
renderList();
const keys = [...new Set(recipes.flatMap(r => allKeysOf(r.refs)))];
if (keys.length && window.APP?.needKeys) {
window.APP.needKeys(keys)
.then(() => {
if (!box.hidden) renderList();
})
.catch(() => {});
}
input?.focus({ preventScroll: true });
}
function close() {
const box = $('#recipeBox');
if (!box || box.hidden) return;
box.hidden = true;
document.body.style.overflow = '';
if (prevFocus?.isConnected) prevFocus.focus({ preventScroll: true });
prevFocus = null;
}
function saveCurrent() {
if (!studioApi) return;
const snap = studioApi.snapshot();
if (!refCount(snap.refs) && !snap.prompt && !snap.extra) {
window.APP?.toast('请先选择参考素材或输入提示词');
return;
}
const input = $('#rcpName');
const name = (input?.value || '').trim() || suggestName(snap);
const entry = {
id: 'r_' + Date.now().toString(36) + '_' + Math.random().toString(36).slice(2, 6),
name: name.slice(0, 48),
t: Date.now(),
mode: snap.mode,
style: snap.style,
shot: snap.shot,
ar: snap.ar,
pl: snap.pl,
extra: snap.extra,
neg: snap.neg,
prompt: snap.prompt,
refs: snap.refs,
};
recipes.unshift(entry);
if (recipes.length > MAX_RECIPES) recipes.length = MAX_RECIPES;
saveStore();
if (input) input.value = '';
renderList();
window.APP?.toast(snap.hasLocalUploads ? '已保存方案(本地上传图仅限本次会话)' : '已保存造型方案');
}
async function applyRecipe(id, keepCurrentPose = false) {
const target = recipes.find(r => r.id === id);
if (!target || !studioApi) return;
close();
await studioApi.applyRecipe(target, { keepCurrentPose });
window.APP?.toast(keepCurrentPose ? '已套用方案并保留当前姿势' : `已载入方案「${target.name}」`);
}
function deleteRecipe(id) {
const idx = recipes.findIndex(r => r.id === id);
if (idx < 0) return;
const [removed] = recipes.splice(idx, 1);
saveStore();
renderList();
window.APP?.toast('已删除方案', () => {
recipes.splice(Math.min(idx, recipes.length), 0, removed);
saveStore();
if (!$('#recipeBox')?.hidden) renderList();
});
}
function exportJson() {
if (!recipes.length) return window.APP?.toast('还没有已保存的方案');
const blob = new Blob(
[JSON.stringify({ app: '衣姿 PoseWear', type: 'studio-recipes', exportedAt: new Date().toISOString(), recipes }, null, 2)],
{ type: 'application/json' }
);
window.X?.dl?.(blob, `posewear-recipes-${new Date().toISOString().slice(0, 10)}.json`);
window.APP?.toast(`已导出 ${recipes.length} 个方案`);
}
function sanitizeSlot(arr, maxLen, allowTuple) {
if (!Array.isArray(arr)) return [];
const out = [];
for (const entry of arr) {
if (out.length >= maxLen) break;
if (typeof entry === 'string' && entry.length > 0 && entry.length <= 80) {
out.push(entry);
} else if (
allowTuple &&
Array.isArray(entry) &&
typeof entry[0] === 'string' &&
entry[0].length > 0 &&
entry[0].length <= 80
) {
const ai = Number.isInteger(entry[1]) && entry[1] >= 0 && entry[1] < 32 ? entry[1] : 0;
out.push([entry[0], ai]);
}
}
return out;
}
async function importJson(file) {
if (!file) return;
if (file.size > 2 * 1024 * 1024) {
window.APP?.toast('导入失败:文件格式不正确');
return;
}
try {
const parsed = JSON.parse(await file.text());
const incoming = Array.isArray(parsed?.recipes) ? parsed.recipes : Array.isArray(parsed) ? parsed : null;
if (!incoming) throw Error('invalid');
const existingIds = new Set(recipes.map(r => r.id));
let added = 0;
for (const item of incoming.slice(0, MAX_RECIPES)) {
if (!item || typeof item.name !== 'string' || !item.name.trim() || !item.refs || typeof item.refs !== 'object') continue;
const id = typeof item.id === 'string' && item.id.length <= 64 && !existingIds.has(item.id)
? item.id
: 'r_' + Date.now().toString(36) + '_' + Math.random().toString(36).slice(2, 6);
existingIds.add(id);
recipes.unshift({
id,
name: item.name.trim().slice(0, 48),
t: Number.isFinite(Number(item.t)) && Number(item.t) > 0 ? Number(item.t) : Date.now(),
mode: item.mode === 'tryon' ? 'tryon' : 'gen',
style: typeof item.style === 'string' ? item.style.slice(0, 32) : 'keep',
shot: typeof item.shot === 'string' ? item.shot.slice(0, 32) : 'auto',
ar: typeof item.ar === 'string' ? item.ar.slice(0, 16) : 'auto',
pl: item.pl === 'zh' ? 'zh' : 'en',
extra: typeof item.extra === 'string' ? item.extra.slice(0, 1000) : '',
neg: typeof item.neg === 'string' ? item.neg.slice(0, 1000) : '',
prompt: typeof item.prompt === 'string' ? item.prompt.slice(0, 4000) : null,
refs: {
r: sanitizeSlot(item.refs.r, 3, false),
g: sanitizeSlot(item.refs.g, 2, true),
p: sanitizeSlot(item.refs.p, 6, true),
e: sanitizeSlot(item.refs.e, 1, true),
x: sanitizeSlot(item.refs.x, 12, true),
},
});
added++;
}
if (!added) {
window.APP?.toast('导入失败:文件中没有有效的方案');
return;
}
if (recipes.length > MAX_RECIPES) recipes.length = MAX_RECIPES;
saveStore();
renderList();
const keys = [...new Set(recipes.flatMap(r => allKeysOf(r.refs)))];
if (keys.length && window.APP?.needKeys) window.APP.needKeys(keys).then(renderList).catch(() => {});
window.APP?.toast(`已导入 ${added} 个方案`);
} catch {
window.APP?.toast('导入失败:文件格式不正确');
}
}
function isOpen() {
const box = $('#recipeBox');
return !!(box && !box.hidden);
}
function init(api) {
studioApi = api;
loadStore();
updateBadge();
$('#wbRecipesBtn')?.addEventListener('click', e => open(e.currentTarget));
$('#rcpX')?.addEventListener('click', close);
$('#rcpSave')?.addEventListener('click', saveCurrent);
$('#rcpName')?.addEventListener('keydown', e => {
if (e.key === 'Enter') {
e.preventDefault();
saveCurrent();
}
});
$('#rcpExp')?.addEventListener('click', exportJson);
$('#rcpImp')?.addEventListener('click', () => $('#rcpImpF')?.click());
$('#rcpImpF')?.addEventListener('change', async e => {
await importJson(e.target.files?.[0]);
e.target.value = '';
});
$('#recipeBox')?.addEventListener('click', e => {
if (e.target.id === 'recipeBox') return close();
const loadBtn = e.target.closest('[data-rcp-load]');
if (loadBtn) return applyRecipe(loadBtn.dataset.rcpLoad, false);
const keepBtn = e.target.closest('[data-rcp-keep]');
if (keepBtn) return applyRecipe(keepBtn.dataset.rcpKeep, true);
const delBtn = e.target.closest('[data-rcp-del]');
if (delBtn) return deleteRecipe(delBtn.dataset.rcpDel);
});
}
window.PoseWearRecipes = {
init,
open,
close,
isOpen,
count: () => recipes.length,
list: () => recipes.slice(),
};
})();