Files
image-workbench-desktop/src/ui-connect-menu.js
T

198 lines
9.1 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.
/* 拖线建节点菜单(2026-10-30)
*
* 交互:从输出端口拖线 → 在画布空白处松手 → 弹出「引用该节点生成」菜单 →
* 点某一项 ⇒ 在松手位置创建该类型节点,并**自动连边**、选中新节点。
*
* 设计要点(已与用户确认):
* 1. 菜单项**不写死清单**:用连接合法性表 connectReasonOf 实时算出「从该源节点能连上的类型」。
* ⇒ 新增节点类型自动出现;规则改了菜单自动跟着变(单一事实来源)。
* 2. 松手点离任何节点太近(< 40 世界像素)时**不弹**菜单 —— 用户本意多半是连到那个节点,
* 差一点就弹菜单会打断操作(参考 infinite-canvas 的 isNearNode 处理)。
* 3. 节点与边由宿主**一次 commitCanvas 提交** ⇒ 撤销是一步。
* 4. 菜单用**屏幕坐标**定位(不跟画布缩放),并做视口边界钳制,避免溢出屏幕。
*
* 约定:**不捕获 app.js 符号**——所有宿主依赖按调用传入(ctx 模式),模块加载期零依赖。
*/
;(function (global) {
'use strict'
const React = global.React
if (!React || !React.createElement) return
const el = React.createElement
// 松手点离节点矩形的距离小于该值(世界像素)就不弹菜单
const NEAR_NODE_TOLERANCE = 40
// 菜单尺寸估算(用于视口边界钳制)
const MENU_W = 208
const MENU_ROW_H = 44
// 点到节点矩形的最小距离(矩形外为真实距离,矩形内为 0)
function distToBox(node, ctx, wx, wy) {
const c = ctx || {}
const w = c.nodeWidth ? c.nodeWidth(node) : 264
const measured = c.measuredH || {}
const h = measured[node.id] || node.h || (c.nodeTypeH ? c.nodeTypeH(node.type) : 220)
const dx = Math.max(node.x - wx, 0, wx - (node.x + w))
const dy = Math.max(node.y - wy, 0, wy - (node.y + h))
return Math.hypot(dx, dy)
}
// 松手点是否贴着某个节点(贴太近就不弹菜单,避免打断"连到该节点"的意图)
function isNearNode(ctx) {
const c = ctx || {}
const nodes = c.nodes || []
const wx = c.wx
const wy = c.wy
const tol = Number.isFinite(c.tolerance) ? c.tolerance : NEAR_NODE_TOLERANCE
if (!Number.isFinite(wx) || !Number.isFinite(wy)) return true
for (const n of nodes) {
if (!n) continue
if (c.excludeId && n.id === c.excludeId) continue
if (distToBox(n, c, wx, wy) < tol) return true
}
return false
}
// 从源节点算出「可新建并连上的类型」——完全由连接合法性表决定,不维护第二份清单
function buildOptions(ctx) {
const c = ctx || {}
const dir = c.direction === 'in' ? 'in' : 'out'
// out:从源节点往右长(候选当目标)|in:从目标节点往左长(候选当来源)
const anchor = dir === 'in' ? c.targetNode : c.sourceNode
const types = c.nodeTypes
if (!anchor || !types || typeof c.connectReasonOf !== 'function') return []
const hidden = Array.isArray(c.hiddenTypes) ? c.hiddenTypes : []
const out = []
for (const entry of types.entries()) {
const type = entry[0]
const spec = entry[1]
if (!spec || spec.hidden) continue
if (hidden.indexOf(type) >= 0) continue // 宿主隐藏的类型(分层/润色默认隐藏,私有开关打开才出现)
// 插件节点需要变体数据(addPluginNode),拖线菜单无法直接构造 ⇒ 不列(仍可从右键菜单/底栏创建)
if (type === 'plugin' || String(type).indexOf('plugin:') === 0) continue
// 虚拟一个落在松手点的目标节点,问合法性表:返回空串 = 可连
const probe = { id: '__iwb_connect_probe__', type, x: 0, y: 0, data: {} }
let reason = ''
try {
reason = dir === 'in'
? (c.connectReasonOf(probe, anchor, false, c.isImageProducer) || '')
: (c.connectReasonOf(anchor, probe, false, c.isImageProducer) || '')
} catch (e) {
reason = '校验失败'
}
if (reason) continue
out.push({
type,
title: spec.title || type,
icon: spec.icon || null,
})
}
return out
}
// 造出「新节点 + 新边」(不写盘、不改状态;由宿主一次提交 ⇒ 一步撤销)
function makeConnected(ctx) {
const c = ctx || {}
if (!c.type || typeof c.uid !== 'function' || typeof c.createNode !== 'function') return null
const node = c.createNode(c.type, { x: Math.round(c.wx), y: Math.round(c.wy) }, c.defaults || {}, c.uid)
if (!node) return null
const edge = c.direction === 'in'
? { id: c.uid('e'), from: node.id, to: c.toId }
: { id: c.uid('e'), from: c.fromId, to: node.id }
if (c.batchSrcId) edge.batchSrcId = c.batchSrcId
return { node, edge }
}
// 拖线松手在空白处 ⇒ 产出"待选菜单"状态(null = 不弹:贴太近某个节点 / 参数不全)
function pendingFromDrop(ctx) {
const c = ctx || {}
const vp = c.viewport
if (!vp || !Number.isFinite(c.clientX) || !Number.isFinite(c.clientY)) return null
const z = Number.isFinite(c.uiZoom) && c.uiZoom > 0 ? c.uiZoom : 1
const rect = c.rect
const wx = (c.clientX / z - (rect ? rect.left / z : 0) - vp.x) / vp.scale
const wy = (c.clientY / z - (rect ? rect.top / z : 0) - vp.y) / vp.scale
const dir = c.direction === 'in' ? 'in' : 'out'
const anchorId = dir === 'in' ? c.toId : c.fromId
if (isNearNode({ nodes: c.nodes, measuredH: c.measuredH, wx, wy, excludeId: anchorId, nodeWidth: c.nodeWidth, nodeTypeH: c.nodeTypeH })) return null
return {
direction: dir,
fromId: c.fromId || null,
toId: c.toId || null,
batchSrcId: c.batchSrcId || null,
wx,
wy,
sx: c.clientX / z,
sy: c.clientY / z,
options: buildOptions({
direction: dir,
sourceNode: (c.nodeMap && c.fromId) ? c.nodeMap.get(c.fromId) : null,
targetNode: (c.nodeMap && c.toId) ? c.nodeMap.get(c.toId) : null,
nodeTypes: c.nodeTypes,
connectReasonOf: c.connectReasonOf,
isImageProducer: c.isImageProducer,
hiddenTypes: c.hiddenTypes,
}),
}
}
// 点菜单某一项 ⇒ 建节点 + 建边 + 选中 + 落盘(一次提交 ⇒ 一步撤销)
function pick(ctx) {
const made = makeConnected(ctx)
if (!made) return false
const nodes = (ctx.nodes || []).concat([made.node])
const edges = (ctx.edges || []).concat([made.edge])
// 撤销快照:本操作发生在任何手势之外,宿主的历史快照不会被自动压栈 ⇒ 必须显式压一次,
// 否则"建节点+建边"无法一步撤销(实测:⌘Z 后节点仍在)。
if (typeof ctx.pushHistory === 'function') ctx.pushHistory()
if (typeof ctx.commitCanvas === 'function') ctx.commitCanvas(nodes, edges)
if (typeof ctx.setSel === 'function') ctx.setSel([made.node.id])
if (typeof ctx.saveNow === 'function') ctx.saveNow({ nodes, edges })
return true
}
function clampToViewport(sx, sy, count) {
const vw = (global.innerWidth || 1200)
const vh = (global.innerHeight || 800)
const h = Math.min(vh - 16, 48 + Math.max(1, count) * MENU_ROW_H)
return {
left: Math.max(8, Math.min(sx, vw - MENU_W - 8)),
top: Math.max(8, Math.min(sy, vh - h - 8)),
}
}
function ConnectMenu(props) {
const p = props || {}
const options = Array.isArray(p.options) ? p.options : []
const pos = clampToViewport(p.sx, p.sy, options.length)
const body = el('div', {
className: 'iwb-ctxmask',
onPointerDown: (e) => { if (e.target === e.currentTarget) p.onClose && p.onClose() },
onContextMenu: (e) => { e.preventDefault(); p.onClose && p.onClose() },
},
el('div', {
className: 'iwb-ctxmenu iwb-connect-menu',
style: { left: pos.left, top: pos.top },
onPointerDown: (e) => e.stopPropagation(),
onContextMenu: (e) => e.stopPropagation(),
onWheel: (e) => e.stopPropagation(),
},
el('div', { className: 'iwb-ctx-title' }, p.direction === 'in' ? '为它添加来源' : '引用该节点生成'),
options.length
? options.map((o) => el('button', {
key: o.type,
className: 'iwb-ctx-item',
'data-type': o.type,
'data-tip': o.title,
onClick: () => p.onPick && p.onPick(o.type),
}, p.renderIcon ? p.renderIcon(o.type) : null, el('span', { className: 'iwb-btn-text' }, o.title)))
: el('div', { className: 'iwb-ctx-item', style: { opacity: 0.6, cursor: 'default' } }, p.direction === 'in' ? '没有可作为来源的节点类型' : '没有可连接的节点类型'),
))
// **不 portal**:必须与现有 ctxMenu 一样渲染在应用树内。
// 原因(2026-10-30 实测):portal 到 body 时会被画布容器的层叠上下文盖住 ——
// 菜单虽然 layout 正确(boundingBox 正常),但 elementFromPoint 命中画布,点击点不到。
return body
}
global.IWBUIConnectMenu = { ConnectMenu, buildOptions, isNearNode, makeConnected, pendingFromDrop, pick, NEAR_NODE_TOLERANCE }
})(typeof window !== 'undefined' ? window : globalThis)