Files
image-workbench-desktop/src/ui-node-card.js
T
qiqi 2cd52d1d4e
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 43s
refactor(promptlib): 收藏入口归插件(宿主不再自带,随插件启停)
按项目所有人要求:提示词库插件负责「管理与收集」的完整能力,宿主只保留基础接口。

宿主侧移除(全部 4 处入口 + 实现):
- 节点气泡星标(app.js 单选气泡的「添加到提示词库」)
- 「选中操作 ▸ 添加到提示词库」、「该节点 ▸ 添加该提示词」
- 提示词节点标题栏星标(src/ui-node-card.js)
- src/runtime-workbench-logic.js 的 addPromptToLibrary(约 45 行)与 ui-canvas-nodes 的 onFavorite 注入

宿主侧保留:promptlib 能力(list/save/insert/copy/notify/onChanged/file*)、prompts 状态与 api('prompts')(备份/迁移)、插件数据通道。

宿主侧补回(此前缺失):右键菜单重新渲染 ctx.commands 注册的插件命令(「插件命令」分区)。

插件 promptlib 1.13.1 → 1.14.0:
- capabilities 增 nodeActions / commands
- nodeActions「收藏为提示词」:仅对 type=prompt 且 text 非空的节点出现(气泡按钮)
- commands「收藏选中的提示词」:右键「插件命令」入口
- 收藏写入插件数据 plugin-data/promptlib.json(以现有数据为基底,保留 cover:{img} 与分组),
  新条目 group:'' 即未分组,并 notify 回执

测试:
- tests/iwb-prompt-collect.spec.js 改为 3 条新契约:插件提供气泡入口 + 宿主无自带入口;
  右键插件命令可用且宿主旧条目已移除;插件停用后两个入口同时消失
- canvas-meta-notice 的旧「点按钮报错回执」用例改为「宿主不得再渲染该入口」
- tests/_helpers/wait.js openDockPanel 加固(等插件宿主初始化,修并行偶发)
- 棘轮下调:app.js 8324 / Workbench 2178

验证:npm run verify:ci 全绿(含 e2e 冒烟 31 条)。
2026-11-27 10:06:03 +08:00

316 lines
18 KiB
JavaScript
Raw Permalink 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 === '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)