Files
aigc-home/prototypes/hel-646-flow-desk/app.js
T
施工员andmultica-agent 8d2df11919 proto: 流水台整站布局与交互隔离原型 (HEL-646)
纯 HTML/CSS/JS 零依赖原型,与 calliope-web 正式代码隔离,不合并、不部署。
含方案.md、关键画面截图与测试站真实素材。

Co-authored-by: multica-agent <github@multica.ai>
2026-09-29 21:36:02 +08:00

1223 lines
78 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.
/* HEL-646 流水台原型:纯前端模拟,数据取自测试站 192.168.200.15:8080 的真实工作流与任务记录。 */
(() => {
'use strict';
const $ = (s, r = document) => r.querySelector(s);
const $$ = (s, r = document) => Array.from(r.querySelectorAll(s));
const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const root = document.documentElement;
const reduceQuery = matchMedia('(prefers-reduced-motion: reduce)');
const reduced = () => reduceQuery.matches || root.dataset.reduce === '1';
const icon = (id) => `<svg><use href="#i-${id}"/></svg>`;
const USAGE = {
text2image: '文生图', image2image: '图生图', text2video: '文生视频', image2video: '图生视频', ref2video: '参考图生视频',
};
const USAGE_ORDER = ['text2image', 'image2image', 'text2video', 'image2video', 'ref2video'];
const CONNS = [
{ id: 'local', name: '本机 ComfyUI-4080', url: 'http://192.168.200.12:8188', ok: true, ms: 22 },
{ id: 'hy', name: '恒源云', url: 'http://127.0.0.1:6008', ok: false, err: '连接被拒绝:目标端口没有服务在监听' },
];
const H3_PARAMS = [
{ key: 'aspect', label: '画面比例', kind: 'select', orig: '16:9', options: ['16:9', '9:16', '1:1', '4:3', '21:9'], common: true },
{ key: 'duration', label: '时长(秒)', kind: 'select', orig: '10', options: ['3', '5', '8', '10'], common: true, unit: '秒' },
{ key: 'seed', label: '随机种子', kind: 'seed', orig: '42', common: true },
{ key: 'megapixels', label: '总像素(百万)', kind: 'number', orig: '0.7', step: 0.1 },
{ key: 'steps', label: '采样步数', kind: 'number', orig: '4' },
{ key: 'denoise', label: '降噪强度', kind: 'number', orig: '1', step: 0.05 },
];
const QWEN_T2I = [
{ key: 'aspect', label: '画面比例', kind: 'select', orig: '1:1', options: ['1:1', '3:4', '4:3', '16:9', '9:16'], common: true },
{ key: 'seed', label: '随机种子', kind: 'seed', orig: '593103825222985', common: true },
{ key: 'negative', label: '反向提示词', kind: 'textarea', orig: '' },
{ key: 'megapixels', label: '总像素(百万)', kind: 'number', orig: '1', step: 0.1 },
{ key: 'batch', label: '批次数量', kind: 'number', orig: '1' },
{ key: 'steps', label: '采样步数', kind: 'number', orig: '25' },
{ key: 'cfg', label: 'CFG', kind: 'number', orig: '1', step: 0.1 },
{ key: 'denoise', label: '降噪强度', kind: 'number', orig: '1', step: 0.05 },
];
const workflows = [
{ id: 13, name: 'H3 参考生视频·参考图(05 用户提供)', usage: 'ref2video', kind: 'video', conn: 'local', status: 'ok', statusText: '可用 · 近 3 次成功',
slots: [{ key: 'ref', label: '参考图', type: 'list', min: 1, max: 9 }], params: H3_PARAMS,
note: 'MiniMax H3 Ref2VA 官方限额:参考图最多 9 张;本工作流 JSON 只连了参考图,不显示参考视频 / 音频入口。',
defaultPrompt: '' },
{ id: 12, name: 'H3 图生视频·首帧(04 用户提供)', usage: 'image2video', kind: 'video', conn: 'local', status: 'ok', statusText: '可用 · 近 2 次成功',
slots: [{ key: 'first', label: '首帧图', type: 'single' }], params: H3_PARAMS, note: '首帧决定画面外观,提示词描述运动。' },
{ id: 11, name: 'Qwen Image 2.1 图片编辑(用户提供)', usage: 'image2image', kind: 'image', conn: 'local', status: 'error', statusText: '不可用 · 文件不完整',
slots: [{ key: 'image', label: '输入图', type: 'single' }],
params: [
{ key: 'resolution', label: '输出分辨率', kind: 'number', orig: '1024', common: true },
{ key: 'seed', label: '随机种子', kind: 'seed', orig: '278835418249884', common: true },
{ key: 'negative', label: '反向提示词', kind: 'textarea', orig: '模糊,低质量,文字乱码,变形' },
{ key: 'steps', label: '采样步数', kind: 'number', orig: '25' },
{ key: 'cfg', label: 'CFG', kind: 'number', orig: '1', step: 0.1 },
{ key: 'denoise', label: '降噪强度', kind: 'number', orig: '1', step: 0.05 },
],
errors: [
'节点 1「Unet Loader (GGUF)」缺少节点类型(class_type),导出时 ComfyUI 未加载该自定义节点',
'节点 9「Patch Sage Attention KJ」缺少节点类型(class_type),导出时 ComfyUI 未加载该自定义节点',
'节点 6「K采样器」(KSampler)没有连接模型(model),模型加载链路在导出时丢失',
] },
{ id: 10, name: 'qwen2.1', usage: 'text2image', kind: 'image', conn: 'local', status: 'ok', statusText: '可用 · 09-29 19:26 试运行通过', slots: [], params: QWEN_T2I },
{ id: 7, name: 'qwen-image-2.1', usage: 'text2image', kind: 'image', conn: null, status: 'idle', statusText: '未试运行 · 跟随默认连接', slots: [], params: QWEN_T2I },
{ id: 6, name: 'minimaxh3-文生图加速版', usage: 'text2video', kind: 'video', conn: null, status: 'idle', statusText: '未试运行 · 名称含“文生图”,实际判定为文生视频', slots: [], params: H3_PARAMS },
{ id: 5, name: 'MiniMax H3 文生视频(审核示例)', usage: 'text2video', kind: 'video', conn: null, status: 'idle', statusText: '未试运行',
slots: [], params: [
{ key: 'duration', label: 'Seconds', kind: 'select', orig: '10', options: ['5', '10'], common: true, unit: '秒' },
{ key: 'fps', label: 'fps', kind: 'number', orig: '24' },
] },
{ id: 4, name: 'Krea2 文生图(审核示例)', usage: 'text2image', kind: 'image', conn: null, status: 'warn', statusText: '上次失败 · 连接上缺 3 个模型', slots: [], params: [] },
];
const A = 'assets/';
const G = [
'linear-gradient(135deg,#6a5cff,#ff7ac6)', 'linear-gradient(135deg,#ff9a3c,#ffd36e)', 'linear-gradient(135deg,#1f8f7a,#9be15d)',
'linear-gradient(135deg,#2336a8,#5bc0ff)', 'linear-gradient(135deg,#8a2be2,#4b0082)', 'linear-gradient(135deg,#f25f5c,#247ba0)',
];
let seq = 100;
const takes = [
{ id: 16, wf: 6, scope: 'standalone', day: '昨天', time: '09-28 23:33', prompt: 'integrated_multimodal_description: a red paper lantern drifting slowly upward through light evening snow over a quiet canal, rippling water reflections',
inputs: [], params: { aspect: '16:9', duration: '3', seed: '42' }, status: 'done', elapsed: '2 分 10 秒',
out: { poster: A + 'v-t2v-16.jpg', src: A + 'v-t2v-16.mp4', w: 736, h: 416, dur: '0:02' } },
{ id: 21, wf: 6, scope: 'standalone', day: '昨天', time: '09-28 23:43', prompt: '(沿用工作流原值)地铁站台十镜头参考提示词',
inputs: [], params: { aspect: '16:9', duration: '5', seed: '42' }, status: 'done', elapsed: '2 分 42 秒',
out: { poster: A + 'v-t2v-21.jpg', src: A + 'v-t2v-21.mp4', w: 736, h: 416, dur: '0:05' } },
{ id: 31, wf: 4, scope: 'p1', source: '《雨夜便利店》创作流程', day: '今天', time: '09-29 08:48', prompt: 'Cinematic extreme wide static shot. Outside the modern 24-hour convenience store at night, heavy rain falls like a curtain…',
inputs: [], params: {}, status: 'failed',
error: { title: 'ComfyUI 拒绝执行:连接上缺 3 个模型文件', items: [
'节点 149(CLIPLoader):ComfyUI 上没有「qwen3vl_4b_fp8_scaled.safetensors」',
'节点 148(UNETLoader):ComfyUI 上没有「Krea-2-Turbo.safetensors」',
'节点 152(LoraLoaderModelOnly):ComfyUI 上没有「krea2/Krea2-realism-V2.safetensors」',
], raw: 'HTTP 400 · prompt_outputs_failed_validation' } },
{ id: 35, wf: 12, scope: 'standalone', day: '今天', time: '09-29 10:41', prompt: '镜头缓缓推进,画面中渐变色彩的微光流动',
inputs: [{ bg: G[3], name: 'test-a.png' }], params: { aspect: '16:9', duration: '3', seed: '42' }, status: 'done', elapsed: '49 秒',
out: { poster: A + 'v-i2v-35.jpg', src: A + 'v-i2v-35.mp4', w: 1152, h: 640, dur: '0:03' } },
{ id: 40, wf: 10, scope: 'standalone', day: '今天', time: '09-29 16:41', prompt: '一只戴墨镜的橘猫坐在电影院前排, 电影放映的光束打在毛上, 胶片感',
inputs: [], params: { aspect: '1:1', seed: '593103825222985' }, status: 'missing', elapsed: '14 秒',
out: { name: 'Qwen_image_2.1_00003.png', w: 1024, h: 1024 } },
{ id: 43, wf: 10, scope: 'standalone', day: '今天', time: '09-29 19:59', prompt: 'Greyscale fashion editorial portrait of an avant-garde woman tilted upwards in profile, captured with striking high-contrast chiaroscuro lighting. She wears oversized, thick-rimmed circular black sunglasses…',
inputs: [], params: { aspect: '3:4', seed: '593103825222985' }, status: 'done', elapsed: '13 秒',
out: { poster: A + 'i-t2i-43.jpg', src: A + 'i-t2i-43.jpg', w: 888, h: 1184, image: true } },
{ id: 44, wf: 13, scope: 'standalone', day: '今天', time: '09-29 20:00', prompt: '让图片中的人物动起来',
inputs: [{ bg: `url(${A}i-t2i-43.jpg)`, name: 'Qwen_image_2.1_00005.png' }], params: { aspect: '16:9', duration: '5', seed: '42', megapixels: '0.4' }, status: 'done', elapsed: '44 秒',
out: { poster: A + 'v-ref2v-44.jpg', src: A + 'v-ref2v-44.mp4', w: 864, h: 480, dur: '0:05' } },
];
const RESULT_FOR = {
ref2video: { poster: A + 'v-ref2v-44.jpg', src: A + 'v-ref2v-44.mp4', w: 864, h: 480, dur: '0:05' },
image2video: { poster: A + 'v-i2v-35.jpg', src: A + 'v-i2v-35.mp4', w: 1152, h: 640, dur: '0:03' },
text2video: { poster: A + 'v-t2v-16.jpg', src: A + 'v-t2v-16.mp4', w: 736, h: 416, dur: '0:02' },
text2image: { poster: A + 'i-t2i-43.jpg', src: A + 'i-t2i-43.jpg', w: 888, h: 1184, image: true },
image2image: { poster: A + 'i-t2i-43.jpg', src: A + 'i-t2i-43.jpg', w: 888, h: 1184, image: true },
};
const state = {
wfId: 13,
connId: 'local',
slots: {},
params: {},
filter: 'all',
scope: 'all',
selected: 44,
context: null,
view: 'desk',
};
const wfById = (id) => workflows.find((w) => w.id === id);
const curWf = () => wfById(state.wfId);
const connById = (id) => CONNS.find((c) => c.id === id);
/* ---------------- Toast ---------------- */
function toast(text, opts = {}) {
const el = document.createElement('div');
el.className = 'toast';
el.innerHTML = `<span class="grow">${text}</span>${opts.action ? `<button>${esc(opts.action)}</button>` : ''}`;
$('#toasts').appendChild(el);
let done = false;
const close = () => {
if (done) return;
done = true;
el.classList.add('out');
setTimeout(() => el.remove(), reduced() ? 130 : 240);
};
if (opts.action) el.querySelector('button').addEventListener('click', () => { opts.onAction?.(); close(); });
setTimeout(() => { opts.onTimeout?.(); close(); }, opts.duration || 3200);
return close;
}
/* ---------------- 浮层管理 ---------------- */
const layers = [];
function openLayer(el, { anchor, instant, origin, onClose, trigger } = {}) {
closeLayer(el, true);
el.classList.toggle('instant', !!instant || false);
if (anchor && innerWidth > 760) {
const r = anchor.getBoundingClientRect();
const w = el.offsetWidth || 520;
let left = Math.min(r.left, innerWidth - w - 12);
if (origin === 'top right') left = Math.max(12, r.right - w);
el.style.left = left + 'px';
if (origin && origin.startsWith('top')) { el.style.top = r.bottom + 8 + 'px'; el.style.bottom = 'auto'; }
else { el.style.top = 'auto'; el.style.bottom = innerHeight - r.top + 8 + 'px'; }
el.style.setProperty('--origin', origin || 'bottom left');
} else if (innerWidth > 760) {
el.style.left = `calc(50% - ${(el.offsetWidth || 520) / 2}px)`;
el.style.top = '12vh';
el.style.bottom = 'auto';
el.style.setProperty('--origin', 'top center');
}
el.classList.add('on');
layers.push({ el, onClose, trigger: trigger || document.activeElement });
}
function closeLayer(el, silent) {
const i = layers.findIndex((l) => l.el === el);
if (i < 0) return;
const [l] = layers.splice(i, 1);
el.classList.remove('on');
l.onClose?.();
if (!silent && l.trigger && document.contains(l.trigger)) l.trigger.focus({ preventScroll: true });
}
function closeTop() {
const l = layers[layers.length - 1];
if (l) { closeLayer(l.el); return true; }
return false;
}
document.addEventListener('pointerdown', (e) => {
for (const l of [...layers]) {
if (l.el.classList.contains('drawer')) continue;
if (l.el.id === 'inspector' && e.target.closest('#feed, .pop, .toast')) continue;
if (!l.el.contains(e.target) && !(l.trigger && l.trigger.contains?.(e.target))) closeLayer(l.el, true);
}
});
/* ---------------- 工作流选择面板 ---------------- */
let wfActive = 0;
let wfRows = [];
let wfFromCmd = false;
function renderWfList() {
const q = $('#wf-search').value.trim().toLowerCase();
const match = (w) => !q || w.name.toLowerCase().includes(q) || USAGE[w.usage].includes(q) || slotSummary(w).includes(q);
let html = '';
wfRows = [];
for (const u of USAGE_ORDER) {
const list = workflows.filter((w) => w.usage === u && match(w));
if (!list.length) continue;
html += `<div class="pop-group">${USAGE[u]} <span>${list.length}</span></div>`;
for (const w of list) {
const idx = wfRows.length;
wfRows.push({ type: 'wf', id: w.id });
const conn = w.conn ? connById(w.conn).name : '跟随默认连接';
const statusCls = w.status === 'ok' ? 'accent' : w.status === 'error' ? 'err' : w.status === 'warn' ? 'warn' : '';
html += `<button class="wf-row ${w.status === 'error' ? 'off' : ''}" role="option" data-i="${idx}" aria-selected="false">
<span class="n">${esc(w.name)}${w.id === state.wfId ? ' <span class="muted">· 当前</span>' : ''}</span>
<span class="s"><span class="tag">${slotSummary(w)}</span><span class="tag">${esc(conn)}</span></span>
<span class="r"><span class="tag ${statusCls}">${esc(w.statusText.split(' · ')[0])}</span></span>
</button>`;
}
}
if (wfFromCmd) {
const jumps = [
{ label: '跳转 · 雨夜便利店 / 镜头脚本(待确认)', go: () => nav('flow') },
{ label: '跳转 · 项目总览', go: () => nav('projects') },
].filter((j) => !q || j.label.includes(q));
if (jumps.length) {
html += '<div class="pop-group">跳转</div>';
for (const j of jumps) {
const idx = wfRows.length;
wfRows.push({ type: 'jump', go: j.go });
html += `<button class="wf-row" role="option" data-i="${idx}" aria-selected="false"><span class="n">${esc(j.label)}</span></button>`;
}
}
}
if (!wfRows.length) html = `<div class="note" style="margin:8px">没有匹配“${esc(q)}”的工作流。可以<button class="why" data-act="import">导入新的 ComfyUI JSON</button>。</div>`;
$('#wf-list').innerHTML = html;
wfActive = Math.max(0, Math.min(wfActive, wfRows.length - 1));
paintWfActive();
}
function paintWfActive() {
$$('#wf-list .wf-row').forEach((b) => b.setAttribute('aria-selected', String(+b.dataset.i === wfActive)));
$(`#wf-list .wf-row[data-i="${wfActive}"]`)?.scrollIntoView({ block: 'nearest' });
}
function pickWfRow(i) {
const row = wfRows[i];
if (!row) return;
closeLayer($('#wf-pop'));
if (row.type === 'jump') { row.go(); return; }
selectWorkflow(row.id);
}
function openWfPop(fromCmd) {
wfFromCmd = !!fromCmd;
$('#wf-search').value = '';
renderWfList();
wfActive = Math.max(0, wfRows.findIndex((r) => r.id === state.wfId));
paintWfActive();
openLayer($('#wf-pop'), fromCmd ? { instant: true, trigger: document.activeElement } : { anchor: $('#wf-chip'), origin: 'bottom left', trigger: $('#wf-chip') });
setTimeout(() => $('#wf-search').focus(), 0);
}
$('#wf-chip').addEventListener('click', () => ($('#wf-pop').classList.contains('on') ? closeLayer($('#wf-pop')) : openWfPop(false)));
$('#wf-search').addEventListener('input', () => { wfActive = 0; renderWfList(); });
$('#wf-search').addEventListener('keydown', (e) => {
if (e.key === 'ArrowDown') { wfActive = Math.min(wfRows.length - 1, wfActive + 1); paintWfActive(); e.preventDefault(); }
else if (e.key === 'ArrowUp') { wfActive = Math.max(0, wfActive - 1); paintWfActive(); e.preventDefault(); }
else if (e.key === 'Enter') { pickWfRow(wfActive); e.preventDefault(); }
});
$('#wf-list').addEventListener('click', (e) => {
const b = e.target.closest('.wf-row');
if (b) pickWfRow(+b.dataset.i);
if (e.target.closest('[data-act="import"]')) { closeLayer($('#wf-pop'), true); openImport(); }
});
$('#wf-list').addEventListener('pointermove', (e) => {
const b = e.target.closest('.wf-row');
if (b && +b.dataset.i !== wfActive) { wfActive = +b.dataset.i; paintWfActive(); }
});
$('#import-open').addEventListener('click', () => { closeLayer($('#wf-pop'), true); openImport(); });
function slotSummary(w) {
if (!w.slots.length) return '仅提示词';
return w.slots.map((s) => (s.type === 'list' ? `${s.label} ${s.min}–${s.max} 张` : `${s.label} ×1`)).join(' · ');
}
function selectWorkflow(id, { keepPrompt = true } = {}) {
const prev = curWf();
const w = wfById(id);
state.wfId = id;
// 已上传的图片跨工作流保留(按新槽位上限截断);参数回到新工作流原值
const nextSlots = {};
for (const s of w.slots) {
const carry = state.slots[s.key] || (prev.slots[0] ? state.slots[prev.slots[0].key] : null) || [];
nextSlots[s.key] = carry.slice(0, s.type === 'list' ? s.max : 1);
}
state.slots = nextSlots;
state.params = {};
if (!keepPrompt) $('#prompt').value = w.defaultPrompt || '';
if (w.conn) state.connId = w.conn;
renderComposer();
renderParams();
if (prev.id !== id) toast(`已切换到「${esc(w.name)}」· ${esc(slotSummary(w))}`, { duration: 2000 });
}
/* ---------------- 输入台 ---------------- */
function renderComposer() {
const w = curWf();
$('#wf-chip-label').textContent = w.name;
$('#wf-chip').classList.toggle('err', w.status === 'error');
renderSlots();
renderCommonChips();
validate();
}
function renderSlots() {
const w = curWf();
const box = $('#slots');
box.innerHTML = w.slots.map((s) => {
const items = state.slots[s.key] || [];
const max = s.type === 'list' ? s.max : 1;
const tiles = items.map((it, i) => `
<div class="tile filled" style="background-image:${it.bg.startsWith('url') || it.bg.startsWith('linear') ? it.bg : `url(${it.bg})`}" data-slot="${s.key}" data-i="${i}" title="${esc(it.name)}">
${s.type === 'list' ? `<span class="idx">${i + 1}</span>` : ''}
${it.uploading ? '<span class="ring">上传中</span>' : ''}
<button class="x" data-remove="${s.key}:${i}" aria-label="移除 ${esc(it.name)}">${icon('x')}</button>
</div>`).join('');
const add = items.length < max ? `<button class="tile add" data-add="${s.key}" aria-label="添加${esc(s.label)}">${icon('plus')}</button>` : '';
const hint = s.type === 'list' ? `${s.min}–${s.max} 张 · 已选 ${items.length}${items.length >= max ? ' · 已达上限' : ''}` : '必填 · 1 张';
return `<div class="slot-group">
<div class="slot-label">${esc(s.label)}<span class="req">*</span><span>${hint}</span>
${takes.some((t) => t.status === 'done' && t.out?.image) ? `<button class="why" style="color:var(--text-2)" data-from-results="${s.key}">从结果选</button>` : ''}
</div>
<div class="slot-row">${tiles}${add}</div>
<div class="slot-hint" data-hint="${s.key}"></div>
</div>`;
}).join('');
}
let pendingSlot = null;
$('#slots').addEventListener('click', (e) => {
const add = e.target.closest('[data-add]');
const rm = e.target.closest('[data-remove]');
const fr = e.target.closest('[data-from-results]');
if (add) { pendingSlot = add.dataset.add; $('#file-input').multiple = curWf().slots.find((s) => s.key === pendingSlot).type === 'list'; $('#file-input').click(); }
if (rm) {
const [k, i] = rm.dataset.remove.split(':');
state.slots[k].splice(+i, 1);
renderSlots(); validate();
}
if (fr) openFromResults(fr);
});
$('#file-input').addEventListener('change', (e) => { addFiles(pendingSlot, e.target.files); e.target.value = ''; });
function slotHint(key, text, isErr) {
const el = $(`[data-hint="${key}"]`);
if (!el) return;
el.textContent = text;
el.classList.toggle('err', !!isErr);
clearTimeout(el._t);
el._t = setTimeout(() => { el.textContent = ''; }, 2600);
}
function addFiles(key, files) {
const w = curWf();
const slot = w.slots.find((s) => s.key === key) || w.slots[0];
if (!slot) { toast('当前工作流没有图片输入槽,不能添加图片。换一个图生图 / 图生视频 / 参考图生视频工作流再试。'); return; }
key = slot.key;
const max = slot.type === 'list' ? slot.max : 1;
state.slots[key] = state.slots[key] || [];
let rejected = 0; let overflow = 0;
for (const f of Array.from(files)) {
if (!/^image\/(png|jpeg|webp)$/.test(f.type)) { rejected++; continue; }
if (f.size > 20 * 1024 * 1024) { rejected++; continue; }
if (slot.type === 'single') state.slots[key] = [];
if (state.slots[key].length >= max) { overflow++; continue; }
const it = { bg: `url(${URL.createObjectURL(f)})`, name: f.name, uploading: true };
state.slots[key].push(it);
setTimeout(() => { it.uploading = false; renderSlots(); validate(); }, 450 + Math.random() * 500);
}
renderSlots(); validate();
if (rejected) slotHint(key, `有 ${rejected} 个文件未添加:仅支持 PNG / JPG / WebP,单张不超过 20MB`, true);
else if (overflow) slotHint(key, `已达上限 ${max} 张,多出的 ${overflow} 张未添加`, true);
}
function openFromResults(anchor) {
const key = anchor.dataset.fromResults;
const imgs = takes.filter((t) => t.status === 'done' && t.out?.image);
$('#menu-list').innerHTML = imgs.map((t) => `<button data-pick="${t.id}"><span class="tile" style="width:36px;height:36px;background-image:url(${t.out.poster})"></span><span>${esc(wfById(t.wf).name)}<br><span class="muted" style="font-size:11px">${t.time}</span></span></button>`).join('');
openLayer($('#menu-pop'), { anchor, origin: 'bottom left', trigger: anchor });
$('#menu-list').onclick = (e) => {
const b = e.target.closest('[data-pick]');
if (!b) return;
const t = takes.find((x) => x.id === +b.dataset.pick);
pushInput(key, { bg: `url(${t.out.poster})`, name: `结果 #${t.id}` });
closeLayer($('#menu-pop'));
};
}
function pushInput(key, it) {
const slot = curWf().slots.find((s) => s.key === key);
if (!slot) return false;
state.slots[key] = state.slots[key] || [];
if (slot.type === 'single') state.slots[key] = [];
if (state.slots[key].length >= slot.max) { slotHint(key, `已达上限 ${slot.max} 张`, true); return false; }
state.slots[key].push(it);
renderSlots(); validate();
return true;
}
// 拖入:整个输入台都是投放区,落在哪个槽就进哪个槽
const composer = $('#composer');
composer.addEventListener('dragover', (e) => {
if (!curWf().slots.length) return;
e.preventDefault();
const tile = e.target.closest('.tile.add') || $('#slots .tile.add');
$$('#slots .tile.add').forEach((t) => t.classList.toggle('drag', t === tile));
});
composer.addEventListener('dragleave', (e) => { if (!composer.contains(e.relatedTarget)) $$('#slots .tile.drag').forEach((t) => t.classList.remove('drag')); });
composer.addEventListener('drop', (e) => {
e.preventDefault();
const tile = e.target.closest('[data-add],[data-slot]');
$$('#slots .tile.drag').forEach((t) => t.classList.remove('drag'));
addFiles(tile ? tile.dataset.add || tile.dataset.slot : curWf().slots[0]?.key, e.dataTransfer.files);
});
function paramValue(p) { return state.params[p.key] ?? p.orig; }
function changedCount() { return curWf().params.filter((p) => state.params[p.key] !== undefined && state.params[p.key] !== p.orig).length; }
function renderCommonChips() {
const w = curWf();
const conn = connById(state.connId);
const chips = w.params.filter((p) => p.common).map((p) => {
const v = paramValue(p);
const changed = state.params[p.key] !== undefined && v !== p.orig;
if (p.kind === 'seed') return `<button class="chip opt-chip ${changed ? 'changed' : ''}" data-chip="${p.key}" title="点击换一个随机种子">${icon('dice')}<span class="lbl mono">种子 ${esc(String(v).slice(0, 8))}${String(v).length > 8 ? '…' : ''}</span></button>`;
return `<button class="chip opt-chip ${changed ? 'changed' : ''}" data-chip="${p.key}" aria-haspopup="menu"><span class="lbl">${esc(v)}${p.unit ? ' ' + p.unit : ''}</span>${icon('down')}</button>`;
});
chips.unshift(`<button class="chip opt-chip ${conn.ok ? '' : 'err'}" data-chip="conn" aria-haspopup="menu" title="${esc(conn.url)}"><span class="dot" style="width:7px;height:7px;border-radius:50%;background:${conn.ok ? 'var(--accent)' : 'var(--err)'}"></span><span class="lbl">${esc(conn.name)}</span></button>`);
$('#common-chips').innerHTML = chips.join('');
const n = changedCount();
$('#params-chip-label').textContent = n ? `参数 · 已改 ${n} 项` : '全部参数';
$('#params-chip').classList.toggle('changed', n > 0);
}
$('#common-chips').addEventListener('click', (e) => {
const b = e.target.closest('[data-chip]');
if (!b) return;
const key = b.dataset.chip;
if (key === 'conn') {
$('#menu-list').innerHTML = CONNS.map((c) => `<button data-conn="${c.id}" aria-selected="${c.id === state.connId}"><span class="dot" style="width:8px;height:8px;border-radius:50%;background:${c.ok ? 'var(--accent)' : 'var(--err)'}"></span><span>${esc(c.name)}<br><span class="muted" style="font-size:11px">${c.ok ? `测试通过 · ${c.ms} ms` : esc(c.err)}</span></span></button>`).join('');
openLayer($('#menu-pop'), { anchor: b, origin: 'bottom left', trigger: b });
$('#menu-list').onclick = (ev) => {
const x = ev.target.closest('[data-conn]');
if (!x) return;
state.connId = x.dataset.conn;
closeLayer($('#menu-pop'));
renderCommonChips(); validate();
};
return;
}
const p = curWf().params.find((q) => q.key === key);
if (p.kind === 'seed') { state.params.seed = String(Math.floor(Math.random() * 1e9)); renderCommonChips(); renderParams(); return; }
$('#menu-list').innerHTML = p.options.map((o) => `<button data-opt="${esc(o)}" aria-selected="${o === paramValue(p)}">${esc(o)}${p.unit ? ' ' + p.unit : ''}${o === p.orig ? ' <span class="muted">· 工作流原值</span>' : ''}</button>`).join('');
openLayer($('#menu-pop'), { anchor: b, origin: 'bottom left', trigger: b });
$('#menu-list').onclick = (ev) => {
const x = ev.target.closest('[data-opt]');
if (!x) return;
state.params[key] = x.dataset.opt;
closeLayer($('#menu-pop'));
renderCommonChips(); renderParams();
};
});
function validate() {
const w = curWf();
const why = $('#why');
const conn = connById(state.connId);
let msg = ''; let err = false; let act = null;
const missing = w.slots.filter((s) => (state.slots[s.key] || []).length < (s.type === 'list' ? s.min : 1));
const uploading = w.slots.some((s) => (state.slots[s.key] || []).some((it) => it.uploading));
if (w.status === 'error') { msg = '工作流不可用 · 查看原因'; err = true; act = () => showParamsTab(); }
else if (!conn.ok) { msg = `「${conn.name}」连不上 · 换连接`; err = true; act = () => $('[data-chip="conn"]')?.click(); }
else if (missing.length) { msg = `还缺:${missing.map((s) => s.label).join('、')}`; act = () => flashSlot(missing[0].key); }
else if (uploading) { msg = '素材上传中…'; }
else if (!$('#prompt').value.trim()) { msg = '还缺:提示词'; act = () => $('#prompt').focus(); }
why.hidden = !msg;
why.textContent = msg;
why.classList.toggle('err', err);
why.onclick = act;
$('#gen-btn').disabled = !!msg;
}
function flashSlot(key) {
const t = $(`[data-add="${key}"]`) || $(`[data-slot="${key}"]`);
if (!t) return;
t.classList.add('need');
t.focus();
setTimeout(() => t.classList.remove('need'), 1200);
if (innerWidth <= 760) composer.classList.add('expanded');
}
$('#prompt').addEventListener('input', () => {
const el = $('#prompt');
el.style.height = 'auto';
el.style.height = Math.min(el.scrollHeight, 180) + 'px';
validate();
});
$('#prompt').addEventListener('focus', () => { if (innerWidth <= 760) composer.classList.add('expanded'); });
document.addEventListener('pointerdown', (e) => {
if (innerWidth <= 760 && composer.classList.contains('expanded') && !composer.contains(e.target) && !e.target.closest('.pop')) composer.classList.remove('expanded');
});
/* ---------------- 提交与进度 ---------------- */
function submit() {
if ($('#gen-btn').disabled) { $('#why').click(); return; }
const w = curWf();
const conn = connById(state.connId);
const inputs = w.slots.flatMap((s) => (state.slots[s.key] || []).map((it) => ({ bg: it.bg, name: it.name })));
const params = {};
for (const p of w.params) params[p.key] = paramValue(p);
const t = {
id: ++seq, wf: w.id, scope: state.context ? 'p1' : 'standalone', source: state.context ? '《雨夜便利店》镜头 S1' : null,
day: '今天', time: nowStr(), prompt: $('#prompt').value.trim(), inputs, params, status: 'queued', progress: 0, phase: '提交中', isNew: true, demo: true,
conn: conn.name,
};
takes.push(t);
state.selected = t.id;
if (state.filter === 'failed' || (state.filter !== 'all' && state.filter !== w.kind)) setFilter('all');
renderFeed({ scrollToEnd: true });
renderPreview(false);
updateTray();
composer.classList.remove('expanded');
runSim(t);
}
function nowStr() {
const d = new Date();
const p = (n) => String(n).padStart(2, '0');
return `09-29 ${p(d.getHours())}:${p(d.getMinutes())}`;
}
function runSim(t) {
const w = wfById(t.wf);
const steps = w.kind === 'video'
? [[t.inputs.length ? '上传素材' : '提交到 ComfyUI', 0.05], ['排队中 · 第 1 位', 0.08], ['采样 1/4', 0.25], ['采样 2/4', 0.42], ['采样 3/4', 0.6], ['采样 4/4', 0.76], ['解码视频', 0.9], ['保存结果', 0.97]]
: [['提交到 ComfyUI', 0.05], ['排队中 · 第 1 位', 0.1], ['采样 8/25', 0.35], ['采样 17/25', 0.65], ['采样 25/25', 0.88], ['保存结果', 0.97]];
let i = 0;
const started = Date.now();
const tick = () => {
if (!takes.includes(t)) return;
if (i < steps.length) {
const [phase, p] = steps[i++];
t.status = i <= 2 ? 'queued' : 'running';
t.phase = phase; t.progress = p;
t.elapsedMs = Date.now() - started;
patchTake(t);
if (state.selected === t.id) renderPreview(false);
setTimeout(tick, 650 + Math.random() * 300);
} else {
t.status = 'done';
t.justDone = true;
t.progress = 1;
t.out = { ...RESULT_FOR[w.usage] };
t.elapsed = `${Math.round((Date.now() - started) / 1000)} 秒(演示加速)`;
patchTake(t, true);
updateTray();
if (state.selected === t.id) renderPreview(true);
if (!isTakeVisible(t)) toast(`「${esc(w.name)}」已完成`, { action: '查看', onAction: () => selectTake(t.id, { scroll: true }) });
}
updateTray();
};
setTimeout(tick, 250);
}
function isTakeVisible(t) {
const el = $(`.take[data-id="${t.id}"]`);
if (!el || state.view !== 'desk') return false;
const r = el.getBoundingClientRect(); const f = $('#feed').getBoundingClientRect();
return r.bottom > f.top && r.top < f.bottom;
}
$('#gen-btn').addEventListener('click', submit);
/* ---------------- 记录流 ---------------- */
function visibleTakes() {
return takes.filter((t) => {
if (state.scope !== 'all' && t.scope !== state.scope) return false;
const w = wfById(t.wf);
if (state.filter === 'image') return w.kind === 'image';
if (state.filter === 'video') return w.kind === 'video';
if (state.filter === 'failed') return t.status === 'failed' || t.status === 'missing';
return true;
});
}
function takeHTML(t) {
const w = wfById(t.wf);
const sel = t.id === state.selected;
const src = t.source || (w.kind === 'video' ? '独立生视频' : '独立生图');
const inputs = t.inputs.length
? `<div class="take-inputs">${t.inputs.slice(0, 4).map((i) => `<span class="mini" style="background-image:${i.bg}" title="${esc(i.name)}"></span>`).join('')}${t.inputs.length > 4 ? `<span class="more">+${t.inputs.length - 4}</span>` : ''}</div>` : '';
let out = '';
const portrait = t.out && t.out.h > t.out.w;
if (t.status === 'done') {
out = `<div class="thumb ${portrait ? 'portrait' : ''} ${t.justDone ? 'fresh' : ''}" style="background-image:url(${t.out.poster})">${t.out.image ? '' : `<span class="play">${icon('play')}</span><span class="badge">${t.out.dur}</span>`}</div>`;
} else if (t.status === 'missing') {
out = '<div class="thumb missing">结果文件已不在<br>服务器上</div>';
} else if (t.status === 'failed') {
out = '<div class="thumb missing" style="border-color:var(--err-soft);color:var(--err)">未生成</div>';
} else {
out = `<div class="thumb pending ${w.kind === 'image' ? 'portrait' : ''}">${esc(t.phase)}</div>`;
}
let st = '';
if (t.status === 'done') st = `<span class="tag accent">完成</span><span class="txt">用时 ${esc(t.elapsed)}</span>`;
else if (t.status === 'queued' || t.status === 'running') st = `<span class="tag run">${t.status === 'queued' ? '排队' : '生成中'}</span><span class="bar"><i style="--p:${t.progress}"></i></span><span class="txt mono">${esc(t.phase)} · ${Math.round(t.progress * 100)}%</span><button class="btn sm ghost" data-act="cancel">取消</button>`;
else if (t.status === 'failed') st = `<span class="tag err">失败</span><span class="err-txt">${esc(t.error.title)}</span><button class="btn sm ghost" data-act="detail">${t.open ? '收起' : '详情'}</button>`;
else if (t.status === 'missing') st = '<span class="tag warn">文件缺失</span><span class="txt">记录还在,产物已被清理或移动</span>';
const actions = t.status === 'done'
? `<button class="btn sm ghost" data-act="reuse">复用</button><button class="btn sm ghost" data-act="download">下载</button><button class="btn sm ghost danger" data-act="delete">删除</button>`
: t.status === 'failed' ? '<button class="btn sm" data-act="retry">重试</button><button class="btn sm ghost danger" data-act="delete">删除</button>'
: t.status === 'missing' ? '<button class="btn sm" data-act="reuse">用相同参数重做</button><button class="btn sm ghost danger" data-act="delete">移除记录</button>' : '';
return `<div class="take ${sel ? 'selected' : ''} ${t.isNew ? 'new' : ''} ${t.open ? 'open' : ''}" role="option" aria-selected="${sel}" data-id="${t.id}" tabindex="-1">
<div class="take-head"><span class="name">${esc(w.name)}</span><span class="tag">${USAGE[w.usage]}</span><span class="meta">${esc(src)} · ${esc(t.time.slice(6))}</span></div>
<div class="take-prompt">${esc(t.prompt || '(使用工作流原提示词)')}</div>
${inputs ? `<div style="grid-column:1">${inputs}</div>` : ''}
<div class="take-state">${st}<div class="take-actions">${actions}</div></div>
<div class="take-out">${out}</div>
${t.status === 'failed' ? `<ul class="err-detail">${t.error.items.map((x) => `<li>${esc(x)}</li>`).join('')}<li class="muted">${esc(t.error.raw)} · 在「ComfyUI 连接」装好模型后点「重新检查」</li></ul>` : ''}
</div>`;
}
function renderFeed({ scrollToEnd } = {}) {
const list = visibleTakes();
let html = ''; let day = '';
for (const t of list) {
if (t.day !== day) { day = t.day; html += `<div class="feed-day">${day}</div>`; }
html += takeHTML(t);
}
if (!list.length) html = `<div class="note" style="margin-top:40px;text-align:center">${state.filter === 'failed' ? '没有失败或缺失的记录。' : '这里还没有记录。选好工作流、写下提示词,按 Ctrl + Enter 生成。'}</div>`;
const feed = $('#feed');
feed.innerHTML = html;
takes.forEach((t) => { t.isNew = false; });
const running = takes.filter((t) => t.status === 'queued' || t.status === 'running').length;
$('#feed-count').textContent = `${list.length} 条记录${running ? ` · ${running} 个进行中` : ''}`;
if (scrollToEnd) requestAnimationFrame(() => { feed.scrollTop = feed.scrollHeight; });
}
function patchTake(t, finished) {
const el = $(`.take[data-id="${t.id}"]`);
if (!el) return;
if (!finished && el.querySelector('.bar')) {
el.querySelector('.bar i').style.setProperty('--p', t.progress);
el.querySelector('.take-state .txt').textContent = `${t.phase} · ${Math.round(t.progress * 100)}%`;
el.querySelector('.take-state .tag').textContent = t.status === 'queued' ? '排队' : '生成中';
el.querySelector('.thumb.pending').textContent = t.phase;
return;
}
const tmp = document.createElement('div');
tmp.innerHTML = takeHTML(t);
t.justDone = false;
el.replaceWith(tmp.firstElementChild);
const running = takes.filter((x) => x.status === 'queued' || x.status === 'running').length;
$('#feed-count').textContent = `${visibleTakes().length} 条记录${running ? ` · ${running} 个进行中` : ''}`;
}
$('#feed').addEventListener('click', (e) => {
const el = e.target.closest('.take');
if (!el) return;
const t = takes.find((x) => x.id === +el.dataset.id);
const act = e.target.closest('[data-act]')?.dataset.act;
if (act === 'detail') { t.open = !t.open; patchTake(t, true); return; }
if (act === 'retry') { retry(t); return; }
if (act === 'delete') { removeTake(t); return; }
if (act === 'reuse') { reuse(t); return; }
if (act === 'download') { toast(`原型不连后端:正式版直接下载 ${t.out.image ? '图片' : 'MP4'} 原文件`); return; }
if (act === 'cancel') { takes.splice(takes.indexOf(t), 1); renderFeed(); updateTray(); toast('已取消该任务,ComfyUI 队列中的对应任务同步中断'); return; }
selectTake(t.id, { fromPointer: true });
});
function selectTake(id, { fromPointer, scroll } = {}) {
if (!takes.some((t) => t.id === id)) return;
if (state.view !== 'desk') nav('desk');
const prev = state.selected;
state.selected = id;
$$('.take').forEach((el) => { const on = +el.dataset.id === id; el.classList.toggle('selected', on); el.setAttribute('aria-selected', String(on)); });
const el = $(`.take[data-id="${id}"]`);
if (el && (scroll || !fromPointer)) el.scrollIntoView({ block: 'nearest', behavior: reduced() || !scroll ? 'auto' : 'smooth' });
if (prev !== id) renderPreview(!!fromPointer);
showPreviewTab();
if (innerWidth <= 1180 && fromPointer) openInspector();
}
function moveSelection(delta) {
const list = visibleTakes();
if (!list.length) return;
let i = list.findIndex((t) => t.id === state.selected);
i = i < 0 ? list.length - 1 : Math.max(0, Math.min(list.length - 1, i + delta));
selectTake(list[i].id, { fromPointer: false });
}
function removeTake(t) {
const el = $(`.take[data-id="${t.id}"]`);
const idx = takes.indexOf(t);
const w = wfById(t.wf);
const vis = visibleTakes();
const vi = vis.indexOf(t);
const neighbor = vis[vi + 1] || vis[vi - 1];
el?.classList.add('leaving');
setTimeout(() => {
takes.splice(takes.indexOf(t), 1);
if (state.selected === t.id) state.selected = neighbor ? neighbor.id : null;
renderFeed(); renderPreview(false); updateTray();
}, reduced() ? 0 : 200);
let undone = false;
toast(`已删除「${esc(w.name)}」这条记录${t.out && !t.out.name ? '及其结果文件' : ''}`, {
action: '撤销', duration: 5000,
onAction: () => { undone = true; takes.splice(Math.min(idx, takes.length), 0, t); t.isNew = true; state.selected = t.id; renderFeed(); renderPreview(false); updateTray(); },
onTimeout: () => { if (!undone) { /* 正式版:此时才调用 DELETE 接口 */ } },
});
}
function retry(t) {
const w = wfById(t.wf);
if (w.status === 'warn') {
toast('连接上仍缺 3 个模型文件,重试会再次被 ComfyUI 拒绝。先到「ComfyUI 连接」安装后点「重新检查」。', { action: '去连接页', onAction: () => nav('connections'), duration: 5200 });
return;
}
reuse(t); submit();
}
function reuse(t) {
const w = wfById(t.wf);
if (w.id !== state.wfId) selectWorkflow(w.id);
$('#prompt').value = t.prompt;
state.params = { ...t.params };
for (const s of w.slots) state.slots[s.key] = t.inputs.slice(0, s.type === 'list' ? s.max : 1).map((i) => ({ ...i }));
renderComposer(); renderParams();
$('#prompt').dispatchEvent(new Event('input'));
$('#prompt').focus();
toast('已把这条记录的工作流、素材与参数放回输入台,可改完再生成');
}
/* ---------------- 检视区 ---------------- */
function renderPreview(crossfade) {
const box = $('#insp-preview');
const t = takes.find((x) => x.id === state.selected);
if (!t) { box.innerHTML = '<div class="stage stage-empty"><div>选择左侧一条记录查看结果</div></div>'; return; }
const w = wfById(t.wf);
const portrait = t.out && t.out.h > t.out.w;
const oldStage = box.querySelector('.stage');
let media;
if (t.status === 'done') media = t.out.image ? `<img src="${t.out.src}" alt="">` : `<video src="${t.out.src}" poster="${t.out.poster}" controls playsinline preload="metadata"></video>`;
else if (t.status === 'missing') media = `<div class="stage-empty"><div>结果文件「${esc(t.out.name)}」已不在服务器上<br><span class="muted">可用相同参数重做,或移除这条记录</span></div></div>`;
else if (t.status === 'failed') media = `<div class="stage-empty"><div style="color:var(--err)">${esc(t.error.title)}</div></div>`;
else media = `<div class="stage-empty"><div>${esc(t.phase)} · ${Math.round(t.progress * 100)}%<br><span class="muted">完成后自动显示在这里</span></div></div>`;
const meta = [
t.out && t.status === 'done' ? `<span><b>${t.out.w}×${t.out.h}</b></span>` : '',
t.params.seed ? `<span>种子 <b class="mono">${esc(t.params.seed)}</b></span>` : '',
t.params.duration ? `<span>时长 <b>${esc(t.params.duration)} 秒</b></span>` : '',
t.elapsed ? `<span>用时 <b>${esc(t.elapsed)}</b></span>` : '',
`<span>${esc(t.conn || '本机 ComfyUI-4080')}</span>`,
t.demo && t.status === 'done' ? '<span class="tag warn">演示产物 · 取自测试站历史结果,非本次真实生成</span>' : '',
].join('');
const canSend = t.status === 'done' && t.out.image;
const actions = t.status === 'done'
? `<button class="btn sm" data-p="reuse">复用到输入台</button>${canSend ? '<button class="btn sm" data-p="send">送入当前图片槽</button>' : ''}<button class="btn sm" data-p="download">下载</button><button class="btn sm danger" data-p="delete">删除</button>`
: t.status === 'failed' ? '<button class="btn sm" data-p="retry">重试</button><button class="btn sm danger" data-p="delete">删除</button>'
: t.status === 'missing' ? '<button class="btn sm" data-p="reuse">用相同参数重做</button><button class="btn sm danger" data-p="delete">移除记录</button>' : '';
const html = `
<div class="stage ${portrait ? 'portrait' : ''}">${media}</div>
<div class="stage-meta">${meta}</div>
<div class="stage-actions">${actions}</div>
<div class="section-title">输入</div>
${t.inputs.length ? `<div class="slot-row" style="margin-bottom:10px">${t.inputs.map((i) => `<span class="tile" style="width:48px;height:48px;background-image:${i.bg}" title="${esc(i.name)}"></span>`).join('')}</div>` : ''}
<div class="note" style="white-space:pre-wrap">${esc(t.prompt || '(使用工作流原提示词)')}</div>
<div class="section-title">工作流</div>
<dl class="kv"><dt>名称</dt><dd>${esc(w.name)}</dd><dt>用途</dt><dd>${USAGE[w.usage]}</dd><dt>来源</dt><dd>${esc(t.source || (w.kind === 'video' ? '独立生视频' : '独立生图'))} · ${esc(t.time)}</dd>
${Object.entries(t.params).filter(([k]) => !['seed', 'duration'].includes(k)).map(([k, v]) => `<dt>${esc((w.params.find((p) => p.key === k) || { label: k }).label)}</dt><dd>${esc(v)}</dd>`).join('')}</dl>`;
const oldMedia = crossfade && oldStage && !reduced() ? Array.from(oldStage.children).map((c) => c.cloneNode(true)) : null;
box.innerHTML = html;
const newStage = box.querySelector('.stage');
// 点选切换:旧画面叠在上层 150ms 淡出,新画面已在下层就位;键盘切换不做动画
if (oldMedia && newStage.className === oldStage.className) {
const wrap = document.createElement('div');
wrap.style.cssText = `position:absolute;inset:0;z-index:3;pointer-events:none;background:#000;transition:opacity var(--d-state) ease`;
oldMedia.forEach((c) => { if (c.tagName === 'VIDEO') c.removeAttribute('controls'); wrap.appendChild(c); });
newStage.appendChild(wrap);
requestAnimationFrame(() => requestAnimationFrame(() => { wrap.style.opacity = '0'; }));
setTimeout(() => wrap.remove(), 200);
}
}
$('#insp-preview').addEventListener('click', (e) => {
const b = e.target.closest('[data-p]');
if (!b) return;
const t = takes.find((x) => x.id === state.selected);
const act = b.dataset.p;
if (act === 'reuse') reuse(t);
if (act === 'retry') retry(t);
if (act === 'delete') removeTake(t);
if (act === 'download') toast(`原型不连后端:正式版直接下载 ${t.out.image ? '图片' : 'MP4'} 原文件`);
if (act === 'send') {
const slot = curWf().slots[0];
if (!slot) { toast('当前工作流没有图片输入槽。切到图生视频或参考图生视频工作流后再送入。', { action: '选工作流', onAction: () => openWfPop(false) }); return; }
if (pushInput(slot.key, { bg: `url(${t.out.poster})`, name: `结果 #${t.id}` })) toast(`已送入「${slot.label}」`);
}
if (innerWidth <= 1180 && ['reuse', 'send', 'retry'].includes(act)) closeInspector();
});
function showPreviewTab() {
$$('.insp-tabs [data-tab]').forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.tab === 'preview')));
$('#insp-preview').hidden = false; $('#insp-params').hidden = true;
$('#insp-hint').textContent = '↑ ↓ 切换 · 空格播放';
}
function showParamsTab() {
$$('.insp-tabs [data-tab]').forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.tab === 'params')));
$('#insp-preview').hidden = true; $('#insp-params').hidden = false;
$('#insp-hint').textContent = '按工作流 JSON 生成';
if (innerWidth <= 1180) openInspector();
}
$('.insp-tabs').addEventListener('click', (e) => {
const b = e.target.closest('[data-tab]');
if (b) (b.dataset.tab === 'preview' ? showPreviewTab : showParamsTab)();
});
$('#params-chip').addEventListener('click', showParamsTab);
function openInspector() { if (innerWidth <= 1180 && !$('#inspector').classList.contains('on')) { $('#inspector').classList.add('on'); layers.push({ el: $('#inspector'), onClose: () => $('#inspector').classList.remove('on') }); } }
function closeInspector() { closeLayer($('#inspector'), true); $('#inspector').classList.remove('on'); }
$('#insp-close').addEventListener('click', closeInspector);
function renderParams() {
const w = curWf();
const conn = w.conn ? connById(w.conn).name : `跟随默认连接(本次用 ${connById(state.connId).name})`;
const field = (p) => {
const v = paramValue(p);
const changed = state.params[p.key] !== undefined && v !== p.orig;
let input;
if (p.kind === 'select') input = `<select class="input ${changed ? 'changed' : ''}" data-f="${p.key}">${p.options.map((o) => `<option ${o === v ? 'selected' : ''}>${esc(o)}</option>`).join('')}</select>`;
else if (p.kind === 'textarea') input = `<textarea class="input ${changed ? 'changed' : ''}" data-f="${p.key}" placeholder="留空沿用工作流原值">${esc(v)}</textarea>`;
else input = `<input class="input mono ${changed ? 'changed' : ''}" data-f="${p.key}" value="${esc(v)}" inputmode="decimal">`;
return `<div class="field"><label><span>${esc(p.label)}</span><span class="orig">原值 ${esc(p.orig || '空')}</span></label>${input}</div>`;
};
const common = w.params.filter((p) => p.common);
const adv = w.params.filter((p) => !p.common);
$('#insp-params').innerHTML = `
<div style="display:flex;gap:8px;align-items:center;margin-bottom:10px"><b style="font-size:14px">${esc(w.name)}</b></div>
<div style="display:flex;gap:6px;flex-wrap:wrap;margin-bottom:12px"><span class="tag">${USAGE[w.usage]}</span><span class="tag">${esc(slotSummary(w))}</span><span class="tag">${esc(conn)}</span></div>
${w.errors ? `<div class="note err"><b>该工作流文件不完整,ComfyUI 无法执行,已禁止生成</b><ul>${w.errors.map((x) => `<li>${esc(x)}</li>`).join('')}</ul><div style="margin-top:8px;color:var(--text-2)">请在已安装对应自定义节点的 ComfyUI 中重新导出 API 格式 JSON,再替换导入。</div><button class="btn sm" style="margin-top:8px" data-reimport>重新导入替换</button></div>` : ''}
${w.note ? `<div class="note">${esc(w.note)}</div>` : ''}
${w.status === 'warn' ? '<div class="note warn">上次运行时连接上缺 3 个模型文件;装好后在「ComfyUI 连接」点「重新检查」。</div>' : ''}
${w.params.length ? '' : '<div class="note">此工作流只暴露提示词,没有其他可调参数。</div>'}
${common.map(field).join('')}
${adv.length ? `<details class="fold"><summary>${icon('right')}高级参数 ${adv.length} 项 · 不改就沿用工作流原值</summary>${adv.map(field).join('')}</details>` : ''}
${changedCount() ? '<button class="btn sm ghost" data-reset>全部恢复工作流原值</button>' : ''}`;
}
$('#insp-params').addEventListener('input', (e) => {
const f = e.target.closest('[data-f]');
if (!f) return;
state.params[f.dataset.f] = f.value;
f.classList.toggle('changed', f.value !== curWf().params.find((p) => p.key === f.dataset.f).orig);
renderCommonChips();
});
$('#insp-params').addEventListener('change', () => renderParams());
$('#insp-params').addEventListener('click', (e) => {
if (e.target.closest('[data-reset]')) { state.params = {}; renderParams(); renderCommonChips(); }
if (e.target.closest('[data-reimport]')) openImport('B');
});
/* ---------------- 筛选 / 范围 ---------------- */
function setFilter(f) {
state.filter = f;
$$('.filters [data-filter]').forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.filter === f)));
renderFeed({ scrollToEnd: true });
}
$('.filters').addEventListener('click', (e) => { const b = e.target.closest('[data-filter]'); if (b) setFilter(b.dataset.filter); });
const SCOPES = [['all', '全部来源'], ['standalone', '独立创作'], ['p1', '雨夜便利店']];
$('#scope-btn').addEventListener('click', () => {
$('#menu-list').innerHTML = SCOPES.map(([k, l]) => `<button data-scope="${k}" aria-selected="${k === state.scope}">${l}${k === 'p1' ? ' <span class="muted">· 项目</span>' : ''}</button>`).join('');
openLayer($('#menu-pop'), { anchor: $('#scope-btn'), origin: 'top left', trigger: $('#scope-btn') });
$('#menu-list').onclick = (e) => {
const b = e.target.closest('[data-scope]');
if (!b) return;
setScope(b.dataset.scope);
closeLayer($('#menu-pop'));
};
});
function setScope(s) {
state.scope = s;
$('#scope-label').textContent = SCOPES.find(([k]) => k === s)[1];
renderFeed({ scrollToEnd: true });
}
/* ---------------- 任务托盘 ---------------- */
function updateTray() {
const running = takes.filter((t) => t.status === 'queued' || t.status === 'running');
$('#tray-dot').className = 'dot' + (running.length ? ' run' : '');
$('#tray-label').textContent = running.length ? `${running.length} 个生成中` : '队列空闲';
if ($('#tray-pop').classList.contains('on')) renderTray();
}
function renderTray() {
const list = [...takes].reverse().slice(0, 6);
$('#tray-list').innerHTML = `<div class="pop-group">最近任务 · 点一下跳到对应记录</div>` + list.map((t) => {
const w = wfById(t.wf);
const st = t.status === 'done' ? '<span class="tag accent">完成</span>' : t.status === 'failed' ? '<span class="tag err">失败</span>' : t.status === 'missing' ? '<span class="tag warn">缺文件</span>' : `<span class="tag run">${Math.round(t.progress * 100)}%</span>`;
return `<button class="tray-row" data-go="${t.id}"><span class="t" style="${t.out?.poster ? `background-image:url(${t.out.poster})` : ''}"></span><span><div class="n">${esc(w.name)}</div><div class="m">${esc(t.source || (w.kind === 'video' ? '独立生视频' : '独立生图'))} · ${t.time.slice(6)}</div></span>${st}</button>`;
}).join('');
}
$('#tray-btn').addEventListener('click', () => {
if ($('#tray-pop').classList.contains('on')) { closeLayer($('#tray-pop')); return; }
renderTray();
openLayer($('#tray-pop'), { anchor: $('#tray-btn'), origin: 'top right', trigger: $('#tray-btn') });
});
$('#tray-list').addEventListener('click', (e) => {
const b = e.target.closest('[data-go]');
if (!b) return;
closeLayer($('#tray-pop'), true);
const t = takes.find((x) => x.id === +b.dataset.go);
if (!visibleTakes().includes(t)) { setFilter('all'); setScope('all'); }
selectTake(t.id, { scroll: true });
});
$('#conn-btn').addEventListener('click', () => nav('connections'));
/* ---------------- 导入工作流抽屉 ---------------- */
const SAMPLE_A = {
'1': { inputs: { value: 'Describe the motion from the first frame.' }, class_type: 'PrimitiveStringMultiline', _meta: { title: '正向提示词' } },
'115': { inputs: { aspect_ratio: '16:9 (Widescreen)', megapixels: 0.7, multiple: 32 }, class_type: 'ResolutionSelector', _meta: { title: '分辨率' } },
'124': { inputs: { steps: 4, denoise: 1, cfg: 1 }, class_type: 'KSampler', _meta: { title: 'K采样器' } },
'129': { inputs: { noise_seed: 42 }, class_type: 'RandomNoise', _meta: { title: '随机种子' } },
'133': { inputs: { value: 10 }, class_type: 'PrimitiveInt', _meta: { title: '时长(秒)' } },
'901': { inputs: { image: 'first_frame.png' }, class_type: 'LoadImage', _meta: { title: '首帧 First Frame' } },
'92': { inputs: { filename_prefix: 'h3_i2v', format: 'mp4' }, class_type: 'SaveVideo', _meta: { title: '保存视频' } },
};
const SAMPLE_B = {
'1': { inputs: { UNKNOWN: 'qwen-image-2.1-Q4_K_M.gguf' }, _meta: { title: 'Unet Loader (GGUF)' } },
'2': { inputs: { clip_name: 'qwen3vl_8b_int8_convrot.safetensors', type: 'qwen_image' }, class_type: 'CLIPLoader', _meta: { title: '加载CLIP' } },
'4': { inputs: { prompt: '参考角色五官,重新生成图片:高细节皮肤质感' }, class_type: 'TextEncodeQwenImageEdit', _meta: { title: '文本编码' } },
'5': { inputs: { image: 'input.png' }, class_type: 'LoadImage', _meta: { title: '输入图' } },
'6': { inputs: { seed: 278835418249884, steps: 25, cfg: 1, denoise: 1 }, class_type: 'KSampler', _meta: { title: 'K采样器' } },
'8': { inputs: { filename_prefix: 'qwen_edit' }, class_type: 'SaveImage', _meta: { title: '保存图像' } },
'9': { inputs: { sage_attention: 'auto' }, _meta: { title: 'Patch Sage Attention KJ' } },
};
const imp = { name: '', conn: 'local', text: '', result: null, usage: null, test: 'none', trigger: null };
function openImport(sample) {
imp.name = ''; imp.text = ''; imp.result = null; imp.usage = null; imp.test = 'none';
imp.trigger = document.activeElement;
renderImport();
$('#scrim').classList.add('on');
$('#drawer').classList.add('on');
layers.push({ el: $('#drawer'), onClose: closeImportVisual, trigger: imp.trigger });
if (sample) loadSample(sample);
setTimeout(() => $('#imp-name')?.focus(), 30);
}
function closeImportVisual() { $('#scrim').classList.remove('on'); $('#drawer').classList.remove('on'); }
$('#drawer-close').addEventListener('click', () => closeLayer($('#drawer')));
$('#scrim').addEventListener('click', () => closeLayer($('#drawer')));
function loadSample(k) {
imp.text = JSON.stringify(k === 'A' ? SAMPLE_A : SAMPLE_B, null, 2);
imp.name = k === 'A' ? 'H3 图生视频·首帧(重新导出)' : 'Qwen Image 2.1 图片编辑(重新导出)';
renderImport();
analyze();
}
function renderImport() {
const r = imp.result;
$('#drawer-body').innerHTML = `
<div class="field"><label for="imp-name"><span>名称</span></label><input class="input" id="imp-name" value="${esc(imp.name)}" placeholder="例如:H3 图生视频·首帧(本机)"></div>
<div class="field"><label><span>绑定连接</span><span class="orig">试运行与生成都走这台 ComfyUI</span></label>
<select class="input" id="imp-conn">${CONNS.map((c) => `<option value="${c.id}" ${c.id === imp.conn ? 'selected' : ''}>${esc(c.name)}${c.ok ? ` · ${c.ms} ms` : ' · 连接失败'}</option>`).join('')}</select></div>
<div class="drop" id="imp-drop">
<div style="display:flex;justify-content:space-between;align-items:center;gap:8px;flex-wrap:wrap">
<span style="font-size:12px;color:var(--text-2)">把 ComfyUI「导出 (API)」得到的 JSON 拖到这里、粘贴,或选择文件</span>
<button class="btn sm" id="imp-file">${icon('upload')}选择文件</button>
</div>
<textarea id="imp-text" spellcheck="false" placeholder='{"1": {"class_type": "LoadImage", "inputs": {...}}, ...}'>${esc(imp.text)}</textarea>
<div style="display:flex;gap:6px;flex-wrap:wrap;align-items:center">
<span class="muted" style="font-size:11px">没有文件?试试:</span>
<button class="btn sm ghost" data-sample="A">示例 A · 完整的 H3 图生视频</button>
<button class="btn sm ghost" data-sample="B">示例 B · 缺自定义节点的 Qwen 图片编辑</button>
</div>
</div>
<div class="checks" id="imp-checks">${r ? checksHTML(r) : ''}</div>`;
const canSave = r && r.ok && imp.usage;
$('#drawer-foot').innerHTML = `
<span class="muted" style="margin-right:auto;font-size:11px;align-self:center">原型内判定为前端简化版;正式版沿用后端 /api/workflows/analyze</span>
${r && !r.ok ? '<button class="btn" data-imp="save-bad">仍然保存(标记为不可用)</button>' : ''}
<button class="btn primary" data-imp="save" ${canSave ? '' : 'disabled'}>保存并使用</button>`;
}
function checksHTML(r) {
const c = (cls, ic, t, d) => `<div class="check ${cls}"><span class="ic">${ic}</span><span class="t">${t}</span><div class="d">${d}</div></div>`;
let html = '';
html += r.errors.length
? c('bad', '!', `第 1 步 · 文件结构:发现 ${r.errors.length} 个问题`, `<ul>${r.errors.map((x) => `<li>${esc(x)}</li>`).join('')}</ul>请在已安装对应自定义节点的 ComfyUI 中重新导出 API 格式 JSON。`)
: c('ok', '✓', `第 1 步 · 文件结构正常`, `${r.nodeCount} 个节点 · API 格式`);
if (r.errors.length) return html + c('', '–', '第 2 步 · 用途与输入槽', '文件结构有问题,暂不判定') + c('', '–', '第 3 步 · 对照连接上的节点与模型', '跳过');
const lowConf = r.confidence === 'low';
html += c(lowConf ? 'run' : 'ok', lowConf ? '?' : '✓', lowConf ? '第 2 步 · 用途不确定,请确认' : `第 2 步 · 判定为「${USAGE[r.usage]}」`,
`${lowConf ? '检测到视频输出和图片输入,但无法确定图片是首帧还是参考图:' : '可手动更正:'}
<div class="usage-pick">${USAGE_ORDER.map((u) => `<button data-usage="${u}" aria-pressed="${imp.usage === u}">${USAGE[u]}</button>`).join('')}</div>
<div class="slot-map">${r.slotsView.map((s) => `<div><span>${esc(s.label)}</span><span class="mono muted">${esc(s.node)}</span></div>`).join('')}
${r.outputs.map((o) => `<div><span>输出 · ${o.kind === 'video' ? '视频' : '图片'}</span><span class="mono muted">${esc(o.node)}</span></div>`).join('')}</div>`);
const conn = connById(imp.conn);
if (!conn.ok) html += c('bad', '!', '第 3 步 · 连不上所选连接', `${esc(conn.name)}:${esc(conn.err)}。可以先保存,连接恢复后再「重新检查」。`);
else if (r.sample === 'A') html += c('ok', '✓', '第 3 步 · 连接上的节点与模型齐全', `${esc(conn.name)} · 自定义节点 7/7 已安装 · 模型文件已找到`);
else html += c('', 'i', '第 3 步 · 对照连接上的节点与模型', '原型未连接后端,正式版会查询该 ComfyUI 的 /object_info 并用中文列出缺失项');
const testCls = imp.test === 'running' ? 'run' : imp.test === 'ok' ? 'ok' : '';
const testTxt = imp.test === 'running' ? '试运行中 · 采样 2/4…' : imp.test === 'ok' ? '试运行通过 · 产出 1 个视频,可下载且类型正确' : '可选:真实提交一次,只有拿到可下载的正确类型产物才算通过';
html += c(testCls, imp.test === 'ok' ? '✓' : '4', '第 4 步 · 试运行(可选)', `${testTxt}${imp.test === 'none' && conn.ok ? '<div style="margin-top:6px"><button class="btn sm" data-imp="test">试运行一次</button></div>' : ''}`);
return html;
}
function analyze() {
const text = imp.text.trim();
if (!text) { imp.result = null; renderImport(); return; }
let json;
try { json = JSON.parse(text); } catch (e) {
imp.result = { ok: false, errors: [`不是合法的 JSON:${e.message}`] }; renderImport(); return;
}
if (Array.isArray(json.nodes) && json.links) {
imp.result = { ok: false, errors: ['这是 ComfyUI 界面格式(含 nodes / links),不是 API 格式。请在 ComfyUI 菜单里用「导出 (API)」重新导出。'] }; renderImport(); return;
}
const entries = Object.entries(json).filter(([, v]) => v && typeof v === 'object');
const errors = [];
for (const [id, n] of entries) if (!n.class_type) errors.push(`节点 ${id}「${n._meta?.title || '未命名'}」缺少节点类型(class_type),导出时 ComfyUI 未加载该自定义节点`);
const outputs = []; const images = []; let prompt = null; const params = [];
for (const [id, n] of entries) {
const ct = n.class_type || ''; const title = n._meta?.title || ct;
if (/SaveVideo|VHS_VideoCombine|SaveWEBM|SaveAnimated|CreateVideo/i.test(ct)) outputs.push({ kind: 'video', node: `${id} · ${ct}` });
else if (/SaveImage|PreviewImage/i.test(ct)) outputs.push({ kind: 'image', node: `${id} · ${ct}` });
if (/^LoadImage/i.test(ct)) images.push({ id, title, role: /ref|参考/i.test(title) ? 'ref' : /first|start|首帧/i.test(title) ? 'first' : 'image' });
if (!prompt && (/PrimitiveString|CLIPTextEncode|TextEncode/i.test(ct) || typeof n.inputs?.prompt === 'string')) prompt = { id, title };
for (const k of Object.keys(n.inputs || {})) if (/^(seed|noise_seed|steps|cfg|denoise|aspect_ratio|megapixels|width|height|length|duration)$/.test(k)) params.push(k);
}
const hasVideo = outputs.some((o) => o.kind === 'video');
if (!outputs.length && !errors.length) errors.push('没有找到输出节点(SaveImage / SaveVideo 等)。若使用了自定义输出节点,保存后需要手动指定输出。');
let usage; let confidence = 'high';
if (hasVideo) {
if (images.some((i) => i.role === 'ref')) usage = 'ref2video';
else if (images.some((i) => i.role === 'first')) usage = 'image2video';
else if (images.length) { usage = 'image2video'; confidence = 'low'; }
else usage = 'text2video';
} else usage = images.length ? 'image2image' : 'text2image';
const slotsView = [];
if (prompt) slotsView.push({ label: '提示词', node: `${prompt.id} · ${prompt.title}` });
for (const i of images) slotsView.push({ label: i.role === 'ref' ? '参考图' : i.role === 'first' ? '首帧图' : '输入图', node: `${i.id} · ${i.title}` });
if (params.length) slotsView.push({ label: `参数 ${new Set(params).size} 项`, node: [...new Set(params)].join(' / ') });
imp.result = { ok: !errors.length, errors, nodeCount: entries.length, outputs, images, usage, confidence, slotsView, sample: text === JSON.stringify(SAMPLE_A, null, 2) ? 'A' : null };
imp.usage = confidence === 'low' ? null : usage;
renderImportProgressively();
}
function renderImportProgressively() {
renderImport();
if (reduced()) return;
const items = $$('#imp-checks .check');
items.forEach((el, i) => { el.style.opacity = '0'; el.style.transform = 'translateY(4px)'; el.style.transition = `opacity 200ms var(--ease-out) ${i * 60}ms, transform 200ms var(--ease-out) ${i * 60}ms`; });
requestAnimationFrame(() => requestAnimationFrame(() => items.forEach((el) => { el.style.opacity = ''; el.style.transform = ''; })));
}
$('#drawer').addEventListener('input', (e) => {
if (e.target.id === 'imp-name') imp.name = e.target.value;
if (e.target.id === 'imp-text') { imp.text = e.target.value; clearTimeout(imp._t); imp._t = setTimeout(() => { const pos = e.target.selectionStart; analyze(); const ta = $('#imp-text'); ta.focus(); ta.setSelectionRange(pos, pos); }, 500); }
});
$('#drawer').addEventListener('change', (e) => { if (e.target.id === 'imp-conn') { imp.conn = e.target.value; imp.test = 'none'; renderImport(); } });
$('#drawer').addEventListener('click', (e) => {
const s = e.target.closest('[data-sample]');
if (s) loadSample(s.dataset.sample);
if (e.target.closest('#imp-file')) $('#json-input').click();
const u = e.target.closest('[data-usage]');
if (u) { imp.usage = u.dataset.usage; renderImport(); }
const a = e.target.closest('[data-imp]')?.dataset.imp;
if (a === 'test') {
imp.test = 'running'; renderImport();
setTimeout(() => { imp.test = 'ok'; renderImport(); }, 1800);
}
if (a === 'save' || a === 'save-bad') saveImport(a === 'save-bad');
});
$('#drawer').addEventListener('dragover', (e) => { if (e.target.closest('#imp-drop')) { e.preventDefault(); $('#imp-drop').classList.add('drag'); } });
$('#drawer').addEventListener('dragleave', (e) => { if (!e.relatedTarget || !$('#imp-drop').contains(e.relatedTarget)) $('#imp-drop')?.classList.remove('drag'); });
$('#drawer').addEventListener('drop', (e) => {
if (!e.target.closest('#imp-drop')) return;
e.preventDefault();
const f = e.dataTransfer.files[0];
if (f) readJsonFile(f);
});
$('#json-input').addEventListener('change', (e) => { if (e.target.files[0]) readJsonFile(e.target.files[0]); e.target.value = ''; });
function readJsonFile(f) {
f.text().then((t) => { imp.text = t; if (!imp.name) imp.name = f.name.replace(/\.json$/i, ''); renderImport(); analyze(); });
}
function saveImport(bad) {
const r = imp.result;
const name = imp.name.trim() || '未命名工作流';
const usage = imp.usage || r.usage || 'text2image';
const kind = usage.includes('video') ? 'video' : 'image';
const slots = [];
if (usage === 'ref2video') slots.push({ key: 'ref', label: '参考图', type: 'list', min: 1, max: 9 });
if (usage === 'image2video') slots.push({ key: 'first', label: '首帧图', type: 'single' });
if (usage === 'image2image') slots.push({ key: 'image', label: '输入图', type: 'single' });
const w = {
id: ++seq, name, usage, kind, conn: imp.conn, status: bad ? 'error' : imp.test === 'ok' ? 'ok' : 'idle',
statusText: bad ? '不可用 · 文件不完整' : imp.test === 'ok' ? '可用 · 刚刚试运行通过' : '未试运行',
slots, params: kind === 'video' ? H3_PARAMS : QWEN_T2I.slice(0, 2).concat(QWEN_T2I.slice(5)), errors: bad ? r.errors : null,
note: usage === 'ref2video' ? 'MiniMax H3 Ref2VA 官方限额:参考图最多 9 张。' : null,
};
workflows.push(w);
closeLayer($('#drawer'), true);
closeImportVisual();
selectWorkflow(w.id);
toast(bad ? `已保存「${esc(name)}」,标记为不可用,生成按钮保持禁用` : `已导入并选中「${esc(name)}」· 输入台已按 JSON 显示:${esc(slotSummary(w))}`, { duration: 4200 });
}
/* ---------------- 页面切换 ---------------- */
const TITLES = { desk: '生成台', projects: '项目', flow: '雨夜便利店 · 创作流程', tasks: '生成台', agents: '智能体', connections: 'ComfyUI 连接', settings: '模型与设置', more: '更多' };
function nav(v) {
if (v === 'tasks') { v = 'desk'; setScope('all'); toast('任务页并入生成台:「全部来源」即全部任务,右上角托盘随时看进度', { duration: 2800 }); }
state.view = v;
$$('.view').forEach((el) => el.classList.remove('on'));
const id = { desk: 'view-desk', projects: 'view-projects', flow: 'view-flow' }[v] || 'view-other';
$('#' + id).classList.add('on');
$$('[data-nav]').forEach((b) => b.toggleAttribute('aria-current', false));
$$(`[data-nav="${v}"]`).forEach((b) => b.setAttribute('aria-current', 'page'));
$('#page-title').textContent = TITLES[v] || '';
$('#scope-btn').style.display = v === 'desk' ? '' : 'none';
if (v === 'projects') renderProjects();
if (v === 'flow') renderFlow();
if (id === 'view-other') renderOther(v);
if (v === 'desk') renderFeed({ scrollToEnd: false });
}
$$('[data-nav]').forEach((b) => b.addEventListener('click', () => nav(b.dataset.nav)));
const STAGES = [['剧本创作', 'done'], ['视觉设计', 'done'], ['分镜设计', 'done'], ['素材资产', 'done'], ['镜头脚本', 'cur']];
const trackHTML = (cur) => `<div class="track">${STAGES.map(([n, s], i) => `<button class="${s}" ${i === cur ? 'aria-current="step"' : ''} data-stage="${i}"><span class="k">${s === 'done' ? '已确认' : '待确认'}</span>${i + 1}. ${n}</button>`).join('')}</div>`;
function renderProjects() {
$('#view-projects').innerHTML = `
<div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap"><h2 style="margin:0;font-size:18px">继续上次</h2><div class="grow" style="flex:1"></div>
<button class="btn" data-todo>导入剧本</button><button class="btn primary" data-todo>${icon('plus')}从创意开始</button></div>
<div class="hero">
<div class="cover" style="background:linear-gradient(160deg,#1c2a3a,#0e1116 60%),#111;display:grid;place-items:center;color:var(--text-3);font-size:12px">暂无生成画面 · 场景 0 · 素材 0</div>
<div><span class="tag warn">镜头脚本 · 待确认</span><h2>雨夜便利店</h2>
<p>时长约 3 分钟(180 秒)· 现代深夜都市 · 24 小时便利店(内)、店外雨夜。刚下班的白领与浑身湿透的男人在暴雨夜的便利店相遇。</p>
${trackHTML(4)}
<div class="row-actions"><button class="btn primary" data-go-flow>继续:确认镜头脚本</button><button class="btn" data-go-desk>查看本项目生成记录</button></div>
</div>
</div>
<h2 style="margin:6px 0 0;font-size:14px;color:var(--text-2)">全部项目 · 2</h2>
<div class="proj-list">
<button class="proj" data-go-flow><b>雨夜便利店</b><span class="muted" style="font-size:12px">镜头脚本 · 待确认 · 1 天前</span><span class="pips"><i class="d"></i><i class="d"></i><i class="d"></i><i class="d"></i><i class="c"></i></span></button>
<button class="proj" data-todo><b>随便</b><span class="muted" style="font-size:12px">分镜设计 · 待确认 · 1 天前</span><span class="pips"><i class="d"></i><i class="d"></i><i class="c"></i><i></i><i></i></span></button>
</div>`;
}
$('#view-projects').addEventListener('click', (e) => {
if (e.target.closest('[data-go-flow]')) nav('flow');
else if (e.target.closest('[data-go-desk]')) { nav('desk'); setScope('p1'); }
else if (e.target.closest('[data-stage]')) nav('flow');
else if (e.target.closest('[data-todo]')) toast('本原型只演示高频生成链路;该入口沿用现有功能');
});
const SHOTS = [
['S1', '4s', '第一场店外暴雨,固定远景,暴雨如帘砸在便利店玻璃门,霓虹在积水里碎成冷蓝光,店内暖黄光从门缝透出。音效:暴雨声。', 'Cinematic extreme wide static shot. Outside the modern 24-hour convenience store at night, heavy rain falls like a curtain against the glass doors, neon signs smear into cold blue puddles, warm yellow interior light glows through the door seam…'],
['S2', '4s', '女人推开玻璃门,湿透的黑大衣滴水,头发贴在脸上。店外冷雨与店内暖光在她身上交界。音效:门铃叮。', 'Cinematic full tracking shot. The 28-year-old woman with black long straight hair plastered to her face, soaked black coat dripping, pushes open the glass door into warm yellow interior light…'],
['S3', '5s', '男人站在饮料柜前没动,隔着货架看她。冷柜白光打在侧脸,雨声压低。', 'Medium close-up, static. A 32-year-old man in a soaked grey hoodie stands still by the drinks fridge, cold white fridge light on his profile, rain muffled…'],
];
function renderFlow() {
$('#view-flow').innerHTML = `
${trackHTML(4)}
<div class="note warn" style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin:0">当前是未确认草稿:确认后才会交给下一阶段的智能体使用。<span style="flex:1"></span><button class="btn sm" data-todo>和「镜头脚本」智能体单聊</button><button class="btn sm primary" data-todo>确认本阶段</button></div>
${SHOTS.map(([no, d, zh, en]) => `<div class="shot"><span class="no">${no}<br><span class="muted" style="font-weight:400;font-size:11px">${d}</span></span><div><div class="p">${zh}</div><div class="en">${en}</div></div><button class="btn sm" data-shot="${no}">生成本镜视频</button></div>`).join('')}`;
}
$('#view-flow').addEventListener('click', (e) => {
const s = e.target.closest('[data-shot]');
if (s) {
const shot = SHOTS.find((x) => x[0] === s.dataset.shot);
state.context = shot[0];
$('#context-bar').classList.add('on');
$('#context-bar b').textContent = `《雨夜便利店》· 镜头 ${shot[0]}`;
nav('desk');
setScope('p1');
selectWorkflow(6);
$('#prompt').value = shot[3];
$('#prompt').dispatchEvent(new Event('input'));
state.params.duration = shot[1].replace('s', '') === '4' ? '5' : shot[1].replace('s', '');
renderCommonChips(); renderParams();
$('#prompt').focus();
return;
}
if (e.target.closest('[data-stage]')) toast('阶段切换沿用现有五段工作台,本原型不展开');
if (e.target.closest('[data-todo]')) toast('本原型只演示高频生成链路;该操作沿用现有功能');
});
$('#ctx-back').addEventListener('click', () => { state.context = null; $('#context-bar').classList.remove('on'); nav('flow'); });
function renderOther(v) {
const desc = {
agents: '五个智能体改为左列表 + 右侧对话;对话里生成的提示词可一键「送到生成台」,直接落到输入台,不再复制粘贴。',
connections: '连接卡与工作流库沿用本原型的状态标签与抽屉:导入就是左侧演示的那个抽屉,四步检查逐条出现;失败项给中文原因与下一步。',
settings: '模型设置与系统设置合并成一个带分组导航的设置页;密钥掩码不回显,连通性测试结果用同一套状态标签。',
more: '窄屏「更多」收纳:全部任务、智能体、ComfyUI 连接、模型与设置。',
}[v] || '';
$('#view-other').innerHTML = `<div><h2>${TITLES[v]}</h2><p style="max-width:520px;margin:8px auto 16px">${desc}</p><p class="muted">本原型聚焦「选择/导入工作流 → 按 JSON 填输入 → 提交 → 切换结果」这条高频链路,该页不做可点演示。</p><button class="btn" data-nav-desk>回到生成台</button></div>`;
$('#view-other [data-nav-desk]').onclick = () => nav('desk');
}
/* ---------------- 键盘 ---------------- */
const inField = (el) => el && (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.tagName === 'SELECT' || el.isContentEditable);
document.addEventListener('keydown', (e) => {
const mod = e.metaKey || e.ctrlKey;
if (mod && e.key.toLowerCase() === 'k') { e.preventDefault(); if ($('#wf-pop').classList.contains('on')) closeLayer($('#wf-pop')); else openWfPop(true); return; }
if (e.key === 'Escape') { if (closeTop()) { e.preventDefault(); return; } if (composer.classList.contains('expanded')) composer.classList.remove('expanded'); return; }
if (mod && e.key === 'Enter' && state.view === 'desk') { e.preventDefault(); submit(); return; }
if (inField(e.target) || state.view !== 'desk' || layers.some((l) => l.el.id !== 'inspector')) return;
if (e.key === '/') { e.preventDefault(); $('#prompt').focus(); }
else if (e.key === 'ArrowDown' || e.key === 'j') { e.preventDefault(); moveSelection(1); }
else if (e.key === 'ArrowUp' || e.key === 'k') { e.preventDefault(); moveSelection(-1); }
else if (e.key === ' ') {
const v = $('#insp-preview video');
if (v && !e.target.closest('button')) { e.preventDefault(); v.paused ? v.play() : v.pause(); }
} else if ((e.key === 'Delete' || e.key === 'Backspace') && state.selected) {
const t = takes.find((x) => x.id === state.selected);
if (t && t.status !== 'queued' && t.status !== 'running') removeTake(t);
}
});
$('#cmd-btn').addEventListener('click', () => openWfPop(true));
/* ---------------- 减少动态 ---------------- */
$('#reduce-toggle').checked = reduceQuery.matches;
if (reduceQuery.matches) root.dataset.reduce = '1';
$('#reduce-toggle').addEventListener('change', (e) => { root.dataset.reduce = e.target.checked ? '1' : '0'; });
/* ---------------- 启动 ---------------- */
const params = new URLSearchParams(location.search);
if (params.get('reduce') === '1') { root.dataset.reduce = '1'; $('#reduce-toggle').checked = true; }
renderComposer();
renderParams();
renderFeed({ scrollToEnd: true });
renderPreview(false);
updateTray();
if (params.get('view')) nav(params.get('view'));
})();