Verify (Gitea) / gate (build · unit · facts) (push) Failing after 33s
组合节点的拼接逻辑不变。断点在「来源判定」:batchSrcText/isBatchSrc 只看节点自身 data.text,而提示词/文本节点在「继承 · 来自 上一级」时 data.text 为空 —— 组合读不到 这一路、nodeRefsOf(combine) 也把它过滤掉(组合→文本/分层节点的参考图随之丢失); 出图侧 resolveNodeTaskValues 走 own||上游,一直是通的,所以出现「能出图、组合是空的」。 - canvas-text: batchSrcText/isBatchSrc 增加可选 (edges, nodes);自身无文案时按 inheritedTextOf 同一套排序取上游第一条(提示词不拼合多路,与节点体显示一致), 只穿透 prompt/textout/relay/batch,组合/LLM/插件节点不越过;不传参保持旧行为 - 组合/连接/端口定位/画布渲染等调用点补传 edges/nodes - 测试:canvas-text 补继承态断言(多路取第一条/接管/停用/环)、plugin-style-node 补组合端到端、iwb-inherit-text 补 DOM 用例(组合行出现并跟随上游)
1173 lines
74 KiB
JavaScript
1173 lines
74 KiB
JavaScript
|
||
// 确认统一走页内确认(桌面端),网页端保持原生 confirm
|
||
function askConfirm (text, opts) {
|
||
const C = (typeof window !== 'undefined') ? window.IWBUIConfirm : null
|
||
if (C && typeof C.askOrNative === 'function') return C.askOrNative(text, opts)
|
||
return Promise.resolve(window.confirm(String(text)))
|
||
}
|
||
;(function (global) {
|
||
'use strict'
|
||
|
||
// 节点体渲染(从 app.js 的 renderBodyInner 按类型分派里逐块搬出;2026-10-29)
|
||
//
|
||
// 约定:
|
||
// · 每个 render*Body(node, props, ctx) 的**函数体与 app.js 原文逐字相同**(只去掉 if 外壳、改缩进),
|
||
// 等价性由 scripts/verify-bodies-move.js 机械校验(level-2:忽略字符串外的所有空白)。
|
||
// · app.js 的模块级联动用 inject() 注入(本文件不直接引用 app.js 的符号)。
|
||
// · ctx = { onUpdate, busy, progress, h, stop, refMini },由调用方 renderBodyInner 组装。
|
||
|
||
// ── 注入依赖(app.js 在首次渲染时调用 inject 注入)─────────────────────────
|
||
let I, LocalTextField, autoGrow, React, ReactDOM, combineSourcePairs, downloadUrl, wResolveOutSrc, isImageProducer, nodePreviewRefsV2, nodeInheritOf, orderedUniqueRefNodes, outProgUI, outThumbCache, uploadRefToImageHost, wDisplayThumbOf, wImgSrcForNode, wImportImage, wPreviewUrlOf, wRawCfg, wResolveImg, wThumbSrc, el, wPluginNodeVariants, wPluginVariantMeta, isBatchSrc, batchSrcText, compareCanvasTextOrder, GenParams, RATIOS, RES_KEYS, RES_MAP, cachedGenerationTasks, classifyErr, fmtDur, presetDisplayName, ratioOfSize, resOfSize, taskStallEndMs, wDedupeTaskIds
|
||
function inject(d) {
|
||
const D = d || {}
|
||
I = D.I
|
||
wPluginNodeVariants = D.wPluginNodeVariants
|
||
wPluginVariantMeta = D.wPluginVariantMeta
|
||
isBatchSrc = D.isBatchSrc
|
||
batchSrcText = D.batchSrcText
|
||
compareCanvasTextOrder = D.compareCanvasTextOrder
|
||
LocalTextField = D.LocalTextField
|
||
autoGrow = D.autoGrow
|
||
combineSourcePairs = D.combineSourcePairs
|
||
downloadUrl = D.downloadUrl
|
||
wResolveOutSrc = D.wResolveOutputSrc
|
||
isImageProducer = D.isImageProducer
|
||
nodePreviewRefsV2 = D.nodePreviewRefsV2
|
||
nodeInheritOf = D.nodeInheritOf
|
||
orderedUniqueRefNodes = D.orderedUniqueRefNodes
|
||
outProgUI = D.outProgUI
|
||
outThumbCache = D.outThumbCache
|
||
uploadRefToImageHost = D.uploadRefToImageHost
|
||
wDisplayThumbOf = D.wDisplayThumbOf
|
||
wImgSrcForNode = D.wImgSrcForNode
|
||
wImportImage = D.wImportImage
|
||
wPreviewUrlOf = D.wPreviewUrlOf
|
||
wRawCfg = D.wRawCfg
|
||
wResolveImg = D.wResolveImg
|
||
wThumbSrc = D.wThumbSrc
|
||
el = D.el
|
||
React = D.React
|
||
ReactDOM = D.ReactDOM
|
||
GenParams = D.GenParams
|
||
RATIOS = D.RATIOS
|
||
RES_KEYS = D.RES_KEYS
|
||
RES_MAP = D.RES_MAP
|
||
cachedGenerationTasks = D.cachedGenerationTasks
|
||
classifyErr = D.classifyErr
|
||
fmtDur = D.fmtDur
|
||
presetDisplayName = D.presetDisplayName
|
||
ratioOfSize = D.ratioOfSize
|
||
resOfSize = D.resOfSize
|
||
taskStallEndMs = D.taskStallEndMs
|
||
wDedupeTaskIds = D.wDedupeTaskIds
|
||
}
|
||
|
||
|
||
// ── relay ──────────────────────────────────────────────
|
||
function renderRelayBody(node, props, ctx) {
|
||
return el('div', { className: 'iwb-node-body iwb-relay-body' },
|
||
el('span', { className: 'iwb-relay-ring' }, null),
|
||
)
|
||
}
|
||
|
||
// ── 提示词「放大编辑」浮层(2026-11-01)──────────────────────
|
||
// 单栏**所见即所得**:contenteditable 内直接渲染样式(标题/列表/粗斜体/删除线/分割线),
|
||
// 保存时再转回纯文本 Markdown(数据仍是纯文本,不污染发给模型的提示词)。
|
||
// 工具条(2026-11-03 中文化):原来「—/B/I/S」靠单个符号认功能,实测认不出来;
|
||
// 「加粗/斜体/删除线」改成中文标签并让标签本身套对应字形(.iwb-md-*,见 style.css),
|
||
// 既读得懂又看得出效果。每组之间插竖线分隔(grp 变化即分隔)。
|
||
const PROMPT_TOOLS = [
|
||
{ k: 'H1', t: '一级标题(再点一次回到普通段落)', cmd: 'formatBlock', arg: '<h1>', grp: 1 },
|
||
{ k: 'H2', t: '二级标题(再点一次回到普通段落)', cmd: 'formatBlock', arg: '<h2>', grp: 1 },
|
||
{ k: 'H3', t: '三级标题(再点一次回到普通段落)', cmd: 'formatBlock', arg: '<h3>', grp: 1 },
|
||
{ k: '列表', t: '无序列表(列表内 Tab / Shift+Tab 升降级)', cmd: 'insertUnorderedList', grp: 2 },
|
||
{ k: '有序', t: '有序列表(列表内 Tab / Shift+Tab 升降级)', cmd: 'insertOrderedList', grp: 2 },
|
||
{ k: '分割线', t: '插入分割线', cmd: 'insertHorizontalRule', grp: 2 },
|
||
{ k: '加粗', t: '加粗(Ctrl/⌘+B)', cmd: 'bold', cls: 'iwb-md-b', grp: 3 },
|
||
{ k: '斜体', t: '斜体(Ctrl/⌘+I)', cmd: 'italic', cls: 'iwb-md-i', grp: 3 },
|
||
{ k: '删除线', t: '删除线', cmd: 'strikeThrough', cls: 'iwb-md-s', grp: 3 },
|
||
{ k: '清除格式', t: '清除全部格式(标题/列表/加粗/斜体/删除线);点错了按 Ctrl/⌘+Z 撤销', cmd: 'clearStyle', grp: 4 },
|
||
]
|
||
const mdEscape = (t) => String(t).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
|
||
const mdInlineToHtml = (t) => mdEscape(t)
|
||
.replace(/\*\*([^*]+)\*\*/g, '<b>$1</b>')
|
||
.replace(/~~([^~]+)~~/g, '<s>$1</s>')
|
||
.replace(/\*([^*]+)\*/g, '<i>$1</i>')
|
||
// 列表项:`- x` / `* x` / `+ x`(无序)、`1. x` / `1) x`(有序);前面的空格 = 层级。
|
||
// 多级列表在 DOM 里是 `<li>a<ul><li>b</li></ul></li>`,缩进每级 2 空格(见 LIST_INDENT)。
|
||
const LIST_ITEM_RE = /^([ \t]*)([-*+]|\d+[.)])[ \t]+(.*)$/
|
||
const LIST_INDENT = ' '
|
||
const listIndentOf = (ws) => { let n = 0; for (let i = 0; i < ws.length; i++) n += ws[i] === '\t' ? 2 : 1; return n }
|
||
const mdToHtml = (md) => {
|
||
const out = []
|
||
// 列表用栈维护(每层记缩进宽度 + ul/ol):缩进回退就逐层关掉,同级换类型就在原位换容器
|
||
const stack = []
|
||
const closeList = () => { while (stack.length) out.push('</li></' + stack.pop().tag + '>') }
|
||
for (const ln of String(md || '').split('\n')) {
|
||
const h = /^(#{1,3})\s+(.*)$/.exec(ln)
|
||
if (h) { closeList(); const n = h[1].length; out.push('<h' + n + '>' + mdInlineToHtml(h[2]) + '</h' + n + '>'); continue }
|
||
if (/^---+$/.test(ln.trim())) { closeList(); out.push('<hr>'); continue }
|
||
const li = LIST_ITEM_RE.exec(ln)
|
||
if (li) {
|
||
const ind = listIndentOf(li[1])
|
||
const tag = /^[-*+]$/.test(li[2]) ? 'ul' : 'ol'
|
||
const top = () => stack[stack.length - 1]
|
||
while (stack.length && ind < top().indent) out.push('</li></' + stack.pop().tag + '>')
|
||
if (!stack.length || ind > top().indent) { out.push('<' + tag + '>'); stack.push({ indent: ind, tag }) }
|
||
else if (top().tag !== tag) { out.push('</li></' + stack.pop().tag + '>'); out.push('<' + tag + '>'); stack.push({ indent: ind, tag }) }
|
||
else out.push('</li>')
|
||
out.push('<li>' + mdInlineToHtml(li[3]))
|
||
continue
|
||
}
|
||
closeList()
|
||
out.push(ln ? '<div>' + mdInlineToHtml(ln) + '</div>' : '<div><br></div>')
|
||
}
|
||
closeList()
|
||
return out.join('')
|
||
}
|
||
// skipList:读 `<li>` 自己的文字时不把嵌套列表的内容算进来(否则会重复一遍)
|
||
const htmlInlineToMd = (n, skipList) => {
|
||
let s = ''
|
||
n.childNodes.forEach((c) => {
|
||
if (c.nodeType === 3) { s += c.nodeValue; return }
|
||
if (c.nodeType !== 1) return
|
||
const t = c.tagName.toLowerCase()
|
||
if (skipList && (t === 'ul' || t === 'ol')) return
|
||
const inner = htmlInlineToMd(c, skipList)
|
||
if (t === 'b' || t === 'strong') s += '**' + inner + '**'
|
||
else if (t === 'i' || t === 'em') s += '*' + inner + '*'
|
||
else if (t === 's' || t === 'strike' || t === 'del') s += '~~' + inner + '~~'
|
||
else if (t === 'br') s += '\n'
|
||
else s += inner
|
||
})
|
||
return s
|
||
}
|
||
// 块级容器 → 一行 Markdown。**必须裁掉首尾换行**(原因见下方「行距」注释)。
|
||
const blockToMd = (n, skipList) => htmlInlineToMd(n, skipList).replace(/^\n+/, '').replace(/\n$/, '')
|
||
// 列表 → 逐行 Markdown:本级一行、嵌套列表交给下一层(缩进 2 空格/级)
|
||
const listToMd = (listEl, depth, lines) => {
|
||
const tag = listEl.tagName.toLowerCase()
|
||
const pad = LIST_INDENT.repeat(Math.min(depth, 6))
|
||
let seq = Number(listEl.getAttribute('start')) || 1
|
||
listEl.childNodes.forEach((li) => {
|
||
if (li.nodeType !== 1 || li.tagName.toLowerCase() !== 'li') return
|
||
lines.push(pad + (tag === 'ol' ? (seq++) + '. ' : '- ') + blockToMd(li, true))
|
||
li.childNodes.forEach((sub) => {
|
||
if (sub.nodeType === 1 && /^(ul|ol)$/.test(sub.tagName.toLowerCase())) listToMd(sub, depth + 1, lines)
|
||
})
|
||
})
|
||
}
|
||
// 「行距越点越宽」的根因(2026-11-03):空行在 contenteditable 里是 `<div><br></div>`,
|
||
// `<br>` 被记成 `\n` 后又被 join 的 `\n` 叠一层 ⇒ 一个空行读出来是 2 个 `\n`;
|
||
// 而「清除格式」会 `readMd() → mdToHtml() → innerHTML` 重渲染 ⇒ 每点一次空行翻倍。
|
||
// 修法:块级容器只取「一行」(裁首尾 `\n`),顶层散落的文本节点/`<br>` 也按单行处理。
|
||
const htmlToMd = (root) => {
|
||
const lines = []
|
||
root.childNodes.forEach((c) => {
|
||
if (c.nodeType === 3) { const t = String(c.nodeValue || '').replace(/\n+$/, ''); if (t.trim()) lines.push(t); return }
|
||
if (c.nodeType !== 1) return
|
||
const t = c.tagName.toLowerCase()
|
||
if (t === 'h1' || t === 'h2' || t === 'h3') lines.push('#'.repeat(Number(t[1])) + ' ' + blockToMd(c))
|
||
else if (t === 'hr') lines.push('---')
|
||
else if (t === 'ul' || t === 'ol') listToMd(c, 0, lines)
|
||
else if (t === 'br') lines.push('')
|
||
else lines.push(blockToMd(c))
|
||
})
|
||
return lines.join('\n')
|
||
}
|
||
function PromptExpandModal(p) {
|
||
const [copied, setCopied] = React.useState(false)
|
||
const editorRef = React.useRef(null)
|
||
const mdRef = React.useRef(p.value || '')
|
||
const readMd = () => { const r = editorRef.current; return r ? htmlToMd(r) : String(mdRef.current || '') }
|
||
// 保存:顺手裁掉行尾空行(用户敲空的尾巴没有语义,留着只会在下次重渲染时被放大成多行)
|
||
const save = () => {
|
||
const md = readMd().replace(/\n+$/, '')
|
||
try { if (typeof p.onCommit === 'function') p.onCommit(md) } finally { if (typeof p.onClose === 'function') p.onClose() }
|
||
}
|
||
// 光标在编辑器内的字符偏移;取不到(选区在外面 / 没选区)返回 -1 = 落到末尾
|
||
const caretPos = () => {
|
||
const r = editorRef.current
|
||
const sel = window.getSelection()
|
||
if (!r || !sel || !sel.rangeCount) return -1
|
||
const rg = sel.getRangeAt(0)
|
||
if (!r.contains(rg.startContainer)) return -1
|
||
const pre = rg.cloneRange()
|
||
pre.selectNodeContents(r)
|
||
pre.setEnd(rg.startContainer, rg.startOffset)
|
||
return pre.toString().length
|
||
}
|
||
const setCaret = (pos) => {
|
||
const r = editorRef.current
|
||
if (!r) return
|
||
r.focus()
|
||
const sel = window.getSelection()
|
||
if (!sel) return
|
||
const rg = document.createRange()
|
||
let left = pos < 0 ? Infinity : pos
|
||
const walk = document.createTreeWalker(r, NodeFilter.SHOW_TEXT)
|
||
for (let n = walk.nextNode(); n; n = walk.nextNode()) {
|
||
if (left <= n.nodeValue.length) { rg.setStart(n, left); rg.collapse(true); sel.removeAllRanges(); sel.addRange(rg); return }
|
||
left -= n.nodeValue.length
|
||
}
|
||
rg.selectNodeContents(r)
|
||
rg.collapse(false)
|
||
sel.removeAllRanges()
|
||
sel.addRange(rg)
|
||
}
|
||
// 自带撤销栈(2026-11-03):格式类操作(如「清除格式」)是**整体重渲染 innerHTML**,
|
||
// 浏览器原生撤销栈到此断掉,Ctrl+Z 撤不回来。这里自己存「操作前快照」,但**不抢**原生撤销:
|
||
// 只有当内容自我们上次重渲染后没被原生编辑改过(innerHTML === applied)时才接管 Ctrl+Z;
|
||
// 期间用户又打了字 ⇒ 先让原生栈撤掉打字(撤到等于 applied 时,下一次按键再接上我们的栈)。
|
||
// 试过 `insertHTML` 替代 innerHTML(进原生栈),实测选区落在 <h1> 里时会把整段嵌进 h1,废弃。
|
||
const undoRef = React.useRef([])
|
||
const redoRef = React.useRef([])
|
||
const appliedRef = React.useRef(null)
|
||
const pushUndo = () => {
|
||
const r = editorRef.current
|
||
if (!r) return
|
||
undoRef.current.push({ html: r.innerHTML, at: caretPos() })
|
||
if (undoRef.current.length > 20) undoRef.current.shift()
|
||
redoRef.current = []
|
||
}
|
||
const stepHistory = (isRedo) => {
|
||
const r = editorRef.current
|
||
if (!r || r.innerHTML !== appliedRef.current) return false
|
||
const from = isRedo ? redoRef.current : undoRef.current
|
||
const to = isRedo ? undoRef.current : redoRef.current
|
||
const st = from.pop()
|
||
if (!st) return false
|
||
to.push({ html: r.innerHTML, at: caretPos() })
|
||
r.innerHTML = st.html
|
||
appliedRef.current = r.innerHTML
|
||
mdRef.current = readMd()
|
||
setCaret(st.at)
|
||
return true
|
||
}
|
||
const clearStyle = () => {
|
||
const r = editorRef.current
|
||
if (!r) return
|
||
const at = caretPos()
|
||
// 清除**整段**样式:走文本层去标记再重新渲染(顺序不会被打乱,也不依赖选区/execCommand 的实现差异)。
|
||
// 重渲染会把光标打回开头 ⇒ 按字符偏移还原(2026-11-03)。
|
||
const md = readMd()
|
||
.replace(/^#{1,3}\s+/gm, '')
|
||
.replace(/^[ \t]*(?:[-*+]|\d+[.)])[ \t]+/gm, '')
|
||
.replace(/\*\*([^*]+)\*\*/g, '$1').replace(/~~([^~]+)~~/g, '$1').replace(/\*([^*]+)\*/g, '$1')
|
||
pushUndo()
|
||
mdRef.current = md
|
||
r.innerHTML = mdToHtml(md)
|
||
appliedRef.current = r.innerHTML
|
||
setCaret(at)
|
||
}
|
||
const exec = (cmd, arg) => {
|
||
const r = editorRef.current
|
||
if (!r) return
|
||
if (cmd === 'clearStyle') return clearStyle()
|
||
r.focus()
|
||
let a = arg
|
||
// 标题按钮再点一次 ⇒ 回到普通段落(Chrome 的 formatBlock 对同名标签不做切换,会卡在标题上)
|
||
if (cmd === 'formatBlock' && '<' + String(document.queryCommandValue('formatBlock') || '').toLowerCase() + '>' === arg) a = '<div>'
|
||
try { document.execCommand(cmd, false, a) } catch (e) { /* 老浏览器忽略 */ }
|
||
mdRef.current = readMd()
|
||
}
|
||
const copy = async () => {
|
||
const v = readMd()
|
||
try { await navigator.clipboard.writeText(v) } catch (e) {
|
||
try { const r = editorRef.current; if (r) { const rg = document.createRange(); rg.selectNodeContents(r); const sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(rg); document.execCommand('copy') } } catch (e2) { /* ignore */ }
|
||
}
|
||
setCopied(true)
|
||
setTimeout(() => setCopied(false), 1200)
|
||
}
|
||
// 只在挂载时把 Markdown 渲染进编辑器(之后不再回写 innerHTML,避免光标跳动);
|
||
// 顺手聚焦并把光标放到末尾 —— 打开就能直接打字,不用先点一下编辑区(2026-11-03)
|
||
React.useEffect(() => { const r = editorRef.current; if (r) { r.innerHTML = mdToHtml(p.value || ''); setCaret(-1) } }, [])
|
||
React.useEffect(() => {
|
||
const onKey = (e) => { if (e.key === 'Escape') { e.stopPropagation(); save() } }
|
||
window.addEventListener('keydown', onKey)
|
||
return () => window.removeEventListener('keydown', onKey)
|
||
}, [])
|
||
return ReactDOM.createPortal(el('div', { className: 'iwb-modal-mask iwb-prompt-mask', onPointerDown: (e) => { if (e.target === e.currentTarget) save() } },
|
||
el('div', { className: 'iwb-prompt-modal' },
|
||
el('div', { className: 'iwb-prompt-bar' },
|
||
...PROMPT_TOOLS.reduce((acc, t, i) => {
|
||
if (i && t.grp !== PROMPT_TOOLS[i - 1].grp) acc.push(el('span', { key: 'sep' + i, className: 'iwb-prompt-sep' }, null))
|
||
acc.push(el('button', {
|
||
key: t.k, className: 'iwb-prompt-tool' + (t.cls ? ' ' + t.cls : ''), title: t.t,
|
||
onMouseDown: (e) => e.preventDefault(), onClick: () => exec(t.cmd, t.arg),
|
||
}, t.k))
|
||
return acc
|
||
}, []),
|
||
// 复制紧跟在格式按钮之后(用户反馈:别和关闭挤在一起),后面才是弹性留白 + 关闭
|
||
el('span', { key: 'sep-copy', className: 'iwb-prompt-sep' }, null),
|
||
copied ? el('span', { key: 'ok', className: 'iwb-prompt-copied' }, '已复制') : null,
|
||
el('button', { key: 'copy', className: 'iwb-prompt-tool iwb-prompt-copy', 'aria-label': '复制', title: '复制全文(Markdown 纯文本)', onClick: copy }, I('copy')),
|
||
el('span', { key: 'sp', className: 'iwb-prompt-bar-sp' }, null),
|
||
el('button', { key: 'x', className: 'iwb-prompt-x', 'aria-label': '关闭', title: '关闭(自动保存)', onClick: save }, '×'),
|
||
),
|
||
el('div', {
|
||
ref: editorRef, className: 'iwb-prompt-area iwb-md-editor', contentEditable: true, suppressContentEditableWarning: true,
|
||
'data-placeholder': '输入画面描述(提示词)…',
|
||
onInput: () => { mdRef.current = readMd() },
|
||
// 只接纯文本:从网页/Word 粘贴会把行内样式、图片、表格结构一起塞进来,
|
||
// 转 Markdown 时结构全丢、正文还可能被拆成奇怪的嵌套块(2026-11-03)
|
||
onPaste: (e) => {
|
||
const cd = e.clipboardData
|
||
if (!cd) return
|
||
e.preventDefault()
|
||
const t = cd.getData('text/plain')
|
||
if (t) { try { document.execCommand('insertText', false, t) } catch (err) { /* 老浏览器忽略 */ } }
|
||
mdRef.current = readMd()
|
||
},
|
||
onKeyDown: (e) => {
|
||
if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') { e.preventDefault(); save(); return }
|
||
// 列表内 Tab / Shift+Tab = 降级/升级(浏览器默认 Tab 会跳到下一个可聚焦元素,等于出不了多级列表)
|
||
if (e.key === 'Tab' && !e.metaKey && !e.ctrlKey && !e.altKey) {
|
||
let inList = false
|
||
try { inList = document.queryCommandState('insertUnorderedList') || document.queryCommandState('insertOrderedList') } catch (err) { inList = false }
|
||
if (inList) {
|
||
e.preventDefault()
|
||
try { document.execCommand(e.shiftKey ? 'outdent' : 'indent') } catch (err) { /* ignore */ }
|
||
mdRef.current = readMd()
|
||
}
|
||
return
|
||
}
|
||
// 撤销 / 重做:能用我们自己的栈就用(撤掉「清除格式」这类整体重渲染),否则让浏览器原生栈处理
|
||
if ((e.metaKey || e.ctrlKey) && /^z$/i.test(e.key)) {
|
||
if (stepHistory(e.shiftKey)) { e.preventDefault(); return }
|
||
setTimeout(() => { mdRef.current = readMd() }, 0)
|
||
return
|
||
}
|
||
if ((e.metaKey || e.ctrlKey) && /^y$/i.test(e.key)) {
|
||
if (stepHistory(true)) { e.preventDefault(); return }
|
||
}
|
||
},
|
||
onPointerDown: (e) => e.stopPropagation(),
|
||
}),
|
||
)), document.body)
|
||
}
|
||
// 供气泡「放大编辑」按钮调用:临时挂一个 root 渲染浮层,关闭即销毁
|
||
function openPromptExpand(opts) {
|
||
const o = opts || {}
|
||
const host = document.createElement('div')
|
||
document.body.appendChild(host)
|
||
const root = ReactDOM.createRoot(host)
|
||
const close = () => { try { root.unmount() } catch (e) { /* ignore */ } try { host.remove() } catch (e2) { /* ignore */ } }
|
||
root.render(el(PromptExpandModal, { value: o.value || '', onCommit: o.onCommit, onClose: close }))
|
||
return close
|
||
}
|
||
|
||
// ── 继承 / 接管 状态条(2026-11-14,提示词与文本节点共用)────────────────────
|
||
// 用户反馈:「样式节点连到提示词/文本节点,框里是空的,是不是没做?」——数据层其实一直通
|
||
// (resolveNodeTaskValues 里 `own || t.text`,自己没写字就用上游那段),但节点体只读自己的
|
||
// data.text,所以看不出上游给了什么,也没法在原文上改。这里把状态显式化:
|
||
// · 继承态:显示上游文本(只读感受由 .is-inherited 的字色体现)——改一个字就写进 data.text = 接管
|
||
// · 接管态:显示「已固定 · 恢复跟随」,点了清空 data.text 回到跟随
|
||
function nodeLabelOf(id, nodesArr) {
|
||
const n = (nodesArr || []).find((x) => x.id === id)
|
||
if (!n) return ''
|
||
const d = n.data || {}
|
||
return String(d.title || d.name || d.styleId || '').trim()
|
||
}
|
||
function inheritBar(info, opts) {
|
||
const o = opts || {}
|
||
const own = !!info.own
|
||
// 没有上游节点(纯手写提示词)就不要显示「已固定 / 恢复跟随」,
|
||
// 否则点「恢复跟随」会把用户手写的文案清空。
|
||
if (!info.hasUpstream) return null
|
||
if (!own && !info.text) return null
|
||
const srcName = nodeLabelOf(info.sourceNodeId, o.nodes)
|
||
const parts = [
|
||
el('span', { className: 'iwb-inherit-tag' + (own ? ' is-taken' : ''), key: 'tag' }, own ? '已固定' : '继承'),
|
||
el('span', {
|
||
className: 'iwb-inherit-src',
|
||
key: 'src',
|
||
title: own
|
||
? '这段文案是你在本节点上改定的,不再跟随上游;点右侧「恢复跟随」可清空'
|
||
: '来自 ' + (srcName || '上一级节点') + '。直接改字就会固定成本节点自己的文案',
|
||
}, own ? '当前用你改的文案' : ('来自 ' + (srcName || '上一级'))),
|
||
]
|
||
if (!own && info.more > 0) {
|
||
parts.push(el('span', {
|
||
className: 'iwb-inherit-more',
|
||
key: 'more',
|
||
title: '多路上游只取画布上最靠上的那一路;要把几路合并成一段,请用「组合」节点',
|
||
}, '另有 ' + info.more + ' 路未用'))
|
||
}
|
||
if (own) parts.push(el('button', { className: 'iwb-inherit-reset', key: 'reset', title: '清空本节点文案,回到跟随上游', onPointerDown: o.stop, onClick: o.onReset }, '恢复跟随'))
|
||
return el('div', { className: 'iwb-inherit-bar' + (own ? ' is-taken' : '') }, ...parts)
|
||
}
|
||
|
||
// ── prompt ──────────────────────────────────────────────
|
||
function renderPromptBody(node, props, ctx) {
|
||
const { onUpdate, refMini, stop } = ctx
|
||
const ownText = node.data.text || ''
|
||
// 多图缩略:连接的所有参考图节点按坐标排序,小图 + 序号角标(图1、图2…)
|
||
const refNodes = nodePreviewRefsV2(node, props.nodes || [], props.edges || [])
|
||
const refThumbs = []
|
||
for (let ri = 0; ri < refNodes.length; ri++) refThumbs.push(refMini(refNodes[ri], ri))
|
||
// 上游继承:自己没写字就把上游那段显示出来(改字即接管)
|
||
const inh = nodeInheritOf(node, props.nodes || [], props.edges || [])
|
||
const inherited = (!inh.own && inh.text) ? inh.text : ''
|
||
return el('div', { className: 'iwb-node-body' },
|
||
inheritBar(inh, { nodes: props.nodes || [], stop, onReset: () => onUpdate(node.id, { text: '' }) }),
|
||
el(LocalTextField, {
|
||
key: 'prompt-text',
|
||
textarea: true,
|
||
className: 'iwb-textarea iwb-textarea-plain' + (inherited ? ' is-inherited' : ''),
|
||
placeholder: '输入画面描述(提示词)…',
|
||
value: ownText || inherited,
|
||
readOnly: !props.editingBody,
|
||
refEl: (el0) => { if (el0) autoGrow(el0) },
|
||
onInput: (e) => autoGrow(e.target),
|
||
onCommit: (v) => onUpdate(node.id, { text: v }), // 静止 350ms / 失焦才写回(打字不再整棵重渲染)
|
||
onPointerDown: (e) => { if (props.editingBody) e.stopPropagation(); else e.preventDefault() },
|
||
onFocus: () => { if (!props.editingBody) props.setEditingBody && props.setEditingBody(true) },
|
||
onBlur: () => props.setEditingBody && props.setEditingBody(false),
|
||
}),
|
||
refThumbs.length ? el('div', { className: 'iwb-task-refs' }, refThumbs) : null,
|
||
)
|
||
}
|
||
|
||
// ── plugin ──────────────────────────────────────────────
|
||
function renderPluginBody(node, props, ctx) {
|
||
const { onUpdate, stop } = ctx
|
||
const variant = wPluginNodeVariants.find((v) => v.id === ((node.data && node.data.variant) || '')) || wPluginVariantMeta.get(String((node.data && node.data.variant) || ''))
|
||
const text = (node.data && node.data.text) || ''
|
||
return el('div', { className: 'iwb-node-body' },
|
||
el('div', { className: 'iwb-hint' }, variant ? String(variant.title) : '插件节点(变体未注册)'),
|
||
el(LocalTextField, {
|
||
key: 'plugin-text',
|
||
textarea: true,
|
||
className: 'iwb-textarea iwb-textarea-plain',
|
||
placeholder: '内容…',
|
||
value: text,
|
||
readOnly: !props.editingBody,
|
||
refEl: (el0) => { if (el0) autoGrow(el0) },
|
||
onInput: (e) => autoGrow(e.target),
|
||
onCommit: (v) => onUpdate(node.id, { text: v }),
|
||
onPointerDown: (e) => { if (props.editingBody) e.stopPropagation(); else e.preventDefault() },
|
||
onFocus: () => { if (!props.editingBody) props.setEditingBody && props.setEditingBody(true) },
|
||
onBlur: () => props.setEditingBody && props.setEditingBody(false),
|
||
}),
|
||
variant && typeof variant.run === 'function' ? el('button', {
|
||
className: 'iwb-btn iwb-btn-sm',
|
||
onPointerDown: stop,
|
||
onClick: () => { try { variant.run({ id: node.id, data: node.data || {}, text }) } catch (e) { if (props.onNotice) props.onNotice({ type: 'err', text: '插件运行失败:' + String((e && e.message) || e) }) } },
|
||
}, '运行') : null,
|
||
)
|
||
}
|
||
|
||
// ── textout ──────────────────────────────────────────────
|
||
function renderTextoutBody(node, props, ctx) {
|
||
const { onUpdate, refMini, stop } = ctx
|
||
// v2 §7:文案输出节点(左入接 LLM / 批量加文案来源,右出接生图;生图优先取此文案)
|
||
const d = node.data || {}
|
||
const outCount = (props.edges || []).filter((e) => e.from === node.id).length
|
||
// 批量加文案(batch)来源:显示对应来源的文案(batchSrcId 指定,未指定取第一个)
|
||
let batchSrcTxt = ''
|
||
const bEdgeT = (props.edges || []).filter((e) => e.to === node.id).map((e) => ({ e, b: (props.nodes || []).find((n) => n.id === e.from) })).find((o) => o.b && o.b.type === 'batch')
|
||
if (bEdgeT) {
|
||
const bsrcsT = (props.edges || []).filter((e) => e.to === bEdgeT.b.id).map((e) => (props.nodes || []).find((n) => n.id === e.from)).filter((n) => isBatchSrc(n, props.edges || [], props.nodes || [])).slice().sort((a, b2) => (a.y - b2.y) || (a.x - b2.x))
|
||
const tgtT = bEdgeT.e.batchSrcId ? bsrcsT.find((s) => s.id === bEdgeT.e.batchSrcId) : bsrcsT[0]
|
||
if (tgtT) batchSrcTxt = batchSrcText(tgtT, props.edges || [], props.nodes || [])
|
||
}
|
||
// 透传参考图展示(按来源顺序,像提示词面板)
|
||
const tRefs = nodePreviewRefsV2(node, props.nodes || [], props.edges || [])
|
||
const tThumbs = []
|
||
for (let ti = 0; ti < tRefs.length; ti++) tThumbs.push(refMini(tRefs[ti], ti))
|
||
// 上游继承(与提示词节点同规则):自己没写字就显示上游那段,改字即接管
|
||
const inh = nodeInheritOf(node, props.nodes || [], props.edges || [])
|
||
const inherited = (!inh.own && inh.text) ? inh.text : ''
|
||
return el('div', { className: 'iwb-node-body' },
|
||
inheritBar(inh, { nodes: props.nodes || [], stop, onReset: () => onUpdate(node.id, { text: '' }) }),
|
||
el('textarea', {
|
||
className: 'iwb-textarea iwb-textarea-plain' + (inherited ? ' is-inherited' : ''),
|
||
placeholder: batchSrcTxt && !(d.text || '').trim() ? '(来源文案)' + batchSrcTxt.slice(0, 60) : '润色后的文案(可手动编辑)',
|
||
value: (d.text || '') || inherited,
|
||
readOnly: !props.editingBody,
|
||
ref: (el0) => { if (el0) autoGrow(el0) },
|
||
onChange: (e) => { onUpdate(node.id, { text: e.target.value }); autoGrow(e.target) },
|
||
onPointerDown: (e) => { if (props.editingBody) e.stopPropagation(); else e.preventDefault() },
|
||
onFocus: () => { if (!props.editingBody) props.setEditingBody && props.setEditingBody(true) },
|
||
onBlur: () => props.setEditingBody && props.setEditingBody(false),
|
||
}, null),
|
||
// 参考图显示在节点最下面(类似提示词节点)
|
||
tThumbs.length ? el('div', { className: 'iwb-task-refs' }, tThumbs) : null,
|
||
)
|
||
}
|
||
|
||
// ── combine ──────────────────────────────────────────────
|
||
function renderCombineBody(node, props, ctx) {
|
||
const { onUpdate, stop, refMini } = ctx
|
||
const d = node.data || {}
|
||
const ins = (props.edges || []).filter((e) => e.to === node.id).map((e) => (props.nodes || []).find((n) => n.id === e.from)).filter(Boolean).slice().sort((a, b) => (a.y - b.y) || (a.x - b.x))
|
||
// 传入的参考图(按来源透传),显示在节点最下面(类似提示词节点)
|
||
// 分隔符选项:2026-10-30 恢复(默认逗号),但控件挪到「组合(N)」同一行右侧(省一整行高度)
|
||
const sepOpts = [['\n', '换行'], [' ', '空格'], [', ', '逗号'], ['、', '顿号'], [' - ', '连字符']]
|
||
const cRefs = nodePreviewRefsV2(node, props.nodes || [], props.edges || [])
|
||
const cThumbs = []
|
||
for (let ci = 0; ci < cRefs.length; ci++) cThumbs.push(refMini(cRefs[ci], ci))
|
||
// 来源列表按「真实文本源」坐标统一排序(方案1,与 combined 一致):relay 透明穿透,拖动中继/文本源都不改变其相对顺序
|
||
const srcRows = []
|
||
const cPairs = []
|
||
for (const inE of (props.edges || [])) {
|
||
if (inE.to !== node.id) continue
|
||
const srcN = (props.nodes || []).find((n) => n.id === inE.from)
|
||
if (!srcN) continue
|
||
if (srcN.data && srcN.data.enabled === false) continue // 停用来源:不显示
|
||
cPairs.push.apply(cPairs, combineSourcePairs(srcN, inE, props.edges || [], props.nodes || []))
|
||
}
|
||
cPairs.sort((a, b) => compareCanvasTextOrder(a.n, b.n))
|
||
for (const cp of cPairs) {
|
||
const pv = cp.text.slice(0, 24) + (cp.text.length > 24 ? '…' : '')
|
||
// 来源标签(2026-11-14):样式节点接进组合后,每行都只剩「▸ 前 24 字」,接两个就分不清
|
||
// 哪行来自 Vigo-08、哪行来自提示词。只给「声明了 outKind:'prompt' 的插件节点」打标 ——
|
||
// 内置 prompt / textout 一般没名字,保持原来的单行样式(零视觉回归)。
|
||
const isPluginPromptSrc = !!(cp.n.data && cp.n.data.outKind === 'prompt')
|
||
const srcName = isPluginPromptSrc ? String(cp.n.data.name || cp.n.data.styleId || '样式').trim() : ''
|
||
srcRows.push(el('div', { key: cp.n.id + '_' + cp.text, className: 'iwb-combine-src' },
|
||
srcName ? el('span', { className: 'iwb-combine-src-tag', title: '来源:' + srcName }, srcName) : null,
|
||
'▸ ' + pv))
|
||
}
|
||
return el('div', { className: 'iwb-node-body' },
|
||
el('div', { className: 'iwb-row iwb-gen-head' },
|
||
el('span', { className: 'iwb-label iwb-gen-title' }, '组合' + ((srcRows.length || cThumbs.length) ? '(' + (srcRows.length + cThumbs.length) + ')' : '')),
|
||
el('select', {
|
||
className: 'iwb-input iwb-combine-sep',
|
||
title: '来源之间的分隔符',
|
||
value: (d.sep == null || d.sep === '') ? ', ' : d.sep,
|
||
onChange: (e) => onUpdate(node.id, { sep: e.target.value }),
|
||
onPointerDown: stop,
|
||
}, sepOpts.map(([v, l]) => el('option', { key: v, value: v }, l))),
|
||
),
|
||
(srcRows.length || cThumbs.length)
|
||
? (srcRows.length ? el('div', { className: 'iwb-combine-srcs' }, srcRows) : null)
|
||
: el('div', { className: 'iwb-err' }, '请连接有文本的节点或参考图片作为来源'),
|
||
// 参考图显示在节点最下面(类似提示词节点)
|
||
cThumbs.length ? el('div', { className: 'iwb-task-refs' }, cThumbs) : null,
|
||
)
|
||
}
|
||
|
||
// ── llm ──────────────────────────────────────────────
|
||
function renderLlmBody(node, props, ctx) {
|
||
const { onUpdate, busy, stop } = ctx
|
||
// v2 §7:LLM 节点(左入接 Prompt,右出接文案输出;指令可自定义,留空用全局默认模板)
|
||
const d = node.data || {}
|
||
const busyLlm = busy[node.id + '::llm']
|
||
const llmCfg = (props.config && props.config.llm) || {}
|
||
const llmProv = (llmCfg.providers || []).find((p) => p.id === llmCfg.defaultProviderId) || (llmCfg.providers || [])[0]
|
||
const llmDefM = llmProv && (llmProv.defaultModel || ((llmProv.models || []).find((m) => m && m.default && m.name) && (llmProv.models || []).find((m) => m && m.default && m.name).name || (llmProv.models || [])[0] && (llmProv.models)[0].name) || '')
|
||
const globalInst = (llmCfg.defaultInstruction || '').trim()
|
||
const promptSrc = (props.edges || []).filter((e) => e.to === node.id).map((e) => (props.nodes || []).find((n) => n.id === e.from)).find((n) => n && n.type === 'prompt')
|
||
const outCount = (props.edges || []).filter((e) => e.from === node.id).length
|
||
const preview = promptSrc ? ((promptSrc.data.text || '').trim()) : ''
|
||
return el('div', { className: 'iwb-node-body' },
|
||
el('div', { className: 'iwb-row iwb-ref-head' },
|
||
el('span', { className: 'iwb-hint' }, promptSrc ? '来自:' + preview.slice(0, 16) + (preview.length > 16 ? '…' : '') : '未连接 提示词'),
|
||
el('span', { className: 'iwb-hint' }, '下游 ' + outCount + ' 个'),
|
||
el('span', { className: 'iwb-hint' }, (llmProv && llmProv.baseUrl) ? ('渠道:' + (llmProv.name || '未命名') + (llmDefM ? ' · ' + llmDefM : '')) : '未配置 LLM 渠道(设置 → LLM 服务)'),
|
||
),
|
||
el('div', { className: 'iwb-label' }, '指令 / 系统提示词(留空用全局默认)'),
|
||
el('textarea', {
|
||
className: 'iwb-textarea',
|
||
placeholder: globalInst || '默认润色指令在「设置 → LLM 服务」配置',
|
||
value: d.instruction || '',
|
||
ref: (el0) => { if (el0) autoGrow(el0) },
|
||
onChange: (e) => { onUpdate(node.id, { instruction: e.target.value }); autoGrow(e.target) },
|
||
onPointerDown: stop,
|
||
}, null),
|
||
el('div', { className: 'iwb-row iwb-actions' },
|
||
el('button', {
|
||
className: 'iwb-btn iwb-btn-primary',
|
||
disabled: !!busyLlm,
|
||
onClick: () => props.onRunLlm && props.onRunLlm(node.id),
|
||
onPointerDown: stop,
|
||
}, busyLlm ? '⏳ 润色中…' : '润色'),
|
||
el('select', {
|
||
className: 'iwb-input iwb-llm-model-sel',
|
||
title: '本次润色使用模型(默认跟随设置中「默认模型」,节点内可覆盖)',
|
||
value: d.model || llmDefM || '',
|
||
onChange: (e) => onUpdate(node.id, { model: e.target.value }),
|
||
onPointerDown: stop,
|
||
},
|
||
(llmProv && llmProv.models && llmProv.models.length
|
||
? llmProv.models.map((m, mi) => el('option', { key: mi, value: m.name }, m.name + ((llmDefM && m.name === llmDefM) ? '(默认)' : '')))
|
||
: (llmDefM ? [el('option', { key: 'd', value: llmDefM }, llmDefM + '(默认)')] : [el('option', { key: 'e', value: '' }, '(未配置模型)')]))),
|
||
),
|
||
d.result && d.result.text ? el('div', { className: 'iwb-hint' }, '✓ 已润色 ' + d.result.text.length + ' 字 → 写入文本节点') : null,
|
||
)
|
||
}
|
||
|
||
// ── batch ──────────────────────────────────────────────
|
||
function renderBatchBody(node, props, ctx) {
|
||
const { onUpdate, stop } = ctx
|
||
// 连接节点:多个来源各自追加统一文案,每个来源对应一对输入/输出端口
|
||
const d = node.data || {}
|
||
const bsrcs = (props.edges || []).filter((e) => e.to === node.id).map((e) => (props.nodes || []).find((n) => n.id === e.from)).filter((n) => isBatchSrc(n, props.edges || [], props.nodes || [])).slice().sort((a, b) => (a.y - b.y) || (a.x - b.x))
|
||
const outCount = Object.keys(d.outs || {}).filter((k) => (props.nodes || []).some((n) => n.id === d.outs[k])).length // 兼容旧数据(手动模式下不再自动创建)
|
||
return el('div', { className: 'iwb-node-body' },
|
||
el('div', { className: 'iwb-row iwb-gen-head' },
|
||
el('span', { className: 'iwb-label iwb-gen-title' }, '连接' + (bsrcs.length ? '(' + bsrcs.length + ' 个来源)' : '')),
|
||
),
|
||
bsrcs.length
|
||
? el('div', { className: 'iwb-batch-srcs' },
|
||
bsrcs.map((s, i) => el('div', { key: s.id, className: 'iwb-batch-src' + (s.data && s.data.enabled === false ? ' iwb-batch-src-off' : ''), title: s.data.text || '' }, '▸ ' + ((s.data && s.data.enabled === false ? '(停用)' : ((s.data && s.data.title) || '').trim() || ('来源 ' + (i + 1)))))),
|
||
)
|
||
: el('div', { className: 'iwb-err' }, '连接 提示词节点(可连多个,每个分别输出)'),
|
||
el('div', { className: 'iwb-combine-row' },
|
||
el('span', { className: 'iwb-plabel' }, '分隔符'),
|
||
el('select', {
|
||
className: 'iwb-input',
|
||
title: '来源文本与统一文案之间的分隔符',
|
||
value: d.sep || '\n',
|
||
onChange: (e) => onUpdate(node.id, { sep: e.target.value }),
|
||
onPointerDown: stop,
|
||
}, [['\n', '换行'], [' ', '空格'], [', ', '逗号'], ['、', '顿号'], [' - ', '连字符']].map(([v, l]) => el('option', { key: v, value: v }, l))),
|
||
),
|
||
el('div', { className: 'iwb-combine-row' },
|
||
el('span', { className: 'iwb-plabel' }, '追加位置'),
|
||
el('select', {
|
||
className: 'iwb-input',
|
||
title: '统一文案添加到来源前面还是后面',
|
||
value: d.extraPos === 'before' ? 'before' : 'after',
|
||
onChange: (e) => onUpdate(node.id, { extraPos: e.target.value }),
|
||
onPointerDown: stop,
|
||
},
|
||
el('option', { value: 'after' }, '添加到来源后'),
|
||
el('option', { value: 'before' }, '添加到来源前'),
|
||
),
|
||
),
|
||
el('textarea', {
|
||
className: 'iwb-textarea',
|
||
placeholder: '统一追加的文案(如:,赛博朋克风格,高细节)',
|
||
value: d.extra || '',
|
||
ref: (el0) => { if (el0) autoGrow(el0) },
|
||
onChange: (e) => { onUpdate(node.id, { extra: e.target.value }); autoGrow(e.target) },
|
||
onPointerDown: stop,
|
||
}, null),
|
||
)
|
||
}
|
||
|
||
// ── ref ──────────────────────────────────────────────
|
||
function renderRefBody(node, props, ctx) {
|
||
const { onUpdate, stop } = ctx
|
||
const d = node.data || {}
|
||
const src = wResolveImg(d.localRef) || wResolveImg(d.data) || d.url
|
||
const hasImg = !!src
|
||
const commitRefUrl = (event) => {
|
||
const root = event && event.currentTarget && event.currentTarget.closest ? event.currentTarget.closest('.iwb-ref-body') : null
|
||
const input = root && root.querySelector('.iwb-ref-url-input')
|
||
const value = String((input && input.value) || '').trim()
|
||
if (!value) return
|
||
if (!/^https?:\/\//i.test(value)) return props.onNotice && props.onNotice('图片链接必须以 http:// 或 https:// 开头')
|
||
onUpdate(node.id, { url: value, data: null, localName: null, name: value.split('/').pop().split('?')[0] || '远程图片' })
|
||
}
|
||
// 序号徽标:全画布参考图节点按坐标排序中的位置(x 从左到右,同 x 按 y)
|
||
const allRefs = (props.nodes || []).filter((n) => n.type === 'ref' && !(n.data && n.data.enabled === false))
|
||
const sorted = orderedUniqueRefNodes(allRefs)
|
||
const idx = sorted.findIndex((n) => n.id === node.id)
|
||
const outCount = (props.edges || []).filter((e) => e.from === node.id).length
|
||
let refFileInput = null
|
||
const fileInput = el('input', {
|
||
type: 'file',
|
||
accept: 'image/*',
|
||
style: { display: 'none' },
|
||
ref: (el0) => { refFileInput = el0 },
|
||
onChange: (e) => {
|
||
const f = e.target.files && e.target.files[0]
|
||
if (!f) return
|
||
try {
|
||
const rd = new FileReader()
|
||
// v3.0.x:节点「上传参考图」与粘贴/拖放共用导入唯一收口(压缩 ≤1600 + 立即引用化)
|
||
rd.onload = () => wImportImage(rd.result, { onError: (msg) => { if (props.onNotice) props.onNotice(msg) } }, (r) => {
|
||
if (!r || !r.ok || !r.data) return
|
||
onUpdate(node.id, { data: r.data, name: f.name, localName: null, url: '' })
|
||
})
|
||
rd.onerror = () => { if (props.onNotice) props.onNotice('读取图片文件失败:' + String(f.name || '')) }
|
||
rd.readAsDataURL(f)
|
||
} catch (err) { console.error(err) }
|
||
},
|
||
}, null)
|
||
return el('div', { className: 'iwb-node-body iwb-ref-body' },
|
||
hasImg
|
||
? el('div', { className: 'iwb-ref-show' },
|
||
el('img', { className: 'iwb-ref-single', decoding: 'async', fetchPriority: 'low', src: wPreviewUrlOf((typeof wImgSrcForNode === 'function' ? wImgSrcForNode : wDisplayThumbOf)(wThumbSrc(src), Math.min(320, (props.node && props.node.w) || 280))), alt: '图片', draggable: false, onError: (e) => { try { const ov = wThumbSrc(src); if (ov && e.currentTarget && e.currentTarget.src !== ov) e.currentTarget.src = ov } catch (err) { /* ignore */ } }, title: '双击放大 · 单击可拖动' }),
|
||
(typeof d.url === 'string' && d.url) ? el('div', { className: 'iwb-ref-url-current', title: d.url }, 'URL 图片') : null,
|
||
)
|
||
: el('div', { className: 'iwb-ref-emptybox', title: '单击选中 · 双击上传图片', onDoubleClick: (e) => { e.stopPropagation(); if (refFileInput) refFileInput.click() } },
|
||
el('span', { className: 'iwb-ref-upload' }, '点击上传参考图'),
|
||
fileInput,
|
||
),
|
||
el('div', { className: 'iwb-ref-url-row' },
|
||
// 「上传到图库」:本地图片直接上传;只有 URL 的节点先取字节再上传(2026-11-01 用户要求常驻)
|
||
(d.data || (typeof d.url === 'string' && d.url)) ? el('button', {
|
||
className: 'iwb-btn iwb-btn-sm iwb-ref-upload-link',
|
||
disabled: props.uploadingRefId === node.id,
|
||
title: props.uploadingRefId === node.id ? '正在上传…' : '上传到图库:把这张图传到图库并填入链接',
|
||
'aria-label': '上传到图库',
|
||
onClick: async (e) => {
|
||
stop(e)
|
||
if (props.uploadingRefId === node.id) return
|
||
props.setUploadingRefId && props.setUploadingRefId(node.id)
|
||
try {
|
||
let payload = d.data
|
||
// 只有 URL 时:先取回字节(同源/允许 CORS 才能成功)
|
||
if (!payload) {
|
||
const res = await fetch(d.url, { credentials: 'same-origin' })
|
||
if (!res || !res.ok) throw new Error('图片下载失败(HTTP ' + (res && res.status) + ')')
|
||
const blob = await res.blob()
|
||
payload = await new Promise((done, fail) => {
|
||
const fr = new FileReader()
|
||
fr.onload = () => done(String(fr.result || ''))
|
||
fr.onerror = () => fail(new Error('读取图片失败'))
|
||
fr.readAsDataURL(blob)
|
||
})
|
||
}
|
||
const url = await uploadRefToImageHost(payload, wRawCfg(), d.name)
|
||
onUpdate(node.id, { url, data: null, localName: null, name: url.split('/').pop() || '在线图片' })
|
||
props.onNotice && props.onNotice('已上传到图库并填入链接')
|
||
} catch (err) {
|
||
props.onNotice && props.onNotice('上传失败:' + String((err && err.message) || err))
|
||
} finally {
|
||
props.setUploadingRefId && props.setUploadingRefId(null)
|
||
}
|
||
},
|
||
onPointerDown: stop,
|
||
}, el('svg', { viewBox: '0 0 24 24', width: 15, height: 15, 'aria-hidden': 'true' },
|
||
el('path', { d: 'M12 16V4m0 0L8 8m4-4 4 4M4 16v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2', fill: 'none', stroke: 'currentColor', 'stroke-width': 1.8, 'stroke-linecap': 'round', 'stroke-linejoin': 'round' }),
|
||
)) : null,
|
||
// 使用链接改为**按回车**(原来右侧还有一个 ✎ 按钮,用户要求去掉)
|
||
el('input', { className: 'iwb-input iwb-ref-url-input', defaultValue: (typeof d.url === 'string' && !d.data) ? d.url : '', placeholder: '输入图片 URL(回车使用)', onKeyDown: (e) => { if (e.key === 'Enter') commitRefUrl(e) }, onPointerDown: stop }),
|
||
),
|
||
|
||
el('div', { className: 'iwb-ref-foot' }, null),
|
||
)
|
||
}
|
||
|
||
// ── out ──────────────────────────────────────────────
|
||
// 输出节点的「结果组」:把各来源生图节点的 result 按**任务**归组并排序(纯函数,不改入参)。
|
||
//
|
||
// 背景(2026-11-04 用户实测「输出图片顺序与任务卡顺序对不上」):原实现在渲染时用**来源节点坐标**
|
||
// 反推组序 —— nodeFor() 只在「直连生图节点的上游」里找 promptId 前缀,一旦中继 / 连接 / 组合等
|
||
// 中间节点介入就一律匹配不到,全部落到 1e9 ⇒ 顺序退化成「谁先出图谁在前」;组内张序同样来自
|
||
// 追加写的 result 数组(并发完成顺序 ≈ 随机),同一个任务的第 2 张可能排在第 1 张前面。
|
||
//
|
||
// 现在顺序锚定**任务卡本身的顺序**(metaOf(gen) 返回该生图节点当前的任务列表 [{id,title}]):
|
||
// ① 生图节点按画布坐标(y → x);
|
||
// ② 任务在任务列表中的下标(列表里没有的旧结果排最后,按出图时间);
|
||
// ③ 变体序号 vi(同任务多张时第 1 张恒在第 2 张前),同 vi 按 at。
|
||
// 组标题也优先用任务当前标题(旧数据 / 中间节点链路都能拿到),不再靠坐标反查节点 data.title。
|
||
function outGroupsOf(srcGens, metaOf) {
|
||
const list = (Array.isArray(srcGens) ? srcGens : []).filter(Boolean)
|
||
const numOr = (v, d) => { const n = Number(v); return Number.isFinite(n) ? n : d }
|
||
const atOf = (g) => { const n = Number(g && g.at); return Number.isFinite(n) && n > 0 ? n : 0 }
|
||
const ordered = list.map((g, i) => ({ g, i }))
|
||
.sort((a, b) => (numOr(a.g.y, 0) - numOr(b.g.y, 0)) || (numOr(a.g.x, 0) - numOr(b.g.x, 0)) || (a.i - b.i))
|
||
.map((x) => x.g)
|
||
const genRank = new Map(ordered.map((g, i) => [String(g.id), i]))
|
||
const metaCache = new Map()
|
||
const metaFor = (gen) => {
|
||
const k = String(gen && gen.id)
|
||
if (!metaCache.has(k)) {
|
||
let m = []
|
||
try { m = typeof metaOf === 'function' ? metaOf(gen) : [] } catch (e) { m = [] }
|
||
metaCache.set(k, (Array.isArray(m) ? m : []).map((t) => ({ id: String((t && t.id) || ''), title: String((t && t.title) || '') })))
|
||
}
|
||
return metaCache.get(k)
|
||
}
|
||
const groups = [], byKey = new Map()
|
||
let seq = 0
|
||
for (const gen of ordered) {
|
||
const meta = metaFor(gen)
|
||
const rankOf = new Map(meta.map((m, i) => [m.id, i]))
|
||
const titleOf = new Map(meta.map((m) => [m.id, m.title]))
|
||
// key = 任务 + 来源生图节点:同一任务接多个生图节点时各自成组;同一节点同任务多张(变体)并为一组
|
||
for (const en of (Array.isArray(gen.data && gen.data.result) ? gen.data.result : [])) {
|
||
if (!en || typeof en !== 'object') continue
|
||
const pid = String(en.promptId || ('gen_' + gen.id + '_' + (seq++)))
|
||
const key = pid + '@' + gen.id
|
||
let grp = byKey.get(key)
|
||
if (!grp) {
|
||
grp = { genId: gen.id, promptId: pid, taskTitle: String(en.taskTitle || ''), taskTitleNow: titleOf.get(pid) || '', label: String(en.label || '结果'), at: atOf(en), rank: rankOf.has(pid) ? rankOf.get(pid) : 1e9, known: rankOf.has(pid), seq: seq++, entries: [] }
|
||
byKey.set(key, grp)
|
||
groups.push(grp)
|
||
}
|
||
grp.entries.push({ vi: numOr(en.vi, 0), at: atOf(en), en })
|
||
}
|
||
}
|
||
groups.sort((a, b) => (numOr(genRank.get(String(a.genId)), 1e9) - numOr(genRank.get(String(b.genId)), 1e9)) || (a.rank - b.rank) || (a.at - b.at) || (a.seq - b.seq))
|
||
return groups.map((grp) => {
|
||
// 组内:同 vi 只留 at 最新(历史残留的同键条目不该重复出图)→ 按 vi、at 排序 → 展开成显示项
|
||
const keep = new Map()
|
||
for (const e of grp.entries) { const prev = keep.get(e.vi); if (!prev || e.at >= prev.at) keep.set(e.vi, e) }
|
||
const items = []
|
||
for (const e of Array.from(keep.values()).sort((a, b) => (a.vi - b.vi) || (a.at - b.at))) {
|
||
for (const it of (Array.isArray(e.en.items) ? e.en.items : [])) if (it && it.ok && it.url) items.push(it)
|
||
}
|
||
return { genId: grp.genId, promptId: grp.promptId, taskTitle: grp.taskTitle, taskTitleNow: grp.taskTitleNow, label: grp.label, at: grp.at, known: grp.known, items }
|
||
})
|
||
}
|
||
|
||
function renderOutBody(node, props, ctx) {
|
||
const { busy, progress, stop } = ctx
|
||
const nodeMap = new Map((props.nodes || []).map((n) => [n.id, n]))
|
||
const srcGens = (props.edges || [])
|
||
.filter((e) => e.to === node.id)
|
||
.map((e) => nodeMap.get(e.from))
|
||
.filter((n) => isImageProducer(n) && !(n.data && n.data.enabled === false))
|
||
// 顺序以任务卡为准:metaOf 读的正是任务卡渲染用的同一份任务列表(同一个缓存),顺序必然一致
|
||
const merged = outGroupsOf(srcGens, (g) => cachedGenerationTasks(g, props.nodes || [], props.edges || []).map((t) => ({ id: t.id, title: t.title || '' })))
|
||
const allOk = []
|
||
for (const m of merged) for (const r of m.items) allOk.push(r)
|
||
const openPreviewAt = (i) => { const u = allOk[i] && allOk[i].url; if (u) props.onPreview && props.onPreview(u, allOk.map((x) => x.url), i) }
|
||
// 生图节点中的 result 项不一定携带与自身匹配的缩略图;只有明确带 idb 引用时才使用 data,避免多张图共享旧缩略图。
|
||
const thumbOf = (r) => (r && r.idb && r.data) ? r.data : ((r && r.url && outThumbCache.get(r.url)) || (r && r.url))
|
||
let imgIndex = 0
|
||
const outCell = (r, ri) => {
|
||
const cur = imgIndex++
|
||
// key 用「url + 组内序号」而不是下标(2026-11-03):下标作 key 时,条目集合一变(旧图被新图替换)
|
||
// React 会按下标复用同一个 DOM 节点,先显示上一张、再等新图解码 ⇒ 肉眼看到「闪一下旧图/空图」。
|
||
// url 稳定 ⇒ 节点复用(不重建、不重新解码);url 变了才新建,内容永远对得上。
|
||
return el('div', { key: String(r.url || '') + '|' + ri, className: 'iwb-out-cell' },
|
||
el('img', { key: 'out-img-' + cur + '-' + String(r.url || '').slice(-48), className: 'iwb-out-cell-img', decoding: 'async', fetchPriority: 'low', referrerPolicy: 'no-referrer', src: wPreviewUrlOf((typeof wImgSrcForNode === 'function' ? wImgSrcForNode : wDisplayThumbOf)(thumbOf(r), Math.max(120, Math.min(360, (node && node.w ? node.w - 40 : 240))))), draggable: false, style: { aspectRatio: (r.width && r.height) ? String(r.width) + ' / ' + String(r.height) : undefined }, title: r.idb && r.data ? '缩略图 · 点击查看原图' : '点击放大(可左右切换)', onError: (e) => { if (e.currentTarget && e.currentTarget.src !== r.url) e.currentTarget.src = r.url }, onClick: () => openPreviewAt(cur) }),
|
||
el('div', { className: 'iwb-out-cell-meta' }, (r.width || '?') + '×' + (r.height || '?')),
|
||
el('div', { className: 'iwb-out-cell-actions' },
|
||
el('button', { className: 'iwb-btn iwb-btn-sm', title: '插入为参考图节点', onClick: () => props.onCopyRef && props.onCopyRef(r.url), onPointerDown: stop }, I('copy')),
|
||
el('button', {
|
||
className: 'iwb-btn iwb-btn-sm',
|
||
title: '下载',
|
||
// v3.25.18:从资料目录的本地归档取图(原图优先),远端 URL 只作兜底
|
||
onClick: async () => {
|
||
let src = r.url
|
||
try { if (wResolveOutSrc) src = (await wResolveOutSrc(r, true)) || r.url } catch (e) { /* 回退远端 */ }
|
||
downloadUrl(src, 'image.png')
|
||
},
|
||
onPointerDown: stop,
|
||
}, I('download')),
|
||
),
|
||
)
|
||
}
|
||
const groupCards = []
|
||
// 同名组标题加简短编号区分(①②③…)
|
||
const rawTitles = merged.map((m) => {
|
||
// 标题优先级:结果条目里的标题快照 → 任务当前标题(中继/连接链路也能拿到)→ 条目 label
|
||
const ttl = m.taskTitle || m.taskTitleNow
|
||
const cleanLabel = (m.label || '').replace(/\s*·\s*\d+\s*$/, '')
|
||
return ttl || cleanLabel || '结果'
|
||
})
|
||
const titleCount = {}
|
||
for (const t of rawTitles) titleCount[t] = (titleCount[t] || 0) + 1
|
||
const seenCount = {}
|
||
const displayTitles = rawTitles.map((t) => {
|
||
if (titleCount[t] > 1) {
|
||
const n = (seenCount[t] = (seenCount[t] || 0) + 1)
|
||
return n > 1 ? (t + ' ' + ['①', '②', '③', '④', '⑤'][Math.min(n - 1, 4)]) : t
|
||
}
|
||
return t
|
||
})
|
||
for (let gi = 0; gi < merged.length; gi++) {
|
||
const m = merged[gi]
|
||
const title = displayTitles[gi]
|
||
groupCards.push(el('div', { key: 'g_' + gi, className: 'iwb-out-group-card' },
|
||
el('div', { className: 'iwb-out-group-title', title: title }, '▸ 组 ' + (gi + 1) + '/' + merged.length + ' · ' + title),
|
||
el('div', { className: 'iwb-out-grouplist' },
|
||
m.items.map((r, ri) => outCell(r, ri)),
|
||
),
|
||
))
|
||
}
|
||
const busyOut = busy[node.id + '::out']
|
||
const progOut = progress[node.id + '::out']
|
||
const sourceBusy = props.sourceBusy || {}
|
||
const sourceProgress = props.sourceProgress || {}
|
||
const sourceRunKeys = Object.keys(sourceBusy).filter((k) => sourceBusy[k])
|
||
const sourceProgOut = sourceRunKeys.reduce((acc, key) => {
|
||
const p = sourceProgress[key]
|
||
if (!p) return acc
|
||
acc.total += Number(p.total) || 0
|
||
acc.done += Number(p.done) || 0
|
||
acc.groups += Math.max(1, Number(p.groups) || 1)
|
||
acc.waitMs = Math.max(acc.waitMs, Number(p.waitMs) || 0)
|
||
acc.avgMs = Math.max(acc.avgMs, Number(p.avgMs) || 0)
|
||
return acc
|
||
}, { total: 0, done: 0, groups: 0, waitMs: 0, avgMs: 0 })
|
||
const sourceRunning = sourceRunKeys.length > 0 && sourceProgOut.total > 0
|
||
const displayProgOut = busyOut && progOut ? progOut : (sourceRunning ? sourceProgOut : null)
|
||
const outProgress = displayProgOut
|
||
? outProgUI(displayProgOut, props.generationConcurrency)
|
||
: null
|
||
// 旧任务残留提示(2026-11-04):v3.24.41 起旧图不再被新任务清空,于是「任务改过提示词/换过标题/
|
||
// 上游断过」后,输出面板里会同时留下不属于当前任务的组 —— 用户看到「组数与任务数对不上」会误判成丢图。
|
||
// 这些组一律排在最后(见 outGroupsOf 的 rank 兜底),这里只补一行低干扰说明。
|
||
const knownGroups = merged.filter((m) => m.known)
|
||
const staleItems = merged.reduce((n, m) => n + (m.known ? 0 : m.items.length), 0)
|
||
const staleBar = (knownGroups.length && staleItems)
|
||
? el('div', { className: 'iwb-out-stale', title: '这些图生成于任务内容变更之前,仍保留显示(v3.24.41 起旧图不清空);不会与新任务的图混排' }, '另有 ' + staleItems + ' 张来自已变更的任务(排在最后)')
|
||
: null
|
||
const outTotal = srcGens.reduce((n, g) => n + (props.taskCountOf ? props.taskCountOf(g) : 0), 0)
|
||
return el('div', { className: 'iwb-node-body' },
|
||
el('button', {
|
||
className: 'iwb-btn iwb-btn-primary iwb-out-run',
|
||
disabled: !!busyOut || !srcGens.length || outTotal <= 0,
|
||
title: '批量出图:生成各来源生图节点勾选的任务,共 ' + outTotal + ' 张(取消任务卡左侧复选框可跳过,不影响其他生图节点)',
|
||
onClick: () => props.onRunOut && props.onRunOut(node.id),
|
||
onPointerDown: stop,
|
||
}, busyOut ? '⏳ 出图中' : (I('run'), '批量出图' + (srcGens.length ? '(' + outTotal + ' 张)' : ''))),
|
||
outProgress,
|
||
el('div', { className: 'iwb-out-groups' }, groupCards),
|
||
staleBar,
|
||
)
|
||
}
|
||
|
||
|
||
// ── gen ──────────────────────────────────────────────
|
||
function renderGenBody(node, props, ctx) {
|
||
const { onUpdate, busy, progress, stop } = ctx
|
||
const d = node.data
|
||
const busyAll = busy[node.id + '::all']
|
||
const cfg = props.config || { providers: [] }
|
||
const providers = cfg.providers || []
|
||
const curProvider = providers.find((p) => p.id === d.provider) || providers[0] || { id: '', keys: [] }
|
||
const keyGroups = curProvider.keys || []
|
||
// 任务激活判断(勾选=参与「生成全部 / 输出出图」;默认激活)
|
||
const taskActiveOf = (tid) => (d.taskActive && d.taskActive[tid] !== undefined) ? !!d.taskActive[tid] : true
|
||
const variantCountOf = (tid) => Math.max(1, Math.min(10, (d.taskVariants && d.taskVariants[tid]) || d.variants || 1))
|
||
|
||
// 收集任务:每个连接的 Prompt / 文案输出 = 一个任务卡(参考图按画布坐标排序;文案输出回溯 LLM→Prompt 收集参考图)
|
||
const selectedProvider = providers.find((p) => p.id === d.provider) || providers[0]
|
||
const selectedModel = String(d.model || '').trim()
|
||
const modelAvailable = !selectedProvider || !selectedModel || !Array.isArray(selectedProvider.models) || selectedProvider.models.length === 0 || selectedProvider.models.some((m) => m.name === selectedModel && m.visible !== false)
|
||
const tasks = cachedGenerationTasks(node, props.nodes || [], props.edges || []).map((t, i) => ({ ...t, refs: Array.isArray(t.refs) ? t.refs : [], text: String(t.text || ''), label: t.label || ('任务 ' + (i + 1) + (t.title ? ' · ' + t.title : '')), title: t.title || '', diagnostics: t.diagnostics || { cycles: [], disabledSources: [] } }))
|
||
|
||
// 按 promptId 索引结果
|
||
const resultByPrompt = {}
|
||
for (const g of (Array.isArray(d.result) ? d.result : [])) {
|
||
if (g && g.promptId) {
|
||
if (!resultByPrompt[g.promptId]) resultByPrompt[g.promptId] = []
|
||
resultByPrompt[g.promptId].push(g)
|
||
}
|
||
}
|
||
|
||
const bulkVariants = Math.max(1, Math.min(10, Number(d.bulkTaskVariants) || d.variants || 1))
|
||
const setAllTaskActive = (active) => onUpdate(node.id, { taskActive: Object.assign({}, d.taskActive || {}, ...tasks.map((t) => ({ [t.id]: active }))) })
|
||
const setAllTaskVariants = (count) => onUpdate(node.id, { bulkTaskVariants: count, taskVariants: Object.assign({}, d.taskVariants || {}, ...tasks.map((t) => ({ [t.id]: count }))) })
|
||
const activeTaskCount = tasks.filter((t) => taskActiveOf(t.id)).length
|
||
const allTasksActive = tasks.length > 0 && activeTaskCount === tasks.length
|
||
const taskBulkBar = tasks.length ? el('div', { className: 'iwb-task-head iwb-task-bulkbar' },
|
||
el('label', { className: 'iwb-task-check', title: allTasksActive ? '关闭全部任务' : '开启全部任务', onPointerDown: stop },
|
||
el('input', { type: 'checkbox', checked: allTasksActive, onChange: (e) => setAllTaskActive(e.target.checked) })
|
||
),
|
||
el('span', { className: 'iwb-task-bulk-title' }, '批量管理 · 已开启 ' + activeTaskCount + '/' + tasks.length),
|
||
el('span', { className: 'iwb-task-btns' },
|
||
el('span', { className: 'iwb-task-count', title: '统一设置全部任务生成张数' },
|
||
el('select', { className: 'iwb-input iwb-task-count-sel', value: bulkVariants, onChange: (e) => setAllTaskVariants(Number(e.target.value)), onPointerDown: stop }, Array.from({ length: 10 }, (_, i) => i + 1).map((n) => el('option', { key: n, value: n }, n + ' 张')))
|
||
)
|
||
)
|
||
) : null
|
||
// 任务卡
|
||
wDedupeTaskIds(tasks) // 任务 id 唯一自检(任何重复都会在这里被后缀区分并告警)
|
||
const taskEls = []
|
||
for (let ti = 0; ti < tasks.length; ti++) {
|
||
const t = tasks[ti]
|
||
const tKey = node.id + '::' + t.id
|
||
const busyTask = busy[tKey]
|
||
const busyAll = !!busy[node.id + '::all']
|
||
const prog = busyTask ? progress[tKey] : null
|
||
const allProg = busyAll ? progress[node.id + '::all'] : null
|
||
const tResults = resultByPrompt[t.id] || []
|
||
const hasErr = tResults.some((g) => (Array.isArray(g.items) ? g.items : []).some((r) => !r.ok))
|
||
const failOpen = !!(d.failOpen && d.failOpen[t.id])
|
||
const errLines = []
|
||
for (const g of tResults) {
|
||
if (!Array.isArray(g.items)) continue
|
||
for (const r of g.items) {
|
||
if (r.ok) continue
|
||
const ce = classifyErr(r.error)
|
||
errLines.push({ text: (r.error || '生成失败'), cls: ce.cls, tag: ce.tag })
|
||
}
|
||
}
|
||
// 待润色标记:文本节点为空但有 LLM 上游(如组合停用后文本被清空,运行前自动润色)→ 任务保留并标明原因
|
||
const srcPs = (props.nodes || []).find((n) => n.id === t.id)
|
||
// 待润色判定基于文本节点自身内容(LLM 回退文本不算):组合停用后文本被清空 → 标记任务来自润色链
|
||
const pendingPol = !!srcPs && srcPs.type === 'textout' && !((srcPs.data && srcPs.data.text) || '').trim() && (props.edges || []).some((e) => e.to === t.id && (props.nodes || []).some((n) => n.id === e.from && n.type === 'llm'))
|
||
const isActive = taskActiveOf(t.id)
|
||
// 任务级进度/计时:单任务与整批都读该任务自己的 perTask(整批时不再复用汇总进度)。
|
||
// 运行中显示「2/3 · 48s」,结束后显示「3 张 · 1分12s」(结束后读持久化的 taskStats)。
|
||
const ptSource = (busyTask && prog && prog.perTask && prog.perTask[t.id]) || (busyAll && allProg && allProg.perTask && allProg.perTask[t.id]) || null
|
||
const savedStat = (d.taskStats && d.taskStats[t.id]) || null
|
||
const taskTotal = Math.max(1, variantCountOf(t.id))
|
||
const taskStat = ptSource || (savedStat ? { done: savedStat.images || taskTotal, total: taskTotal, state: 'done', wallMs: savedStat.ms || 0, persisted: true } : null)
|
||
// t0 === 0 表示该任务在这批里还没轮到(排队中);state === 'done' 表示该任务在这批里已收尾
|
||
// (手动结束 / 成功 / 失败都算收尾)→ 按钮立刻回到「生成」,不再停留在等待/结束
|
||
const ptFinished = !!(ptSource && ptSource.state === 'done')
|
||
const taskQueued = !!(ptSource && !ptFinished && !ptSource.t0)
|
||
const taskRunning = !!(ptSource && !ptFinished && ptSource.t0)
|
||
const taskBusy = taskRunning || taskQueued
|
||
// 距上一次进展(无进展时从首张开始算)→ 超过阈值才允许「结束」
|
||
const stallMs = taskRunning ? Math.max(0, Date.now() - (ptSource.lastDoneAt || ptSource.t0)) : 0
|
||
const canEndTask = taskRunning && stallMs >= taskStallEndMs(props.config)
|
||
// 本节点正在批量生成但该任务不在这批里 → 不能启动新任务(与 runLockConflicts 一致,避免点了才报错)
|
||
const taskBlocked = !taskBusy && !!busyAll
|
||
// 注:行内进度线已移除(v3.24.42)——单张任务恒为 0→100%,进度无法线性反映真实等待,
|
||
// 「进行中」的感知改由 .iwb-task-running 的呼吸描边承担(见 style.css)。
|
||
const taskTimer = (() => {
|
||
if (!taskStat) return null
|
||
if (taskRunning) {
|
||
const el0 = ptSource && ptSource.t0 ? Date.now() - ptSource.t0 : 0
|
||
return { cls: ' iwb-task-timer-run', text: (taskStat.done || 0) + '/' + taskStat.total + (el0 > 1500 ? ' · ' + fmtDur(el0) : '') }
|
||
}
|
||
const wall = taskStat.wallMs || (taskStat.ms || 0)
|
||
const imgN = taskStat.done || taskStat.total
|
||
return { cls: ' iwb-task-timer-done', text: imgN + ' 张 · ' + fmtDur(wall) }
|
||
})()
|
||
taskEls.push(el('div', { key: t.edgeId || t.id, 'data-prompt-id': t.id, className: 'iwb-task' + (isActive ? '' : ' iwb-task-inactive') + (taskRunning ? ' iwb-task-running' : '') },
|
||
el('div', { className: 'iwb-task-head' },
|
||
el('label', { className: 'iwb-task-check', title: isActive ? '已激活:参与「生成全部 / 输出出图」' : '未激活:不参与「生成全部 / 输出出图」', onPointerDown: stop },
|
||
el('input', {
|
||
type: 'checkbox',
|
||
checked: isActive,
|
||
onChange: (e) => onUpdate(node.id, { taskActive: Object.assign({}, d.taskActive || {}, { [t.id]: e.target.checked }) }),
|
||
}),
|
||
),
|
||
el('span', { className: 'iwb-task-title', title: (t.title ? '标题:' + t.title + ' · ' : '') + t.text },
|
||
(t.label.length > 14 ? t.label.slice(0, 14) + '…' : t.label),
|
||
pendingPol ? el('span', { className: 'iwb-task-refinfo iwb-task-pending', title: '该文本节点当前无内容(如组合节点停用);运行时将先自动润色再生成' }, ' · 待润色') : null,
|
||
t.refs.length ? el('span', { className: 'iwb-task-refinfo', title: t.refs.length + ' 张参考图' }, ' · ' + t.refs.length + ' 张') : null,
|
||
),
|
||
el('span', { className: 'iwb-task-btns' },
|
||
taskTimer ? el('span', { className: 'iwb-task-timer' + taskTimer.cls, title: taskRunning ? '本任务已用时长' : '本任务上次用时' }, taskTimer.text) : null,
|
||
el('span', { className: 'iwb-task-count', title: '本任务生成张数' },
|
||
el('select', {
|
||
className: 'iwb-input iwb-task-count-sel',
|
||
value: (d.taskVariants && d.taskVariants[t.id]) || 1,
|
||
onChange: (e) => onUpdate(node.id, { taskVariants: Object.assign({}, d.taskVariants || {}, { [t.id]: Number(e.target.value) }) }),
|
||
onPointerDown: stop,
|
||
}, Array.from({ length: 10 }, (_, i) => i + 1).map((n) => el('option', { key: n, value: n }, n + ' 张'))),
|
||
),
|
||
// 三态按钮:可生成「生成」→ 已提交「等待」(点它需确认,防误触)→ 超过阈值无新进展「结束」
|
||
(() => {
|
||
if (canEndTask) {
|
||
const mins = Math.max(1, Math.round(stallMs / 60000))
|
||
return el('button', {
|
||
className: 'iwb-btn iwb-btn-sm iwb-btn-danger',
|
||
title: '已 ' + mins + ' 分钟没有新进展:点此提前结束该任务(不影响同批其他任务;服务商可能已生成,是否重试由你决定)',
|
||
onClick: () => props.onCancel && props.onCancel(node.id, t.id),
|
||
onPointerDown: stop,
|
||
}, I('x'), '结束')
|
||
}
|
||
if (taskBusy) {
|
||
return el('button', {
|
||
className: 'iwb-btn iwb-btn-sm iwb-task-btn-wait',
|
||
'aria-busy': 'true',
|
||
title: (taskQueued ? '已排队,等待提交…' : '已提交,正在等待服务商返回(点击可提前结束,需确认)'),
|
||
onClick: async () => {
|
||
if (!props.onCancel) return
|
||
if (!(await askConfirm('该任务仍在等待服务商返回' + (taskQueued ? '(尚未提交)' : '(已 ' + fmtDur(stallMs) + ' 无新进展)') + '。\n\n确定要提前结束这个任务吗?只会停止本任务的等待,不影响同批其他任务;服务商侧可能已生成,是否重试由你决定。', { title: '提前结束任务', okText: '结束' }))) return
|
||
props.onCancel(node.id, t.id)
|
||
},
|
||
onPointerDown: stop,
|
||
}, el('span', { className: 'iwb-task-btn-ring', 'aria-hidden': 'true' }), taskQueued ? '排队' : '等待')
|
||
}
|
||
return el('button', {
|
||
className: 'iwb-btn iwb-btn-sm iwb-btn-primary',
|
||
disabled: taskBlocked || !modelAvailable,
|
||
title: taskBlocked ? '本节点正在批量生成中,请等待或结束后再单独生成' : '生成当前任务',
|
||
onClick: () => props.onRun(node.id, t.id),
|
||
onPointerDown: stop,
|
||
}, I('run'), '生成')
|
||
})(),
|
||
hasErr ? el('button', { className: 'iwb-btn iwb-btn-sm', title: '重试失败任务', onClick: () => props.onRun(node.id, t.id), onPointerDown: stop }, '重试') : null,
|
||
),
|
||
),
|
||
hasErr ? el('button', { className: 'iwb-task-err-toggle' + (failOpen ? ' iwb-task-err-toggle-open' : ''), onClick: () => onUpdate(node.id, { failOpen: Object.assign({}, d.failOpen || {}, { [t.id]: !failOpen }) }), onPointerDown: stop }, failOpen ? '▾ 收起错误' : ('⚠ 查看错误(' + errLines.length + ')')) : null,
|
||
(hasErr && failOpen) ? el('div', { className: 'iwb-task-err' }, errLines.map((e, i) => el('div', { key: i, className: 'iwb-task-errline iwb-err-' + e.cls, title: e.text }, '[' + e.tag + '] ' + e.text))) : null,
|
||
))
|
||
}
|
||
|
||
const ratioPresets = (props.config && props.config.canvas && Array.isArray(props.config.canvas.sizePresets) && props.config.canvas.sizePresets.length) ? props.config.canvas.sizePresets : RATIOS
|
||
// 同上:显示名用 label(可改),value 只作标识(不可改)
|
||
const ratioOpts = ratioPresets.map((r) => el('option', { key: r.value, value: r.value }, presetDisplayName(r)))
|
||
const curRatio = d.ratio || ratioOfSize(d.size) || 'auto'
|
||
const curRes = RES_MAP[d.res] || resOfSize(d.size) || '1K'
|
||
const curRatioAuto = curRatio === 'auto'
|
||
const resOpts = RES_KEYS.map((k) => el('option', { key: k, value: k }, k))
|
||
// 参数单元:无分类标题,仅下拉框(title 悬停提示)
|
||
const cell = (label, control) => el('div', { className: 'iwb-gen-cell', title: label },
|
||
control,
|
||
)
|
||
// 参数设置:横向一行(服务商·分组·模型·比例·清晰度),宽度随内容自适应
|
||
const genParams = el(GenParams, { nodeId: node.id, data: d, config: props.config, onUpdate: (patch) => onUpdate(node.id, patch) })
|
||
return el('div', { className: 'iwb-node-body' },
|
||
genParams,
|
||
!tasks.length ? el('div', { className: 'iwb-err' }, '请连接 提示词节点(或 文本节点,可连多个,每个生成一个任务)') : null,
|
||
taskBulkBar,
|
||
taskEls.length ? el('div', { className: 'iwb-tasks' }, taskEls) : null,
|
||
)
|
||
}
|
||
|
||
// ── LOD 低细节体(v3.24.78)──────────────────────────────
|
||
// 两档语义(判据在 IWBCanvasGeometry.lodModeOf):
|
||
// lite —— 节点屏幕宽 < 64px 但画布缩放 ≥ 15%:画**一张代表图 / 首行文字**。
|
||
// 用户原话「图片简化后无法判断节点内容」:灰块认不出是哪个节点,等于把画布变成一片灰。
|
||
// 这里仍然不建 textarea / 图片网格 / 按钮 / 事件,成本只比纯占位多一个 <img>。
|
||
// plain —— 缩放 < 15%:连图都不画(此时节点屏幕宽普遍 < 30px,缩略图也没有信息量)。
|
||
// 中继节点在判据层就被豁免,不会走到这里。
|
||
const LOD_IMG_TYPES = ['ref', 'gen', 'out', 'layer']
|
||
|
||
// 取「这个节点最能代表内容的一张图」:参考图取自身;生图节点取第一条结果(沿用 renderOutBody 的 thumbOf 优先级)。
|
||
// 输出 / 图层节点要靠连线反推图,成本高且 15% 缩放下已无意义 ⇒ 不取(退化成灰块)。
|
||
function lodThumbOf(node) {
|
||
const d = node.data || {}
|
||
if (node.type === 'ref') {
|
||
const s = wResolveImg(d.data) || d.url
|
||
return s ? wThumbSrc(s) : ''
|
||
}
|
||
if (node.type === 'gen') {
|
||
const groups = Array.isArray(d.result) ? d.result : []
|
||
for (let gi = 0; gi < groups.length; gi++) {
|
||
const items = (groups[gi] && Array.isArray(groups[gi].items)) ? groups[gi].items : []
|
||
for (let ii = 0; ii < items.length; ii++) {
|
||
const r = items[ii]
|
||
if (!r) continue
|
||
const u = (r.idb && r.data) ? r.data : ((r.url && outThumbCache.get(r.url)) || r.url || '')
|
||
if (u) return wThumbSrc(u)
|
||
}
|
||
}
|
||
}
|
||
return ''
|
||
}
|
||
|
||
// 文本类节点第一条非空行(提示词 / LLM 提示词 / 标题)。超过 40 字截断,避免一行撑破窄节点。
|
||
function lodTextOf(node) {
|
||
const d = node.data || {}
|
||
const raw = String(d.text || d.prompt || d.title || '')
|
||
const line = (raw.split(/\r?\n/).map((s) => s.trim()).filter(Boolean)[0]) || ''
|
||
return line.length > 40 ? (line.slice(0, 40) + '…') : line
|
||
}
|
||
|
||
function lodBody(node, mode) {
|
||
const isImg = LOD_IMG_TYPES.indexOf(node.type) >= 0
|
||
if (mode !== 'plain' && isImg) {
|
||
const src = lodThumbOf(node)
|
||
if (src) {
|
||
return el('div', { className: 'iwb-node-body iwb-node-body-lod iwb-lod-lite iwb-lod-img' },
|
||
// 缩略图不参与点击(节点本体负责选中/拖动),所以不挂事件;alt 留空由 CSS 兜底尺寸
|
||
el('img', { className: 'iwb-lod-thumb', src: wDisplayThumbOf(src), decoding: 'async', draggable: false, alt: '' }),
|
||
)
|
||
}
|
||
return el('div', { className: 'iwb-node-body iwb-node-body-lod iwb-lod-lite iwb-lod-img' }, null)
|
||
}
|
||
if (mode !== 'plain') {
|
||
const line = lodTextOf(node)
|
||
return line
|
||
? el('div', { className: 'iwb-node-body iwb-node-body-lod iwb-lod-lite iwb-lod-text iwb-lod-has-text' },
|
||
el('div', { className: 'iwb-lod-line', title: line }, line))
|
||
: el('div', { className: 'iwb-node-body iwb-node-body-lod iwb-lod-lite iwb-lod-text' }, null)
|
||
}
|
||
return el('div', { className: 'iwb-node-body iwb-node-body-lod iwb-lod-plain ' + (isImg ? 'iwb-lod-img' : 'iwb-lod-text') }, null)
|
||
}
|
||
|
||
// md:纯函数(Markdown ⇄ 编辑器 HTML)的测试钩子 —— 行距翻倍的回归由 tests/prompt-md-roundtrip-test.js 守住
|
||
global.IWBNodeBodies = { inject, openPromptExpand, md: { toHtml: mdToHtml, toMd: htmlToMd }, relay: renderRelayBody, prompt: renderPromptBody, plugin: renderPluginBody, textout: renderTextoutBody, combine: renderCombineBody, llm: renderLlmBody, batch: renderBatchBody, ref: renderRefBody, out: renderOutBody, gen: renderGenBody, outGroupsOf, lodBody }
|
||
})(typeof window !== 'undefined' ? window : globalThis)
|