288 lines
17 KiB
JavaScript
288 lines
17 KiB
JavaScript
/* ui-canvas-view.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 ICONS, IDB, computeEdgePath, copyImageToClipboard, downloadUrl, nodeTypeColor, nodeTypeH, nodeWidth, wBlobFromDataUrl, wRegisterBlobUrl
|
||
|
||
function inject (d) {
|
||
if (!d) throw new Error('[iwb][IWBUICanvasView] 依赖未注入')
|
||
ICONS = d.ICONS
|
||
IDB = d.IDB
|
||
computeEdgePath = d.computeEdgePath
|
||
copyImageToClipboard = d.copyImageToClipboard
|
||
downloadUrl = d.downloadUrl
|
||
nodeTypeColor = d.nodeTypeColor
|
||
nodeTypeH = d.nodeTypeH
|
||
nodeWidth = d.nodeWidth
|
||
wBlobFromDataUrl = d.wBlobFromDataUrl
|
||
wRegisterBlobUrl = d.wRegisterBlobUrl
|
||
return true
|
||
}
|
||
|
||
function I(name, cls) {
|
||
return el('svg', { className: 'iwb-ic' + (cls ? ' ' + cls : ''), viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true, dangerouslySetInnerHTML: { __html: ICONS[name] || '' } })
|
||
}
|
||
|
||
function Minimap(props) {
|
||
const { nodes, viewport, canvasSize, measuredH, measuredT, onJump } = props
|
||
const hOf = (n) => (measuredH && measuredH[n.id]) || n.h || nodeTypeH(n.type)
|
||
// v3.26.17:小地图缩小一档(132×88),并整体上移到工具栏之上
|
||
const MW = 132, MH = 88, PAD = 5
|
||
let minX = 0, minY = 0, maxX = 1, maxY = 1
|
||
for (const n of nodes) {
|
||
minX = Math.min(minX, n.x); minY = Math.min(minY, n.y)
|
||
maxX = Math.max(maxX, n.x + nodeWidth(n)); maxY = Math.max(maxY, n.y + (hOf(n)))
|
||
}
|
||
const bw = Math.max(1, maxX - minX), bh = Math.max(1, maxY - minY)
|
||
const s = Math.min((MW - PAD * 2) / bw, (MH - PAD * 2) / bh)
|
||
const ox = PAD + (MW - PAD * 2 - bw * s) / 2 - minX * s
|
||
const oy = PAD + (MH - PAD * 2 - bh * s) / 2 - minY * s
|
||
// 节点点阵仅在 nodes/几何变化时重建;仅视口变化(拖动视图定位)时复用,避免每帧重排全部节点
|
||
const dots = React.useMemo(() => {
|
||
const d = []
|
||
for (const n of nodes) d.push(el('div', {
|
||
key: n.id,
|
||
className: 'iwb-mini-node',
|
||
style: { left: (ox + n.x * s), top: (oy + n.y * s), width: Math.max(3, nodeWidth(n) * s), height: Math.max(3, hOf(n) * s), background: nodeTypeColor(n.type) },
|
||
}, null))
|
||
return d
|
||
}, [nodes, ox, oy, s, measuredT])
|
||
const cw = canvasSize.w || 800, ch = canvasSize.h || 600
|
||
const vx0 = -viewport.x / viewport.scale, vy0 = -viewport.y / viewport.scale
|
||
const vx1 = vx0 + cw / viewport.scale, vy1 = vy0 + ch / viewport.scale
|
||
// rAF 节流:拖动时只保留本帧最后一次位置,避免每个 pointermove 都触发 React 重渲染(跟随主画布平移的同款节流)
|
||
const rafId = React.useRef(null)
|
||
const dragRef = React.useRef(false)
|
||
const pending = React.useRef(null)
|
||
React.useEffect(() => () => { if (rafId.current != null) cancelAnimationFrame(rafId.current) }, [])
|
||
const jumpAt = (e) => {
|
||
const rect = e.currentTarget.getBoundingClientRect()
|
||
const mx = e.clientX - rect.left, my = e.clientY - rect.top
|
||
pending.current = { wx: (mx - ox) / s, wy: (my - oy) / s }
|
||
if (rafId.current != null) return
|
||
rafId.current = requestAnimationFrame(() => {
|
||
rafId.current = null
|
||
const w = pending.current
|
||
if (w) onJump(w.wx, w.wy)
|
||
})
|
||
}
|
||
return el('div', {
|
||
className: 'iwb-minimap', title: '点击/拖动定位',
|
||
onPointerDown: (e) => {
|
||
if (e.button !== 0) return
|
||
try { e.currentTarget.setPointerCapture(e.pointerId) } catch (err) { /* ignore */ }
|
||
dragRef.current = true
|
||
e.preventDefault(); e.stopPropagation()
|
||
jumpAt(e)
|
||
},
|
||
onPointerMove: (e) => { if (dragRef.current) jumpAt(e) },
|
||
onPointerUp: (e) => { dragRef.current = false; try { e.currentTarget.releasePointerCapture(e.pointerId) } catch (err) { /* ignore */ } },
|
||
onPointerCancel: () => { dragRef.current = false },
|
||
onPointerLeave: () => { dragRef.current = false },
|
||
},
|
||
dots,
|
||
el('div', {
|
||
className: 'iwb-mini-view',
|
||
style: { left: (ox + vx0 * s), top: (oy + vy0 * s), width: Math.max(4, (vx1 - vx0) * s), height: Math.max(4, (vy1 - vy0) * s) },
|
||
}, null),
|
||
)
|
||
}
|
||
|
||
function ToolbarBottom(props) {
|
||
const { onAdd, onOpenPrompts, onFitView, onZoom, tool, onTool } = props
|
||
// 工具组(2026-10-31):互斥「选择 / 抓手」。抓手 = 空格+左键的固化版(不用按住空格),
|
||
// 只影响画布空白处的左键拖:选择态=框选,抓手态=平移。节点/组/端口全部照旧(各自 stopPropagation)。
|
||
const toolBtn = (id, icon, tip) => el('button', {
|
||
className: 'iwb-btn' + (tool === id ? ' iwb-btn-on' : ''),
|
||
'data-tip': tip,
|
||
'data-tool': id,
|
||
'aria-pressed': tool === id ? 'true' : 'false',
|
||
onClick: () => onTool(id),
|
||
}, I(icon))
|
||
return el('div', { className: 'iwb-toolbar-wrap' },
|
||
el('div', { className: 'iwb-toolbar iwb-toolbar-bottom' },
|
||
// 最左:模式类工具(与右侧「添加节点」等动作类按钮用分割线隔开)
|
||
el('span', { className: 'iwb-tgroup' },
|
||
toolBtn('select', 'pointer', '选择工具(V):拖动=框选节点'),
|
||
toolBtn('pan', 'hand', '抓手(H):拖动=平移画布'),
|
||
),
|
||
el('span', { className: 'iwb-toolbar-sep' }, null),
|
||
el('span', { className: 'iwb-tgroup' },
|
||
el('button', { className: 'iwb-btn', 'data-tip': '提示词', onClick: () => onAdd('prompt') }, I('file-text')),
|
||
el('button', { className: 'iwb-btn', 'data-tip': '图片', onClick: () => onAdd('ref') }, I('ref')),
|
||
el('button', { className: 'iwb-btn', 'data-tip': '文本', onClick: () => onAdd('textout') }, I('textout')),
|
||
el('button', { className: 'iwb-btn', 'data-tip': '组合', onClick: () => onAdd('combine') }, I('server-plus')),
|
||
el('button', { className: 'iwb-btn', 'data-tip': '连接', onClick: () => onAdd('batch') }, I('batch')),
|
||
el('button', { className: 'iwb-btn', 'data-tip': '中继', onClick: () => onAdd('relay') }, I('circle-dot')),
|
||
el('button', { className: 'iwb-btn', 'data-tip': '配置', onClick: () => onAdd('gen') }, I('gen')),
|
||
el('button', { className: 'iwb-btn', 'data-tip': '输出', onClick: () => onAdd('out') }, I('presentation')),
|
||
),
|
||
// v3.25.82:底栏「资源库」按钮已删(右侧栏/提示词库面板已覆盖该入口,用户裁定)
|
||
// 最右侧独立一格:缩放(−/+)+ 适应视图(显示全部节点)。适应与快捷键 Shift+F 等价。
|
||
el('span', { className: 'iwb-toolbar-sep' }, null),
|
||
el('span', { className: 'iwb-tgroup' },
|
||
// iwb-btn-fit:沿用底栏既有「适应视图」紧凑样式(15px 图标 + 窄内边距),少占横向空间
|
||
// 缩放按钮放「适应」左边:三者都是「视图类」动作,与左边的新建/资源库分开
|
||
el('button', { className: 'iwb-btn iwb-btn-fit', 'data-tip': '缩小', 'aria-label': '缩小画布', onClick: () => onZoom(-1) }, I('zoom-out')),
|
||
el('button', { className: 'iwb-btn iwb-btn-fit', 'data-tip': '放大', 'aria-label': '放大画布', onClick: () => onZoom(1) }, I('zoom-in')),
|
||
el('button', { className: 'iwb-btn iwb-btn-fit', 'data-tip': '适应', onClick: onFitView }, I('maximize')),
|
||
),
|
||
),
|
||
)
|
||
}
|
||
|
||
function EdgePath(props) {
|
||
const { ed, src, dst, graph, nodeMap, measuredH, pathCache, focusNodeId, selEdge, edgeHover, onSelect, onDelete } = props
|
||
const d = React.useMemo(() => computeEdgePath(ed, graph, nodeMap, measuredH, pathCache), [ed, src, dst, graph, nodeMap, measuredH])
|
||
if (!d) return null
|
||
const relation = focusNodeId ? (ed.to === focusNodeId ? ' iwb-edge-upstream' : (ed.from === focusNodeId ? ' iwb-edge-downstream' : '')) : ''
|
||
const cls = 'iwb-edge' + (selEdge === ed.id ? ' iwb-edge-sel' : '') + relation + ((edgeHover && edgeHover.mode === 'insert' && edgeHover.edgeId === ed.id) ? ' iwb-edge-hot' : '') + ((edgeHover && edgeHover.mode === 'detach' && edgeHover.edgeIds.indexOf(ed.id) >= 0) ? ' iwb-edge-detach' : '')
|
||
const hnd = { onPointerDown: (e) => { e.stopPropagation(); onSelect(ed.id) }, onDoubleClick: (e) => { e.stopPropagation(); onDelete(ed.id) } }
|
||
return el('g', { 'data-edge-id': ed.id },
|
||
el('path', { key: ed.id + '_hit', className: 'iwb-edge-hit', d, fill: 'none', ...hnd }),
|
||
el('path', { key: ed.id, className: cls, d, fill: 'none', title: '点击选中(Delete 断开)· 双击直接断开', ...hnd }),
|
||
)
|
||
}
|
||
|
||
function ImagePreview(props) {
|
||
const list = (props.list && props.list.length) ? props.list : (props.src ? [props.src] : [])
|
||
const idx = Math.max(0, Math.min(props.idx || 0, Math.max(0, list.length - 1)))
|
||
const entry = list[idx]
|
||
const urlsRef = useRef(new Map()) // key -> { url, own }
|
||
const orderRef = useRef([]) // 保留顺序(最多 4 张,超出 revoke 最旧)
|
||
// 当前张「原图解析完成」后的 src(objectURL / dataURL / 图床 URL)。复制时优先用它,
|
||
// 避免拿还在等解析的占位缩略图,也避免把「条目引用对象」直接丢给 fetch。
|
||
const resolvedRef = useRef('')
|
||
const releaseKey = (key) => {
|
||
const it = urlsRef.current.get(key)
|
||
if (!it) return
|
||
urlsRef.current.delete(key)
|
||
const i = orderRef.current.indexOf(key)
|
||
if (i >= 0) orderRef.current.splice(i, 1)
|
||
if (it.own) { try { URL.revokeObjectURL(it.url) } catch (e) { /* ignore */ } }
|
||
}
|
||
const releaseAll = () => {
|
||
for (const key of Array.from(urlsRef.current.keys())) releaseKey(key)
|
||
urlsRef.current.clear(); orderRef.current = []
|
||
}
|
||
const entryKeyOf = (e) => 'out:' + (e.origIdb || '') + '|' + (e.idb || '') + '|' + (e.url || '') + '|' + (e.name || '')
|
||
const placeholderOf = (e) => (typeof e === 'string' ? e : ((e && (e.thumb || e.url)) || ''))
|
||
// 解析一张:原图(origIdb)优先 → 缩略图(idb)→ 图床 url;dataURL 转 Blob + objectURL,堆里不留 base64
|
||
const resolveEntry = (e) => {
|
||
if (!e || typeof e === 'string' || !e.__gallery) return Promise.resolve(placeholderOf(e))
|
||
const key = entryKeyOf(e)
|
||
const hit = urlsRef.current.get(key)
|
||
if (hit) return Promise.resolve(hit.url)
|
||
const ph = placeholderOf(e)
|
||
return (e.origIdb ? IDB.get(e.origIdb).catch(() => null) : Promise.resolve(null))
|
||
.then((v) => v || (e.idb ? IDB.get(e.idb).catch(() => null) : null))
|
||
.then(async (b64) => {
|
||
const raw = b64 || e.url || ''
|
||
if (!raw) return ph
|
||
if (String(raw).indexOf('data:') !== 0) return String(raw) // 图床 URL 直接显示
|
||
const blob = await wBlobFromDataUrl(raw)
|
||
if (!blob) return ph
|
||
// 注册 Blob:预览里的「复制」拿到的就是这个 objectURL,
|
||
// 而线上 CSP 禁止 fetch(blob:),必须能从注册表直接取回原 Blob
|
||
const url = wRegisterBlobUrl(blob)
|
||
if (!url) return ph
|
||
urlsRef.current.set(key, { url, own: true })
|
||
orderRef.current.push(key)
|
||
while (orderRef.current.length > 4) releaseKey(orderRef.current[0])
|
||
return url
|
||
})
|
||
.catch(() => ph)
|
||
}
|
||
const [cur, setCur] = useState(() => placeholderOf(entry))
|
||
const entryKeyStr = (typeof entry === 'string') ? ('s:' + entry.length + ':' + entry.slice(0, 32)) : (entry ? entryKeyOf(entry) : '')
|
||
const go = (delta) => { const ni = (idx + delta + list.length) % list.length; props.onNav && props.onNav(ni) }
|
||
// 当前张:先用已有 320px 缩略图/图床 url 占位,原图解析完成后替换
|
||
useEffect(() => {
|
||
let alive = true
|
||
resolvedRef.current = '' // 切张先清空,避免复制到上一张的原图
|
||
setCur(placeholderOf(entry))
|
||
resolveEntry(entry).then((u) => { if (alive && u) { resolvedRef.current = u; setCur(u) } }).catch(() => {})
|
||
return () => { alive = false }
|
||
}, [idx, list.length, entryKeyStr])
|
||
// 预取相邻 ±1(只进缓存,不改变当前显示)
|
||
useEffect(() => {
|
||
if (list.length < 2) return
|
||
const around = [list[(idx + 1) % list.length], list[(idx - 1 + list.length) % list.length]]
|
||
for (const e of around) if (e && typeof e !== 'string') resolveEntry(e).catch(() => {})
|
||
}, [idx, list.length, entryKeyStr])
|
||
// 关闭/卸载:revoke 全部 objectURL 并清空
|
||
useEffect(() => () => releaseAll(), [])
|
||
// 键盘:←/→ 切换预览,Esc 关闭
|
||
useEffect(() => {
|
||
const onKey = (e) => {
|
||
if (e.key === 'ArrowLeft') go(-1)
|
||
else if (e.key === 'ArrowRight') go(1)
|
||
else if (e.key === 'Escape') props.onClose && props.onClose()
|
||
}
|
||
window.addEventListener('keydown', onKey)
|
||
return () => window.removeEventListener('keydown', onKey)
|
||
}, [idx, list.length])
|
||
if (!list.length) return null
|
||
const src = cur || placeholderOf(entry)
|
||
// 复制源:优先「本地已解析源」(原图 objectURL / 缩略图 dataURL),远程 http(s) 只作最后回退,
|
||
// 避免 fetch 远程图床被 CORS 拦下。src 与 <img src> 同源(组件内已解析),不把条目对象丢给 fetch。
|
||
const copySrc = (() => {
|
||
// 候选:原图解析结果 → 当前显示 src → 列表占位缩略图(图床图本地没原图时,缩略图 dataURL 也能复制)
|
||
const cand = [resolvedRef.current, src, placeholderOf(entry)].filter(Boolean)
|
||
const local = cand.find((u) => !/^https?:/i.test(String(u)))
|
||
return local || cand[0] || ''
|
||
})()
|
||
return el('div', { className: 'iwb-imgpreview', onPointerDown: (e) => { if (e.target === e.currentTarget) props.onClose() } },
|
||
list.length > 1 ? el('button', { className: 'iwb-prev-nav iwb-prev-left', title: '上一张(←)', onClick: (e) => { e.stopPropagation(); go(-1) } }, '‹') : null,
|
||
el('img', { src, alt: '预览', onClick: (e) => e.stopPropagation(), onKeyDown: () => {} }),
|
||
list.length > 1 ? el('button', { className: 'iwb-prev-nav iwb-prev-right', title: '下一张(→)', onClick: (e) => { e.stopPropagation(); go(1) } }, '›') : null,
|
||
el('div', { className: 'iwb-prev-bar', onClick: (e) => e.stopPropagation() },
|
||
el('span', { className: 'iwb-prev-count' }, (idx + 1) + ' / ' + list.length),
|
||
el('button', {
|
||
className: 'iwb-btn iwb-btn-sm',
|
||
title: '复制当前图片到剪贴板(统一转为 PNG)',
|
||
onClick: async () => {
|
||
try {
|
||
// 与图库条目复制共用同一个实现(app.js 的 copyImageToClipboard),不再各写一份。
|
||
// v3.24.65:先等一次原图解析(resolveEntry 命中缓存时是同步返回)—— 否则刚点开就复制,
|
||
// 拿到的是 320px 占位缩略图;SVG 也只有在原图解析后才注册成 Blob 供光栅化。
|
||
const resolved = await resolveEntry(entry).catch(() => '')
|
||
await copyImageToClipboard(resolved || copySrc)
|
||
props.onFlash && props.onFlash('已复制图片到剪贴板(PNG),可在画布空白处粘贴为参考图节点')
|
||
} catch (e) { props.onFlash && props.onFlash('复制失败:' + String((e && e.message) || e)) }
|
||
},
|
||
}, I('copy'), ' 复制'),
|
||
el('button', {
|
||
className: 'iwb-btn iwb-btn-sm',
|
||
title: '下载当前图片',
|
||
onClick: async () => {
|
||
// 同上:原图优先,占位缩略图只作最后兜底(此前 SVG 的原图在这里被下成 320px jpeg)
|
||
const resolved = await resolveEntry(entry).catch(() => '')
|
||
downloadUrl(resolved || src, 'image.png')
|
||
},
|
||
}, I('download'), ' 下载'),
|
||
),
|
||
)
|
||
}
|
||
|
||
global.IWBUICanvasView = { inject, I, Minimap, ToolbarBottom, EdgePath, ImagePreview }
|
||
})(typeof window !== 'undefined' ? window : globalThis)
|