587 lines
39 KiB
JavaScript
587 lines
39 KiB
JavaScript
/* ui-canvas-pointer.js —— 画布指针/键盘事件(2026-11-26 从 app.js 收编)
|
||
*
|
||
* 纯搬移:useEffect 内的函数体与 app.js 原「pointer & key handlers」逐字一致,
|
||
* 只把外层自由变量改成 ctx(每次渲染传入)/ inject(模块级常量与纯函数)两路。
|
||
*
|
||
* 依赖清单不是人肉枚举:ctx 与 inject 的名单由 ESLint no-undef 反推(漏项 lint 直接红)。
|
||
* ctx 每次渲染都是新对象,但 hook 只读值、不比较对象身份,与原闭包语义等价。
|
||
*/
|
||
;(function (global) {
|
||
'use strict'
|
||
const React = global.React || {}
|
||
const el = (type, prop, ...children) => React.createElement(type, prop, ...children)
|
||
|
||
let deps = {}
|
||
function inject(d) { Object.assign(deps, d) }
|
||
|
||
function useCanvasPointer(ctx) {
|
||
const { refs, hOf, canvasEl, groupMembersOf, groupElById, sel, selAnchorOf, setTick, setSel, setBoxSel, applyViewportDom, applyGroupBoxVisual, CanvasStore, canConnect, edgeEndpoints, distToSeg, setEdgeHover, connectReason, inPortWorld, setConn, setConnTarget, saveNow, setConnMenu, clearGenResults, setViewport, pushHistory, commitCanvas, settingOpen, drawerOpen, drawerTab, helpOpen, wsMoreOpen, ctxMenu, connMenu, readClipboardGraph, pasteCopiedNodes, pasteGraph, stageClip, copyNodes, selRef, activeWsIdRef, activeWsId, findSpot, setNotice, showToast, setDrawerOpen, conn, setCtxMenu, setWsMoreOpen, setSettingOpen, tool, setTool, setSelEdge, exportCanvas, setHelpOpen, fitSelection, refineSelection, fitView, toggleEnabled, makeGroup, groupOf, ungroup, undo, redo, cutNodes, duplicateNodes, selEdge, deleteEdge, deleteNodes, updateNode, td } = ctx
|
||
const { e2e, createRafBatcher, nodeWidth, computeEdgePath, groupBoxOf, groupPadOf, floatbarPlace, uiZoom, groupPadFromDrag, NODE_W, uid, ConnectMenuMod, ConnectMenu, nodeTypeH, NODE_TYPES, CanvasGeometry, isImageProducer, wPrivateToolsOn, withGroupPad, CanvasOps, wImportImage, HOTKEY_DEFAULTS, hotkeyMatches, IWNodeBodies, wRenameNodeDialog, RuntimeLifecycle } = deps
|
||
React.useEffect(() => {
|
||
// 框选/连线高频更新合并到一帧(rAF 节流),大画布拖拽更流畅
|
||
const rafSet = createRafBatcher()
|
||
const computeBoxIds = (b, cLeft, cTop, vp) => {
|
||
const sx = Math.min(b.x0, b.x1), sy = Math.min(b.y0, b.y1)
|
||
const ex = Math.max(b.x0, b.x1), ey = Math.max(b.y0, b.y1)
|
||
const tw = (cx, cy) => ({ x: (cx - cLeft - vp.x) / vp.scale, y: (cy - cTop - vp.y) / vp.scale })
|
||
const wl = tw(sx, sy), wr = tw(ex, ey)
|
||
const hitIds = refs.nodes.filter((n) => {
|
||
const nw = nodeWidth(n), nh = hOf(n)
|
||
return n.x < wr.x && n.x + nw > wl.x && n.y < wr.y && n.y + nh > wl.y
|
||
}).map((n) => n.id)
|
||
let ids = hitIds
|
||
if (b.mode === 'add') ids = Array.from(new Set((b.baseSel || []).concat(hitIds)))
|
||
if (b.mode === 'toggle') {
|
||
const hit = new Set(hitIds)
|
||
ids = (b.baseSel || []).filter((id) => !hit.has(id)).concat(hitIds.filter((id) => !(b.baseSel || []).includes(id)))
|
||
}
|
||
return { ids, sx: sx - cLeft, sy: sy - cTop, ex: ex - cLeft, ey: ey - cTop }
|
||
}
|
||
// 方案1:拖动中只做轻量 DOM transform,不调用 setNodes / 不重建 O(n) 派生数据(graphCache/nodeMap/visibleIds/边循环),
|
||
// 避免大画布每帧 O(n) 重渲染导致掉帧。就地更新 refs 节点坐标(供 hit 测试 / 连线取最新位置),
|
||
// 并仅对被拖节点及其相连边做 DOM 级更新;drop 时(onUp)才 setNodes 提交 + 保存。
|
||
const dragApplyVisual = (positions) => {
|
||
const el0 = canvasEl.el
|
||
if (!el0) return
|
||
const ids = Object.keys(positions)
|
||
const idSet = new Set(ids)
|
||
for (const id of ids) {
|
||
const pos = positions[id]
|
||
const node = refs.nodeMap && refs.nodeMap.get(id)
|
||
if (node) { node.x = pos.x; node.y = pos.y }
|
||
const nEl = el0.querySelector('[data-node-id="' + id + '"]')
|
||
if (nEl) nEl.style.transform = 'translate(' + pos.x + 'px, ' + pos.y + 'px)'
|
||
}
|
||
const graph = refs.graphCache && refs.graphCache.index
|
||
const pathCache = refs.edgePathCache
|
||
if (!pathCache) return
|
||
for (const ed of refs.edges) {
|
||
if (!idSet.has(ed.from) && !idSet.has(ed.to)) continue
|
||
const d = computeEdgePath(ed, graph, refs.nodeMap, refs.measuredH, pathCache)
|
||
const gEl = el0.querySelector('[data-edge-id="' + ed.id + '"]')
|
||
if (gEl && d) { const ps = gEl.querySelectorAll('path'); for (let i = 0; i < ps.length; i++) ps[i].setAttribute('d', d) }
|
||
}
|
||
// 边线/节点 canvas:拖动中坐标已就地更新,命令式重画一次(不触发 React)。
|
||
try { if (typeof refs.edgeCanvasDraw === 'function') refs.edgeCanvasDraw(refs.viewport.x, refs.viewport.y, refs.viewport.scale) } catch (e) { /* ignore */ }
|
||
try { if (typeof refs.nodeCanvasDraw === 'function') refs.nodeCanvasDraw(refs.viewport.x, refs.viewport.y, refs.viewport.scale) } catch (e) { /* ignore */ }
|
||
// 节点组外框实时跟随:外框由成员包围盒派生,拖动中不重渲染 → 必须就地改 DOM(否则松手才跳)。
|
||
// 用 refs.nodeGroupMap 反查受影响的组,避免每帧 O(groups×members) 扫描。
|
||
if (refs.nodeGroupMap && refs.nodeGroupMap.size) {
|
||
const touchedG = new Set()
|
||
for (const id of ids) { const gid = refs.nodeGroupMap.get(id); if (gid) touchedG.add(gid) }
|
||
for (const gid of touchedG) {
|
||
const g = refs.groups.find((x) => x && x.id === gid)
|
||
if (!g) continue
|
||
const members = groupMembersOf(g)
|
||
if (members.length < 2) continue
|
||
const box = groupBoxOf(members, hOf, groupPadOf(g))
|
||
const elG = groupElById(gid)
|
||
if (elG) {
|
||
elG.style.left = box.x + 'px'; elG.style.top = box.y + 'px'
|
||
elG.style.width = box.w + 'px'; elG.style.height = box.h + 'px'
|
||
}
|
||
}
|
||
}
|
||
// 气泡实时跟随:单选与多选(节点组)都要跟,用与 React 完全一致的 helper 就地改 left/top(O(1),不 setNodes)。
|
||
// 拖动不改 viewport(viewport.x/y 不变),且 refs 节点坐标已就地更新,因此与 React 渲染值始终一致,无偏移。
|
||
{
|
||
const fb = el0.querySelector('.iwb-node-floatbar')
|
||
const anchor = (fb && sel && sel.length) ? selAnchorOf(sel, refs.nodes) : null
|
||
if (anchor) {
|
||
const vp = refs.viewport
|
||
const pl = floatbarPlace(anchor.minY, anchor.maxY, anchor.lift, vp)
|
||
fb.style.left = (vp.x + anchor.cx * vp.scale) + 'px'
|
||
fb.style.top = pl.top + 'px'
|
||
fb.style.setProperty('--iwb-fb-k', String(pl.k))
|
||
fb.classList.toggle('iwb-node-floatbar-below', pl.below)
|
||
}
|
||
}
|
||
}
|
||
const onMove = (e) => {
|
||
const target = e && e.target
|
||
if (!(refs.box || refs.pan || refs.drag || refs.resize || refs.groupResize || refs.connFrom) && target && target.closest && target.closest('.iwb-fullmask, .iwb-lib, .iwb-lib-embedded, .iwb-drawer, .iwb-toolbar, .iwb-rightrail, .iwb-navrail, .iwb-plugin-page, .iwb-statusbar, .iwb-minimap, .iwb-hint-bottom, .iwb-modal-mask, .iwb-ctxmask')) return // 手势进行中(框选/平移/拖节点/连线/缩放)不按 target 断流:否则指针划过库面板,框选卡住、松手收不了尾
|
||
const vp = refs.viewport
|
||
if (!vp) return
|
||
// UI 缩放(zoom)下 pointer 坐标是视觉物理像素;画布坐标是布局像素 → 统一除以 uiZoom 对齐
|
||
const z = uiZoom()
|
||
const mx = e.clientX / z, my = e.clientY / z
|
||
let cRect = null
|
||
if (canvasEl.el) cRect = canvasEl.el.getBoundingClientRect()
|
||
const cLeft = cRect ? cRect.left / z : 0
|
||
const cTop = cRect ? cRect.top / z : 0
|
||
const toWorld = (cx, cy) => ({ x: (cx - cLeft - vp.x) / vp.scale, y: (cy - cTop - vp.y) / vp.scale })
|
||
// 节点组框内/操作栏拖动:同样先记起点,超过阈值才启动(避免"点一下组"就污染撤销历史)
|
||
if (refs.groupDown && !refs.drag) {
|
||
const gd = refs.groupDown
|
||
if (Math.hypot(mx - gd.sx, my - gd.sy) > 4) {
|
||
refs.drag = { start: gd.start, gx: gd.sx, gy: gd.sy }
|
||
setTick((t) => t + 1)
|
||
refs.groupDown = null
|
||
}
|
||
}
|
||
// 节点体拖动:按下时仅记起点,真实移动超过阈值才启动拖动(区分点击与拖拽,避免纯点击污染撤销历史)
|
||
if (refs.bodyDown && !refs.bodyDown.active && !refs.drag) {
|
||
const bd = refs.bodyDown
|
||
if (Math.hypot(mx - bd.sx, my - bd.sy) > 4) {
|
||
bd.active = true
|
||
refs.drag = { start: bd.start, gx: bd.sx, gy: bd.sy }
|
||
// 拖动开始渲染一次,让 dragging/draggingNode 高亮生效;之后帧走 dragApplyVisual(不再 setNodes)
|
||
setTick((t) => t + 1)
|
||
}
|
||
}
|
||
if (refs.box) {
|
||
const b = refs.box
|
||
b.x1 = mx; b.y1 = my
|
||
rafSet(() => {
|
||
if (!refs.box) return // 框选已结束(pointerup 置 null):跳过排队中的 rAF 回调,防止选择框复燃残留
|
||
const r = computeBoxIds(b, cLeft, cTop, vp)
|
||
setSel(r.ids)
|
||
setBoxSel({ x0: r.sx, y0: r.sy, x1: r.ex, y1: r.ey })
|
||
})
|
||
return
|
||
}
|
||
if (refs.pan) {
|
||
const p = refs.pan
|
||
p.mx = mx; p.my = my
|
||
// 只改 DOM;同一帧内多次 pointermove 合并成一次写入(参考 infinite-canvas 的 rAF 合批)。
|
||
rafSet(() => {
|
||
if (!refs.pan) return
|
||
applyViewportDom(p.vx + (p.mx - p.sx), p.vy + (p.my - p.sy), refs.viewport.scale)
|
||
})
|
||
return
|
||
}
|
||
if (refs.groupResize) {
|
||
const gr = refs.groupResize
|
||
gr.dx = (mx - gr.gx) / vp.scale
|
||
gr.dy = (my - gr.gy) / vp.scale
|
||
rafSet(() => {
|
||
if (!refs.groupResize) return
|
||
const rr = refs.groupResize
|
||
if (!Number.isFinite(rr.dx) || !Number.isFinite(rr.dy)) return
|
||
applyGroupBoxVisual(rr.groupId, groupPadFromDrag(rr.base, rr.dir, rr.dx, rr.dy))
|
||
})
|
||
return
|
||
}
|
||
if (refs.resize) {
|
||
const r = refs.resize
|
||
r.mx = mx; r.my = my
|
||
rafSet(() => {
|
||
if (!refs.resize) return
|
||
const rr = refs.resize
|
||
const nw = Math.round(Math.max(180, rr.sw + (rr.mx - rr.gx) / vp.scale))
|
||
const nh = Math.round(Math.max(90, rr.sh + (rr.my - rr.gy) / vp.scale))
|
||
// v3.87.15 缩放流畅度:尺寸按像素取整后**没变就不提交**——亚像素/抖动移动不再触发
|
||
// 整张画布的重渲染与重排(缩放时每帧一次的全量 render 是卡顿主要来源)。
|
||
if (rr.lw === nw && rr.lh === nh) return
|
||
rr.lw = nw; rr.lh = nh
|
||
if (e2e) window.__IWB_E2E_RESIZE_UPDATES__ = (window.__IWB_E2E_RESIZE_UPDATES__ || 0) + 1
|
||
CanvasStore.updateNodes((prev) => prev.map((n) => (n.id === rr.nodeId ? { ...n, w: nw, h: nh } : n)), { persist: false })
|
||
})
|
||
return
|
||
}
|
||
if (refs.drag) {
|
||
const d = refs.drag
|
||
const dx = (mx - d.gx) / vp.scale
|
||
const dy = (my - d.gy) / vp.scale
|
||
d.dx = dx; d.dy = dy
|
||
rafSet(() => {
|
||
if (!refs.drag) return
|
||
const dd = refs.drag
|
||
const positions = {}
|
||
for (const nodeId in dd.start) {
|
||
let nx = Math.round(dd.start[nodeId].x + dd.dx)
|
||
let ny = Math.round(dd.start[nodeId].y + dd.dy)
|
||
positions[nodeId] = { x: nx, y: ny }
|
||
}
|
||
// 方案1:拖动中只做轻量 DOM transform + 就地更新 refs 坐标,不调用 setNodes(避免每帧 O(n) 重渲染);drop 才提交。
|
||
dragApplyVisual(positions)
|
||
})
|
||
if (Object.keys(d.start).length === 1) {
|
||
const bid = Object.keys(d.start)[0]
|
||
const bnode = refs.nodes.find((n) => n.id === bid)
|
||
let hit = null
|
||
if (bnode && (e.altKey || refs.altDown)) {
|
||
// 脱离(Alt):单入单出时可将节点从链中抽出,两端直接相连
|
||
const ins = refs.edges.filter((ed) => ed.to === bid)
|
||
const outs = refs.edges.filter((ed) => ed.from === bid)
|
||
if (ins.length === 1 && outs.length === 1 && canConnect(ins[0].from, outs[0].to)) {
|
||
hit = { mode: 'detach', edgeIds: [ins[0].id, outs[0].id], a: ins[0].from, c: outs[0].to }
|
||
}
|
||
// 插入(节点吸附到连线中点拆分):需按住 Alt 才检测/高亮,防止移动节点时自动吸入;
|
||
// 与脱离并列检测(脱离不满足时仍可插入)
|
||
if (!hit && refs.edges.length) {
|
||
let bnx = Math.round(d.start[bid].x + dx)
|
||
let bny = Math.round(d.start[bid].y + dy)
|
||
const bz = { x: bnx + (bnode.w || NODE_W) / 2, y: bny + hOf(bnode) / 2 }
|
||
for (const ed of refs.edges) {
|
||
if (ed.from === bid || ed.to === bid) continue
|
||
const ep = edgeEndpoints(ed)
|
||
if (!ep) continue
|
||
if (distToSeg(bz, { x: ep.x1, y: ep.y1 }, { x: ep.x2, y: ep.y2 }) < 26 && canConnect(ed.from, bid) && canConnect(bid, ed.to)) {
|
||
hit = { mode: 'insert', edgeId: ed.id, from: ed.from, to: ed.to, x1: ep.x1, y1: ep.y1, x2: ep.x2, y2: ep.y2 }
|
||
break
|
||
}
|
||
}
|
||
}
|
||
}
|
||
refs.edgeHover = hit
|
||
const newKey = hit ? (hit.mode + ':' + (hit.mode === 'detach' ? hit.edgeIds.join(',') : hit.edgeId)) : null
|
||
if (newKey !== (refs.edgeHoverKey || null)) {
|
||
refs.edgeHoverKey = newKey
|
||
setEdgeHover(hit)
|
||
}
|
||
} else if (refs.edgeHover) {
|
||
refs.edgeHover = null
|
||
refs.edgeHoverKey = null
|
||
setEdgeHover(null)
|
||
}
|
||
return
|
||
}
|
||
if (refs.connFrom) {
|
||
const wpt = toWorld(mx, my)
|
||
const wx = wpt.x
|
||
const wy = wpt.y
|
||
// 悬停目标检测:可连接→吸附入口并绿框;不可连接→红框警告;无目标→跟随鼠标
|
||
let target = null
|
||
try {
|
||
const el = /** @type {HTMLElement | null} */ (document.elementFromPoint(e.clientX, e.clientY))
|
||
const nd = el && el.closest ? /** @type {HTMLElement | null} */ (el.closest('.iwb-node')) : null
|
||
if (nd && nd.dataset && nd.dataset.nodeId && nd.dataset.nodeId !== refs.connFrom.nodeId) {
|
||
target = refs.nodes.find((n) => n.id === nd.dataset.nodeId) || null
|
||
}
|
||
} catch (err) { /* ignore */ }
|
||
const fromId = refs.connFrom.nodeId
|
||
rafSet(() => {
|
||
if (!refs.connFrom) return // 连线已结束(pointerup 置 null):跳过排队中的 rAF 回调,防止预览线复燃残留
|
||
if (target) {
|
||
const rev = !!refs.connFrom.reverse
|
||
// 反向拖拽:候选节点是**来源** ⇒ 合法性要按 (target → 我) 判断
|
||
const reason = rev ? connectReason(target.id, fromId) : connectReason(fromId, target.id)
|
||
if (!reason) {
|
||
const port = rev ? { x: target.x + nodeWidth(target), y: target.y + hOf(target) / 2 } : inPortWorld(target)
|
||
setConn({ from: fromId, x: port.x, y: port.y, reverse: rev })
|
||
setConnTarget({ nodeId: target.id, valid: true })
|
||
} else {
|
||
setConn({ from: fromId, x: wx, y: wy, reverse: rev })
|
||
setConnTarget({ nodeId: target.id, valid: false, reason })
|
||
}
|
||
} else {
|
||
setConn({ from: fromId, x: wx, y: wy })
|
||
setConnTarget(null)
|
||
}
|
||
})
|
||
}
|
||
}
|
||
const onUp = (e) => {
|
||
const target = e && e.target
|
||
if (!(refs.box || refs.pan || refs.drag) && target && target.closest && target.closest('.iwb-fullmask')) return // 手势中(框选/平移/拖节点)不拦松手:否则指针落在面板上松手,选择框残留、拖动卡死
|
||
// 节点体纯点击(未超过拖动态阈值):只保持选择,不进入 drag 处理(不污染撤销历史)
|
||
if (refs.bodyDown && !refs.bodyDown.active) { refs.bodyDown = null; }
|
||
// 节点组纯点击(未超过阈值):同上,只保留「框内单击=选中整组」的选择结果
|
||
if (refs.groupDown && !refs.drag) { refs.groupDown = null; }
|
||
if (refs.box) {
|
||
const b = refs.box
|
||
let cRect = null
|
||
if (canvasEl.el) cRect = canvasEl.el.getBoundingClientRect()
|
||
const z = uiZoom()
|
||
const cl = cRect ? cRect.left / z : 0
|
||
const ct = cRect ? cRect.top / z : 0
|
||
const r = computeBoxIds(b, cl, ct, refs.viewport)
|
||
setSel(r.ids)
|
||
// 框选位移:真实拖动位移大(屏蔽随后 600ms 内的 dblclick,避免框选收尾残留误触发画布双击);
|
||
// 位移≈0 视为点击(不屏蔽,双击节点标题栏居中放大仍可用)
|
||
const moved = Math.hypot(b.x1 - b.x0, b.y1 - b.y0)
|
||
refs.lastBoxMove = moved > 8 ? Date.now() : 0
|
||
refs.box = null
|
||
setBoxSel(null)
|
||
return
|
||
}
|
||
if (refs.connFrom && refs.connFrom.reverse) {
|
||
// 反向拖拽(从输入端口起线):落在某个节点上 ⇒ 该节点 → 我这个输入口;落在空白处 ⇒ 弹「为它添加来源」
|
||
const myId = refs.connFrom.nodeId
|
||
const ctR = refs.connTarget
|
||
const srcId = (ctR && ctR.valid) ? ctR.nodeId : null
|
||
refs.connFrom = null
|
||
setConn(null)
|
||
setConnTarget(null)
|
||
if (srcId && srcId !== myId && canConnect(srcId, myId)) {
|
||
const curR = refs.edges
|
||
if (!curR.some((ed) => ed.from === srcId && ed.to === myId)) {
|
||
// 新增入边不清旧结果(与正向拖线一致,2026-11-03)
|
||
const nextR = curR.concat([{ id: uid('e'), from: srcId, to: myId }])
|
||
CanvasStore.updateEdges(nextR, { persist: false })
|
||
refs.edges = nextR
|
||
saveNow({ edges: nextR })
|
||
}
|
||
return
|
||
}
|
||
const pendingIn = (ConnectMenuMod && ConnectMenu) ? ConnectMenuMod.pendingFromDrop({ direction: 'in', nodes: refs.nodes, measuredH: refs.measuredH, viewport: refs.viewport, rect: canvasEl.el ? canvasEl.el.getBoundingClientRect() : null, clientX: e.clientX, clientY: e.clientY, uiZoom: uiZoom(), toId: myId, nodeWidth, nodeTypeH, nodeMap: refs.nodeMap, nodeTypes: NODE_TYPES, connectReasonOf: CanvasGeometry.connectReasonOf, isImageProducer, hiddenTypes: wPrivateToolsOn ? null : ['llm', 'layer'] }) : null
|
||
if (pendingIn) { setConnMenu(pendingIn); return }
|
||
saveNow()
|
||
return
|
||
}
|
||
if (refs.connFrom) {
|
||
const fromId = refs.connFrom.nodeId
|
||
// 自动吸附目标(可连接时)或红框目标(不可连接)
|
||
const ct = refs.connTarget
|
||
let toId = (ct && ct.valid) ? ct.nodeId : null
|
||
if (!toId) {
|
||
let t = e.target
|
||
if (!(t && t.dataset && t.dataset.iwbPort === 'in')) {
|
||
try {
|
||
const hit = /** @type {HTMLElement | null} */ (document.elementFromPoint(e.clientX, e.clientY))
|
||
if (hit && hit.dataset && hit.dataset.iwbPort === 'in') t = hit
|
||
} catch (err) { /* ignore */ }
|
||
}
|
||
if (t && t.dataset && t.dataset.iwbPort === 'in' && t.dataset.iwbNode) toId = t.dataset.iwbNode
|
||
}
|
||
if (toId && toId !== fromId && canConnect(fromId, toId)) {
|
||
const bsrcId = refs.connFrom.batchSrcId || null
|
||
// 与在线版(Web)一致:普通节点同对仅一条边;batch 多输出按来源(batchSrcId)区分,不同来源可连同一目标
|
||
// 立即保存最新边(override 避免 setState 未提交读旧值)
|
||
const curEdges = refs.edges
|
||
if (!curEdges.some((ed) => ed.from === fromId && ed.to === toId && (ed.batchSrcId || null) === bsrcId)) {
|
||
clearGenResults([toId])
|
||
const newEdge = bsrcId ? { id: uid('e'), from: fromId, to: toId, batchSrcId: bsrcId } : { id: uid('e'), from: fromId, to: toId }
|
||
const nextEdges = curEdges.concat([newEdge])
|
||
CanvasStore.updateEdges(nextEdges, { persist: false })
|
||
saveNow({ edges: nextEdges }) // 传入最新边,避免保存旧数据(setState 未提交前 refs 旧值)
|
||
}
|
||
refs.connFrom = null
|
||
setConn(null)
|
||
setConnTarget(null)
|
||
return // 连线成功完成:不进入下方 drag/resize 分支(避免再次用旧数据保存)
|
||
}
|
||
const bsrcPending = refs.connFrom.batchSrcId || null
|
||
refs.connFrom = null
|
||
setConn(null)
|
||
setConnTarget(null)
|
||
// 拖到空白处松手 ⇒ 弹「引用该节点生成」菜单(贴太近的节点不弹,避免打断"连到该节点"的意图)
|
||
const pendingMenu = (ConnectMenuMod && ConnectMenu) ? ConnectMenuMod.pendingFromDrop({ nodes: refs.nodes, measuredH: refs.measuredH, viewport: refs.viewport, rect: canvasEl.el ? canvasEl.el.getBoundingClientRect() : null, clientX: e.clientX, clientY: e.clientY, uiZoom: uiZoom(), fromId, batchSrcId: bsrcPending, nodeWidth, nodeTypeH, nodeMap: refs.nodeMap, nodeTypes: NODE_TYPES, connectReasonOf: CanvasGeometry.connectReasonOf, isImageProducer, hiddenTypes: wPrivateToolsOn ? null : ['llm', 'layer'] }) : null
|
||
if (pendingMenu) { setConnMenu(pendingMenu); return }
|
||
saveNow()
|
||
}
|
||
// 平移末帧提交:必须写在下面 `if (refs.drag || …)` 之外(纯平移不进那个分支),否则松手会回跳一点。
|
||
if (refs.pan && Number.isFinite(refs.pan.mx) && Number.isFinite(refs.pan.my)) {
|
||
const pp = refs.pan
|
||
setViewport((v) => ({ ...v, x: pp.vx + (pp.mx - pp.sx), y: pp.vy + (pp.my - pp.sy) }))
|
||
}
|
||
if (refs.drag || refs.resize || refs.groupResize) {
|
||
let nextNodes = refs.nodes
|
||
let nextEdges = refs.edges
|
||
let nextGroups
|
||
// 节点组外框缩放:把拖动中的额外留白写回组(留白为 0 时清空 pad → 恢复纯自适应)
|
||
if (refs.groupResize) {
|
||
pushHistory()
|
||
const rr = refs.groupResize
|
||
// pointerup 可能早于排队的 rAF:直接用最后一次指针位置重算,避免落点丢失(与节点缩放同一处理)
|
||
const live = (Number.isFinite(rr.dx) && Number.isFinite(rr.dy))
|
||
? groupPadFromDrag(rr.base, rr.dir, rr.dx, rr.dy)
|
||
: ((refs.groupPadLive && refs.groupPadLive[rr.groupId]) || rr.base)
|
||
nextGroups = refs.groups.map((g) => (g.id === rr.groupId ? withGroupPad(g, live) : g))
|
||
refs.groupPadLive = null
|
||
refs.groupResize = null
|
||
}
|
||
if (refs.drag) {
|
||
pushHistory()
|
||
// 拖拽落点:Alt=脱离(单入单出直连两端);普通=插入(节点吸附到边中点)
|
||
const hv = refs.edgeHover
|
||
if (hv) {
|
||
const bid = Object.keys(refs.drag.start)[0]
|
||
const bnode = refs.nodes.find((n) => n.id === bid)
|
||
if (bnode && Object.keys(refs.drag.start).length === 1) {
|
||
if (hv.mode === 'detach' && (e.altKey || refs.altDown)) {
|
||
// 脱离:删除入边+出边,两端直接相连;节点停在拖拽位置
|
||
const inEd = refs.edges.find((ed) => ed.id === hv.edgeIds[0])
|
||
const outEd = refs.edges.find((ed) => ed.id === hv.edgeIds[1])
|
||
if (inEd && outEd && !refs.edges.some((ed) => ed.from === hv.a && ed.to === hv.c)) {
|
||
nextEdges = refs.edges.filter((ed) => ed.id !== hv.edgeIds[0] && ed.id !== hv.edgeIds[1]).concat([{ id: uid('e'), from: hv.a, to: hv.c }])
|
||
nextNodes = nextNodes.map((n) => {
|
||
if (n.id === inEd.to && n.type === 'textout') return { ...n, data: { ...n.data, text: '' } }
|
||
if (n.id === hv.c && isImageProducer(n)) return { ...n, data: { ...n.data, result: null } }
|
||
return n
|
||
})
|
||
}
|
||
} else if (hv.mode === 'insert' && (e.altKey || refs.altDown)) {
|
||
// 插入(按 Alt):节点吸附到线段中点,原边拆成两条
|
||
const bw = bnode.w || NODE_W
|
||
const bh = hOf(bnode)
|
||
const nx = Math.round((hv.x1 + hv.x2) / 2 - bw / 2)
|
||
const ny = Math.round((hv.y1 + hv.y2) / 2 - bh / 2)
|
||
if (!refs.edges.some((ed) => ed.from === hv.from && ed.to === bid) && !refs.edges.some((ed) => ed.from === bid && ed.to === hv.to)) {
|
||
nextNodes = nextNodes.map((n) => {
|
||
if (n.id === bid) return { ...n, x: nx, y: ny }
|
||
if (n.id === hv.to && isImageProducer(n)) return { ...n, data: { ...n.data, result: null } }
|
||
return n
|
||
})
|
||
nextEdges = refs.edges.filter((ed) => ed.id !== hv.edgeId).concat([{ id: uid('e'), from: hv.from, to: bid }, { id: uid('e'), from: bid, to: hv.to }])
|
||
}
|
||
}
|
||
}
|
||
}
|
||
refs.edgeHover = null
|
||
refs.edgeHoverKey = null
|
||
setEdgeHover(null)
|
||
}
|
||
if (refs.resize) pushHistory()
|
||
if (refs.resize && Number.isFinite(refs.resize.mx) && Number.isFinite(refs.resize.my)) {
|
||
const rr = refs.resize
|
||
const nw = Math.max(180, rr.sw + (rr.mx - rr.gx) / refs.viewport.scale)
|
||
const nh = Math.max(90, rr.sh + (rr.my - rr.gy) / refs.viewport.scale)
|
||
nextNodes = nextNodes.map((n) => (n.id === rr.nodeId ? { ...n, w: Math.round(nw), h: Math.round(nh) } : n))
|
||
}
|
||
// pointerup 可能早于排队的 rAF,先提交最后一个拖动位置,避免落点丢失。
|
||
if (refs.drag && Number.isFinite(refs.drag.dx) && Number.isFinite(refs.drag.dy)) {
|
||
const dd = refs.drag
|
||
nextNodes = nextNodes.map((n) => {
|
||
if (!dd.start[n.id]) return n
|
||
let nx = Math.round(dd.start[n.id].x + dd.dx)
|
||
let ny = Math.round(dd.start[n.id].y + dd.dy)
|
||
return { ...n, x: nx, y: ny }
|
||
})
|
||
}
|
||
refs.drag = null
|
||
refs.bodyDown = null
|
||
refs.groupDown = null
|
||
refs.resize = null
|
||
commitCanvas(nextNodes, nextEdges, nextGroups)
|
||
// 拖动结束强制重渲染一次(端口/连线使用最新测量高度,消除滞后窗口)
|
||
requestAnimationFrame(() => setTick((t) => t + 1))
|
||
}
|
||
refs.pan = null
|
||
}
|
||
// 粘贴上下文(v3.24.67):判定在 src/clipboard-kind.js,落地在 src/clipboard-paste.js,
|
||
// 这里只把 Workbench 闭包依赖递过去(每次调用现取,避免陈旧闭包)。
|
||
const pasteCtx = () => ({
|
||
refs, ui: { settingOpen, drawerOpen, helpOpen, wsMoreOpen, ctxMenu, connMenu }, readClipboardGraph, pasteCopiedNodes, pasteGraph,
|
||
// 复制侧(DOM copy 事件)要用:选中集合取实时镜像(渲染闭包的 sel 可能是框选前的空数组)
|
||
stageClip, copyNodes, ids: () => selRef.current, clipboardOf: (list) => CanvasOps.clipboardOf(refs.nodes, refs.edges, refs.groups, list),
|
||
hasTextSelection: (el) => !!((typeof window !== 'undefined' && window.IWBClipboardCopy) ? window.IWBClipboardCopy.hasTextSelection(el) : null),
|
||
markSys: (ok) => { refs.sysClipOk = !!ok },
|
||
wsId: activeWsIdRef.current || activeWsId, activeWsId: () => activeWsIdRef.current || activeWsId, nodes: () => refs.nodes,
|
||
uid, findSpot, nodeW: (ty) => nodeWidth({ type: ty }), nodeH: (ty) => nodeTypeH(ty),
|
||
pushHistory, commitCanvas, setSel, setNotice, showToast, importImage: wImportImage,
|
||
readNativeImage: (typeof window !== 'undefined' && window.IWBDesktop && window.IWBDesktop.clipboardReadImage) ? () => window.IWBDesktop.clipboardReadImage() : null,
|
||
readNativeText: (typeof window !== 'undefined' && window.IWBDesktop && window.IWBDesktop.clipboardReadText) ? () => window.IWBDesktop.clipboardReadText().then((r) => ((r && r.ok) ? r.text : '')).catch(() => '') : null,
|
||
closeLibrary: () => { setDrawerOpen(false) },
|
||
})
|
||
const onKey = (e) => {
|
||
const t = e.target, C = window.IWBClipboardCopy, hasTxt = C && C.hasTextSelection
|
||
if (t && t.tagName && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.tagName === 'SELECT' || t.isContentEditable) && !(C && C.fieldCopyIntent(e, t))) return
|
||
const hotkeys = Object.assign({}, HOTKEY_DEFAULTS, refs.config && refs.config.canvas && refs.config.canvas.hotkeys || {})
|
||
const hit = (id) => hotkeyMatches(e, hotkeys[id])
|
||
// v3.26.109:Esc 不再关闭右侧栏(用户明确要求)——面板连同里面的筛选/选中状态一起没了,
|
||
// 误按代价远大于收益。右栏只用顶栏按钮 / N 键 / 拖拽分隔条控制。
|
||
if (hit('cancel')) {
|
||
if (refs.connFrom || refs.box || refs.drag || refs.resize || refs.groupResize || conn) { refs.drag = null; refs.bodyDown = null; refs.groupDown = null; refs.resize = null; refs.groupResize = null; refs.groupPadLive = null; refs.connFrom = null; refs.box = null; refs.pan = null; refs.edgeHover = null; refs.edgeHoverKey = null; setEdgeHover(null); setConn(null); setConnTarget(null); setBoxSel(null); return }
|
||
if (connMenu) { setConnMenu(null); return }; if (ctxMenu) { setCtxMenu(null); return }; if (wsMoreOpen) { setWsMoreOpen(false); return }; if (settingOpen) { setSettingOpen(false); return }; if (tool === 'pan') { setTool('select'); return }; return
|
||
}
|
||
if (hit('selectAll')) { e.preventDefault(); setSel(refs.nodes.map((n) => n.id)); setSelEdge(null); return }
|
||
if (hit('save')) { e.preventDefault(); saveNow(); return }
|
||
if (hit('exportCanvas')) { e.preventDefault(); exportCanvas(); return }
|
||
if (hit('help')) { e.preventDefault(); setHelpOpen(true); return }
|
||
// n = 右侧栏开合,t = 左侧栏开合(只做开关、不改当前面板;与顶栏两个开关按钮同一条事件通道)
|
||
if (hit('toggleLibrary') || hit('toggleLeftDock')) { e.preventDefault(); try { window.dispatchEvent(new CustomEvent('iwb:dock-toggle', { detail: { side: hit('toggleLibrary') ? 'right' : 'left' } })) } catch (err) { /* ignore */ } return }
|
||
if (hit('fitSelection')) { e.preventDefault(); fitSelection(); return }
|
||
if (hit('refine')) { e.preventDefault(); refineSelection(); return }
|
||
if (hit('fitView')) { e.preventDefault(); fitView(); return }
|
||
if (hit('toggleEnabled')) { e.preventDefault(); toggleEnabled(sel); return }
|
||
if (hit('resetView')) { e.preventDefault(); setViewport({ x: 40, y: 30, scale: 1 }); return }
|
||
// 缩放:与底栏「−/+」共用 refs.zoomByRef(锚画布中心,档位与上下限见 IWBCanvasGeometry.zoomStep)
|
||
if (hit('zoomIn') || hit('zoomOut')) { e.preventDefault(); if (refs.zoomByRef) refs.zoomByRef(hit('zoomOut') ? -1 : 1); return }
|
||
if (hit('pan')) { refs.spaceDown = true; e.preventDefault(); return }
|
||
// 工具切换(H 抓手 / V 选择):与空格互补——空格是「临时按住」,工具是「持续状态」
|
||
if (hit('toolPan')) { e.preventDefault(); refs.pan = null; setTool('pan'); return }
|
||
if (hit('toolSelect')) { e.preventDefault(); refs.pan = null; setTool('select'); return }
|
||
if (hit('detach')) { refs.altDown = true; return }
|
||
if (hit('group')) { e.preventDefault(); makeGroup(); return }
|
||
if (hit('ungroup')) { e.preventDefault(); const g = sel.map((id) => groupOf(id)).find(Boolean); if (g) ungroup(g.id); return }
|
||
if (hit('undo')) { e.preventDefault(); undo(); return }
|
||
if (hit('redo')) { e.preventDefault(); redo(); return }
|
||
// 复制不再在这里做:mac 上 ⌘C 常被原生菜单 Edit>Copy 接管,keydown 到不了 JS(静默失败)。
|
||
// 现在统一由 DOM copy 事件处理(src/clipboard-graph.js 的 bindCopy,同步 clipboardData),
|
||
// 这里只保留"不 preventDefault"——prevent 反而会取消原生复制动作、连 copy 事件都不派发。
|
||
if (hit('copy')) return
|
||
if (hit('cut')) { if (sel.length && !(hasTxt && hasTxt(t)) && cutNodes(sel)) e.preventDefault(); return }
|
||
// Ctrl+Shift+V:永远粘贴内部节点组剪贴板(不受系统剪贴板内容影响)。
|
||
// 必须先于 Ctrl+V 分支判断,让 Ctrl+Shift+V 不被 Ctrl+V 语义吃掉;
|
||
// 同时设一个时间窗,吞掉浏览器为 Ctrl+Shift+V 派发的「纯文本 paste」(Chrome 行为)。
|
||
if (hit('pasteGroup')) { e.preventDefault(); refs.pasteGroupUntil = Date.now() + 800; pasteCopiedNodes(); return }
|
||
if (hit('paste')) {
|
||
// 2026-11-26:⌘V 不再只"探测 + 提示"。桌面端(mac)焦点不在输入框时根本不派发 paste
|
||
// 事件,旧实现只能提示"请按 Ctrl+Shift+V"。现在这里直接**主动粘贴**(指针在画布才接管):
|
||
// 先让原生走(有 paste 事件的平台照旧),150ms 内没等到事件才自己读剪贴板。
|
||
const mod = (typeof window !== 'undefined' && window.IWBClipboardPaste) || null
|
||
if (mod && mod.pasteFromKey) mod.pasteFromKey(pasteCtx())
|
||
return
|
||
}
|
||
if (hit('duplicate')) { e.preventDefault(); duplicateNodes(sel); return }
|
||
if (hit('delete')) { if (selEdge) { deleteEdge(selEdge); return }; if (sel.length) { deleteNodes(sel); return } }
|
||
if (hit('expandEdit')) {
|
||
const en = sel.length === 1 ? refs.nodes.find((x) => x.id === sel[0]) : null
|
||
if (en && en.type === 'prompt' && IWNodeBodies && IWNodeBodies.openPromptExpand) {
|
||
e.preventDefault()
|
||
IWNodeBodies.openPromptExpand({ value: (en.data && en.data.text) || '', onCommit: (v) => updateNode(en.id, { text: v }) })
|
||
return
|
||
}
|
||
}
|
||
if (hit('rename')) { const rn = sel.length === 1 ? refs.nodes.find((x) => x.id === sel[0]) : null; if (rn) { e.preventDefault(); wRenameNodeDialog(rn, td, updateNode) } return } // F2 改名(第 3 入口,与气泡铅笔/右键菜单同一实现);仅单选生效,多选有歧义不猜
|
||
}
|
||
const onBlur = () => { refs.drag = null; refs.bodyDown = null; refs.groupDown = null; refs.resize = null; refs.groupResize = null; refs.groupPadLive = null; refs.connFrom = null; refs.pan = null; refs.box = null; refs.spaceDown = false; refs.edgeHover = null; refs.edgeHoverKey = null; refs.altDown = false; setEdgeHover(null); setConn(null); setConnTarget(null); setBoxSel(null) }
|
||
const lifecycle = RuntimeLifecycle && typeof RuntimeLifecycle.addDisposer === 'function' && typeof window !== 'undefined' && typeof window.IWBRuntimeLifecycleFactory === 'function' ? window.IWBRuntimeLifecycleFactory() : null
|
||
if (lifecycle) {
|
||
lifecycle.addEvent(window, 'pointermove', onMove)
|
||
lifecycle.addEvent(window, 'pointerup', onUp)
|
||
} else {
|
||
window.addEventListener('pointermove', onMove)
|
||
window.addEventListener('pointerup', onUp)
|
||
}
|
||
const onKeyUp = (e) => {
|
||
const hotkeys = Object.assign({}, HOTKEY_DEFAULTS, refs.config && refs.config.canvas && refs.config.canvas.hotkeys || {})
|
||
if (hotkeyMatches(e, hotkeys.pan)) refs.spaceDown = false
|
||
if (hotkeyMatches(e, hotkeys.detach)) refs.altDown = false
|
||
}
|
||
// 统一剪贴板入口(v3.24.67)——判定在 src/clipboard-kind.js,落地在 src/clipboard-paste.js:
|
||
// ① 图片 → 新建参考图节点(**多张全建**,且不再自动下载原图:粘贴 ≠ 另存到下载目录)
|
||
// ② data:image 文本 → 参考图节点;图片链接 → 带网址的参考图节点;纯文本 → 提示词节点
|
||
// ③ 非图片文件(PDF/视频/压缩包)→ 明确提示,不再落进回退分支误贴上一份节点组
|
||
// ④ 系统剪贴板为空 → 什么都不做。节点/节点组只走 Ctrl+Shift+V 与右键菜单
|
||
// (旧的 300ms 回退已删除 —— 它按 token 只让最后一次执行,连按 3 次只贴 1 份)
|
||
// ⑤ 浮层(设置/图库/帮助/放大编辑)打开、焦点在输入框里 —— 都不接管画布粘贴;
|
||
// 输入框里粘图片/文件会给一句说明(文本仍走浏览器原生),浮层里静默放行
|
||
// 替换参考图只保留显式入口(节点头「粘贴图片替换」/ 气泡按钮 / 上传),且必须可撤销。
|
||
const onPaste = (e) => {
|
||
const t = e.target, editable = !!(t && t.tagName && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.tagName === 'SELECT' || t.isContentEditable))
|
||
refs.pasteEventAt = Date.now() // 真收到 paste → 主动粘贴那条定时器不再重复读剪贴板
|
||
const mod = (typeof window !== 'undefined' && window.IWBClipboardPaste) || null
|
||
// pasteStamp 只在**真正被消费**时自增(其它模块靠它判断这次 paste 有没有被处理)。
|
||
if (mod && mod.handle(e, pasteCtx(), editable)) refs.pasteStamp = (refs.pasteStamp || 0) + 1
|
||
}
|
||
window.addEventListener('keydown', onKey)
|
||
window.addEventListener('keyup', onKeyUp)
|
||
// 复制主通道(2026-11-26):DOM copy 事件 + keydown 兜底,见 src/clipboard-graph.js
|
||
const copyMod = (typeof window !== 'undefined' && window.IWBClipboardGraph) || null
|
||
if (copyMod && copyMod.bindCopy) copyMod.bindCopy(pasteCtx)
|
||
window.addEventListener('paste', onPaste)
|
||
window.addEventListener('blur', onBlur)
|
||
return () => {
|
||
rafSet.cancel()
|
||
if (lifecycle) lifecycle.dispose()
|
||
else {
|
||
window.removeEventListener('pointermove', onMove)
|
||
window.removeEventListener('pointerup', onUp)
|
||
}
|
||
window.removeEventListener('keydown', onKey)
|
||
window.removeEventListener('keyup', onKeyUp)
|
||
window.removeEventListener('paste', onPaste)
|
||
window.removeEventListener('blur', onBlur)
|
||
// 复制通道绑在 window 上(不在 lifecycle 里):卸载时必须显式摘掉,否则回到首页后
|
||
// ⌘C 仍会拿已卸载那份 refs 去复制旧画布的选中节点。
|
||
if (copyMod && copyMod.unbindCopy) copyMod.unbindCopy()
|
||
}
|
||
}, [sel, selEdge, settingOpen, drawerOpen, drawerTab, wsMoreOpen, ctxMenu, connMenu, helpOpen])
|
||
}
|
||
|
||
global.IWBCanvasPointer = { inject, useCanvasPointer }
|
||
})(typeof window !== 'undefined' ? window : globalThis)
|