Files
image-workbench-desktop/src/ui-node-card.js
T
qiqi 9225a76895
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 33s
fix(combine): 继承态提示词把上游文案与参考图交给组合/连接节点
组合节点的拼接逻辑不变。断点在「来源判定」: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 用例(组合行出现并跟随上游)
2026-11-23 11:22:43 +08:00

323 lines
19 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.
/* ui-node-card.js —— 自 app.js 收编(结构优化,2026-10-28)
*
* 无状态 UI 组件:数据与回调经 props 传入;React / el / hooks 从 global 解析。
* 宿主(app.js)通过 inject() 一次性注入应用层助手。
*
* ⚠️ 为什么 inject 而不是 props 注入依赖:
* 这些依赖在 app.js 里都是 const 单次赋值 / 函数声明,运行期不变 ⇒ 加载时注入没有"快照失效"问题。
* 好处是组件函数体可以**逐字不动**地搬过来,等价性由 scripts/verify-move.js 证明。
*
* ⚠️ 依赖清单是用 ESLint 的 no-undef 反推出来的(不是人肉枚举),漏项会被 CI 直接抓到。
*/
;(function (global) {
'use strict'
const React = global.React || {}
const el = (type, prop, ...children) => React.createElement(type, prop, ...children)
const useState = React.useState
const useEffect = React.useEffect
const useRef = React.useRef
const useMemo = React.useMemo
const useCallback = React.useCallback
const useLayoutEffect = React.useLayoutEffect
let I, NODE_H, W_NODECARD_PASTE_ONCE, batchPortTop, isBatchSrc, isImageProducer, nodeTypeColor, nodeTypeH, nodeTypeHasPort, nodeTypeIcon, nodeTypeTitle, nodeWidth, renderBody, wImportImage, wResolveImgAsync
function inject (d) {
if (!d) throw new Error('[iwb][IWBUINodeCard] 依赖未注入')
I = d.I
NODE_H = d.NODE_H
W_NODECARD_PASTE_ONCE = d.W_NODECARD_PASTE_ONCE
batchPortTop = d.batchPortTop
isBatchSrc = d.isBatchSrc
isImageProducer = d.isImageProducer
nodeTypeColor = d.nodeTypeColor
nodeTypeH = d.nodeTypeH
nodeTypeHasPort = d.nodeTypeHasPort
nodeTypeIcon = d.nodeTypeIcon
nodeTypeTitle = d.nodeTypeTitle
nodeWidth = d.nodeWidth
renderBody = d.renderBody
wImportImage = d.wImportImage
wResolveImgAsync = d.wResolveImgAsync
return true
}
// 背景色令牌(颜色值由 style.css 按主题映射;data.bg 存令牌,不是 hex)
const BG_TOKEN_RE = /^(white|cyan|purple|pink|orange|yellow|green)$/
// 第一版把 hex 直接写进 data.bg;这里做**渲染期自动迁移**(不改用户数据):
// 认识的旧 hex → 新令牌(跟随主题换色),不认识的才走内联回退(保持原色,不丢)。
const BG_LEGACY_HEX = {
'#ffffff': 'white', '#cfeff2': 'cyan', '#d5d6fb': 'purple', '#fbd0e0': 'pink',
'#ffdcb5': 'orange', '#ffe9a3': 'yellow', '#d3f0cf': 'green',
}
const bgTokenOf = (node) => {
const v = String((node && node.data && node.data.bg) || '').toLowerCase()
return BG_TOKEN_RE.test(v) ? v : (BG_LEGACY_HEX[v] || '')
}
const bgHexOf = (node) => {
const v = String((node && node.data && node.data.bg) || '')
return v && !bgTokenOf(node) ? v : ''
}
function NodeCard(props) {
const node = props.node
const w = nodeWidth(node)
const h = props.measuredH || node.h || nodeTypeH(node.type)
const color = nodeTypeColor(node.type)
const sel = props.selected
const [elRef] = useState(() => ({ el: null }))
const [editingTitle, setEditingTitle] = useState(false)
const [titleDraft, setTitleDraft] = useState('')
const [editingBody, setEditingBody] = useState(false)
const bodyFreezeRef = React.useRef(null) // v3.87.16:缩放期间冻结节点体用
// 从剪贴板粘贴图片替换(按钮方式:navigator.clipboard.read)
const pasteFromClipboard = () => {
const applyBlob = (blob) => {
if (!blob) return
const rd = new FileReader()
rd.onload = () => wImportImage(rd.result, { onError: (msg) => props.onNotice && props.onNotice(msg) }, (r) => {
if (!r || !r.ok || !r.data) { props.onNotice && props.onNotice((r && r.text) || '粘贴图片处理失败,未修改原参考图'); return }
props.onSnapshot && props.onSnapshot() // 替换是可撤销的显式操作:先压快照再改图
props.onUpdate && props.onUpdate(node.id, { data: r.data, name: 'clipboard.png', localName: null, url: '' })
props.onNotice && props.onNotice('图片已粘贴,正在保存…')
})
rd.onerror = () => props.onNotice && props.onNotice('读取剪贴板图片失败,未修改原参考图')
try { rd.readAsDataURL(blob) } catch (e) { props.onNotice && props.onNotice('读取剪贴板图片失败,未修改原参考图') }
}
// v3.24.67:待命监听「用上即摘除」,且与气泡按钮共用同一槽位(src/clipboard-paste-once.js)。
// 旧实现里 clipboard.read() 成功后从不摘除监听 → 之后任意粘贴都会把这张参考图再替换一次。
const PO = (typeof window !== 'undefined' && window.IWBPasteOnce) ? window.IWBPasteOnce : null
const once = PO ? PO.arm((files) => applyBlob(files && files[0])) : null
try {
if (navigator.clipboard && navigator.clipboard.read) {
navigator.clipboard.read().then((items) => {
for (const it of (items || [])) {
const t = (it.types || []).find((x) => String(x).indexOf('image/') === 0)
if (t) { it.getType(t).then((b) => { if (once) once.disarm(); applyBlob(b) }).catch(() => {}) ; return }
}
}).catch(() => {})
}
} catch (err) { /* fallback to the armed paste listener above */ }
}
// 节点高度测量:挂载后立即同步测量一次(保证端口/连线用实际高度而非默认 NODE_H),
// 即使 ResizeObserver 不可用也有初始测量值;RO 可用时持续跟随高度变化
useEffect(() => {
const el0 = elRef.el
if (!el0) return
let rafId = null
let lastHeight = 0
const commitHeight = (height) => {
const next = Math.round(Number(height) || 0)
if (!next || Math.abs(next - lastHeight) < 2) return
lastHeight = next
props.onMeasure && props.onMeasure(node.id, next)
}
commitHeight(el0.offsetHeight)
if (typeof ResizeObserver === 'undefined') return
const ro = new ResizeObserver((entries) => {
const entry = entries && entries[0]
const next = entry && entry.borderBoxSize && entry.borderBoxSize[0]
? entry.borderBoxSize[0].blockSize
: (entry && entry.contentRect ? entry.contentRect.height : el0.offsetHeight)
if (rafId != null) cancelAnimationFrame(rafId)
rafId = requestAnimationFrame(() => { rafId = null; commitHeight(next) })
})
ro.observe(el0)
return () => { ro.disconnect(); if (rafId != null) cancelAnimationFrame(rafId) }
}, [])
// 标题带(节点外框上方左侧):中继节点不显示。
// 仍复用 .iwb-node-title / .iwb-node-title-input,DOM 结构与类名不变,既有测试契约保持。
const head = node.type === 'relay' ? null : el('div', {
className: 'iwb-node-head',
onPointerDown: (e) => { if (e.button !== 0) return; e.stopPropagation(); props.onHeaderDown(e, node.id) },
onDoubleClick: (e) => { e.stopPropagation(); props.onZoomTo && props.onZoomTo(node.id) },
},
nodeTypeIcon(node.type) ? el('span', { className: 'iwb-node-headicon' }, I(nodeTypeIcon(node.type))) : null,
editingTitle ? el('input', {
className: 'iwb-input iwb-node-title-input',
value: titleDraft,
autoFocus: true,
placeholder: '节点标题',
onFocus: (e) => e.target.select(),
onPointerDown: (e) => e.stopPropagation(),
onClick: (e) => e.stopPropagation(),
onChange: (e) => setTitleDraft(e.target.value),
onKeyDown: (e) => {
if (e.key === 'Enter') { props.onUpdate && props.onUpdate(node.id, { title: titleDraft.trim() }); setEditingTitle(false) }
if (e.key === 'Escape') setEditingTitle(false)
},
onBlur: () => { if (editingTitle) { props.onUpdate && props.onUpdate(node.id, { title: titleDraft.trim() }); setEditingTitle(false) } },
}, null) : el('span', {
className: 'iwb-node-title',
title: '双击修改节点标题(批量出图时用于区分任务)',
onDoubleClick: (e) => { e.stopPropagation(); setTitleDraft((node.data && node.data.title && String(node.data.title).trim()) ? node.data.title : (nodeTypeTitle(node.type))); setEditingTitle(true) },
}, (node.data && node.data.title && String(node.data.title).trim()) ? node.data.title : (nodeTypeTitle(node.type))),
el('span', { className: 'iwb-node-headbtns' },
node.type === 'prompt' ? el('button', {
className: 'iwb-node-del',
title: '添加到提示词库',
'data-tip': '收藏',
onPointerDown: (e) => e.stopPropagation(),
onClick: () => props.onFavorite && props.onFavorite(node.id),
}, I('star')) : null,
node.type === 'ref' ? el('label', {
className: 'iwb-node-del',
title: '替换图片',
'data-tip': '替换',
onPointerDown: (e) => e.stopPropagation(),
}, I('upload'),
el('input', { type: 'file', accept: 'image/*', style: { display: 'none' }, 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) => props.onNotice && props.onNotice(msg) }, (r) => {
if (!r || !r.ok || !r.data) { props.onNotice && props.onNotice((r && r.text) || '上传图片处理失败,未修改原参考图'); return }
if (props.onUpdate) props.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),
) : null,
node.type === 'ref' ? el('button', { className: 'iwb-node-del', 'aria-label': '粘贴', 'data-tip': '粘贴', onPointerDown: (e) => e.stopPropagation(), onClick: () => pasteFromClipboard() }, I('paste')) : null,
el('button', {
className: 'iwb-node-del',
title: '复制节点(Ctrl/Cmd+D)',
'data-tip': '复制',
onPointerDown: (e) => e.stopPropagation(),
onClick: () => props.onDuplicate(node.id),
}, I('copy')),
el('button', {
className: 'iwb-node-del',
title: '删除节点',
'data-tip': '删除',
onPointerDown: (e) => e.stopPropagation(),
onClick: () => props.onDelete(node.id),
}, I('x')),
),
)
// v3.87.16 缩放流畅度:**缩放期间冻结节点体元素**(几何照常更新)。
// 实测:一次 60 步缩放在有图节点上触发 180 次节点体渲染(每帧约 3 次),每帧重建结果网格
// (每张图都要重新创建元素 + diff 属性)就是"有图片的画布缩放非常卡"的主因。
// 复用同一个 React 元素 → React 直接跳过该子树的重渲染;松手(sizing=false)立刻解冻重渲染。
const freeze = props.sizing && bodyFreezeRef.current ? bodyFreezeRef.current : null
// LOD('' / 'lite' / 'plain')的分派在 renderBody 内部(v3.24.78):那边先做完节点体模块的依赖注入,
// 再决定画轻量体还是完整体。放在这里会踩「注入还没发生 ⇒ lodBody 里 el 未定义 ⇒ 退回灰块」的坑。
const body = freeze || renderBody(node, Object.assign({}, props, { editingBody, setEditingBody }))
if (props.sizing) bodyFreezeRef.current = body
else bodyFreezeRef.current = null
const hasIn = isImageProducer(node) || node.type === 'relay' || node.type === 'out' || node.type === 'prompt' || node.type === 'llm' || node.type === 'textout' || node.type === 'combine' || node.type === 'batch' || nodeTypeHasPort(node, 'in')
const hasOut = node.type === 'prompt' || node.type === 'relay' || node.type === 'ref' || isImageProducer(node) || node.type === 'llm' || node.type === 'textout' || node.type === 'combine' || node.type === 'batch' || nodeTypeHasPort(node, 'out')
const ports = []
if (hasIn) {
if (node.type === 'batch') {
// 连接节点:每个输入来源一个输入端口(与输出端口同排,成对出现);无来源时默认 1 对占位端口
const bsrcs = props.batchSources || []
const list = bsrcs.length ? bsrcs : [null]
const n = list.length
list.forEach((bs, bi) => {
ports.push(el('div', {
key: 'bi_' + (bs ? bs.id : 'default'),
className: 'iwb-port iwb-port-in iwb-port-batch-in' + ((bs && (props.edges || []).some((e) => e.to === node.id && e.from === bs.id)) ? ' iwb-port-linked' : ''),
style: { top: batchPortTop(bi, n, h) },
title: '输入:' + (bs ? (((bs.data && bs.data.title) || '').trim() || ('来源 ' + (bi + 1))) : '来源 1'),
'data-iwb-port': 'in',
'data-iwb-node': node.id,
onPointerDown: (e) => { e.stopPropagation(); props.onInPortDown(node.id) },
}, null))
})
} else {
ports.push(el('div', {
key: 'in',
className: 'iwb-port iwb-port-in' + ((props.edges || []).some((e) => e.to === node.id) ? ' iwb-port-linked' : ''),
style: { top: node.type === 'prompt' ? Math.max(46, h * 0.3) : h / 2 },
'data-iwb-port': 'in',
'data-iwb-node': node.id,
onPointerDown: (e) => { e.stopPropagation(); props.onInPortDown(node.id) },
}, null))
}
}
if (hasOut) {
if (node.type === 'batch') {
// 连接节点:每个输入来源一个输出端口(按来源行均匀分布);无来源时默认 1 对占位端口
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 list = bsrcs.length ? bsrcs : [null]
const n = list.length
list.forEach((bs, bi) => {
ports.push(el('div', {
key: 'bo_' + (bs ? bs.id : 'default'),
className: 'iwb-port iwb-port-out iwb-port-batch' + ((props.edges || []).some((e) => e.from === node.id && (e.batchSrcId || null) === (bs ? bs.id : null)) ? ' iwb-port-linked' : ''),
style: { top: batchPortTop(bi, n, h) },
title: '输出:' + (bs ? (((bs.data && bs.data.title) || '').trim() || ('来源 ' + (bi + 1))) : '来源 1'),
'data-iwb-batch-src': bs ? bs.id : '',
onPointerDown: (e) => { e.stopPropagation(); props.onOutPortDown(node.id, bs ? bs.id : undefined) },
}, null))
})
} else {
ports.push(el('div', {
key: 'out',
className: 'iwb-port iwb-port-out' + ((props.edges || []).some((e) => e.from === node.id) ? ' iwb-port-linked' : ''),
style: { top: h / 2 },
onPointerDown: (e) => { e.stopPropagation(); props.onOutPortDown(node.id) },
}, null))
}
}
const connInfo = (props.connTarget && props.connTarget.nodeId === node.id) ? props.connTarget : null
const connCls = connInfo ? (connInfo.valid ? ' iwb-conn-ok' : ' iwb-conn-bad') : ''
return el('div', {
className: 'iwb-node' + ((node.data && node.data.bg) ? ' iwb-node-bg-custom' : '') + (sel ? ' iwb-node-selected' : '')
+ (props.draggingNode ? ' iwb-node-dragging' : '') + (node.h ? ' iwb-node-fixed' : '') + (node.type === 'relay' ? ' iwb-node-relay' : '') + connCls + (node.data && node.data.enabled === false ? ' iwb-node-disabled' : ''),
'data-bg': (bgTokenOf(node) || undefined),
'data-node-id': node.id,
title: connInfo && !connInfo.valid ? connInfo.reason : undefined,
style: { transform: 'translate(' + node.x + 'px, ' + node.y + 'px)', width: w, background: (bgHexOf(node) || undefined), '--iwb-node-color': (bgHexOf(node) || undefined), minHeight: (node.type === 'gen' && node.data && node.data.collapsed) ? 56 : (node.h || (node.type === 'out' ? NODE_H.out : 56)), height: 'auto', borderTopColor: 'color-mix(in srgb, ' + color + ' 70%, transparent)', left: 0, top: 0 },
ref: (el0) => { elRef.el = el0 },
onPointerDown: (e) => {
if (e.button !== 0) return
e.stopPropagation()
// 整节节点都可点选+拖动(对齐参考项目:不只标题)。点在可交互控件上时仅选中。
const t0 = e.target
const interactive = t0 && t0.closest && t0.closest('input, select, button, .iwb-port, .iwb-resize, .iwb-ref-url-input, .iwb-ref-url-submit, .iwb-task-count-sel, .iwb-node-title-input')
if (interactive) { props.onSelect(node.id); return }
props.onSelect(node.id)
props.onBodyDown(e, node.id)
},
onDoubleClick: (e) => {
// 双击节点体:图片节点打开预览,文字(prompt/文本)节点聚焦内容编辑;不拦截标题双击(缩放归 onZoomTo)
const t0 = e.target
if (t0 && t0.closest && t0.closest('input, select, button, .iwb-node-head, .iwb-port, .iwb-resize')) return
if (node.type === 'ref' || node.type === 'out') {
// 2026-10-20 修:图片节点双击打不开(刷新后)。
// 根因:node.data.url 在刷新后是**引用对象**({__blob}/{__cache}),
// 而预览组件 ImagePreview 的 placeholderOf() 对对象只认 .thumb/.url ⇒ 拿到 '' ⇒ <img src="">。
// ⇒ 这里用 wResolveImgAsync:**等引用解析成 objectURL** 再开预览。
// (解析失败/无内容时不打开预览,不给用户一个坏掉的空窗。)
const raw = (node.data && node.data.url) || (node.data && node.data.data)
wResolveImgAsync(raw).then((src) => {
if (!src) return
e.stopPropagation()
props.onPreview && props.onPreview(src)
}).catch(() => { /* ignore */ })
return
}
if (node.type === 'prompt' || node.type === 'textout' || node.type === 'llm' || node.type === 'combine' || node.type === 'batch') {
e.stopPropagation()
// 双击文字节点进入内容编辑:解除只读并聚焦
setEditingBody(true)
const ta = elRef.el && elRef.el.querySelector('.iwb-textarea')
if (ta) { ta.readOnly = false; ta.focus() }
}
},
}, head, body, ports,
connInfo && !connInfo.valid ? el('div', { className: 'iwb-conn-hint' }, '⚠ ' + (connInfo.reason || '无法连接')) : null,
el('div', {
className: 'iwb-resize',
onPointerDown: (e) => { e.stopPropagation(); props.onResizeStart(node.id, e) },
}, null),
)
}
global.IWBUINodeCard = { inject, NodeCard }
})(typeof window !== 'undefined' ? window : globalThis)