Files
image-workbench-desktop/src/canvas-geometry.js
T
2026-12-01 10:13:08 +08:00

452 lines
31 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.
/* 连线几何与合法性(自 app.js Workbench() 收编,P2-9)
*
* 纯函数:
* - connectReasonOf(src, dst, hasEdge, isImageProducer):连线合法性决策表,返回空串表示允许,否则返回可读原因。
* - distToSeg(p, a, b):点到线段距离(连线插入吸附检测)。
*
* 需要注入依赖的一组(P1 拆分批 3,2026-10-28 自 app.js 收编):
* - computeEdgePath(ed, graph, nodeMap, measuredH, pathCache):连线三次贝塞尔路径 d 属性(含 batch 端口定位 + 路径缓存)
* - areNodeEqual(prev, next):NodeCard 的 React.memo 比较器(拖拽/缩放/缩放窗口内放宽数组引用比较)
*
* 依赖注入:create({ nodeTypeH, nodeWidth, isBatchSrc, batchPortTop })。
* · nodeTypeH / nodeWidth:节点默认高宽(宿主读 NODE_TYPES / NODE_W 常量表 —— 那两张表被边界守门冻结,不搬)
* · isBatchSrc / batchPortTop / compareCanvasTextOrder:批量节点判定、端口纵向定位、端口来源排序
* (均来自 src/canvas-text.js)
* 无依赖的 connectReasonOf / distToSeg 仍直接挂在 window.IWBCanvasGeometry 上(不破坏既有消费方)。
* 宿主只经 window.IWBCanvasGeometry 使用。
*/
;(function (global) {
'use strict'
const connectReasonOf = (src, dst, hasEdge, isImageProducer) => {
// ── 声明式「提示词类输出」(2026-11-14)────────────────────────────────
// 插件节点可以声明 `data.outKind === 'prompt'`,表示「我这一路输出的是一段提示词」
// (首个使用方 = 风格库的样式节点:它输出的就是渲染后的完整提示词)。
// 这类节点的 type 是 `plugin:<id>:<variant>`,**运行时注册、宿主静态表里没有**,
// 逐条往下面 7 张白名单里加类型既容易漏,以后再加节点类型时还会再漏一次。
// 所以这里做一次归一化:声明了就按 prompt 节点参与下面的规则判定。
// 内置节点没有 outKind 字段 ⇒ 所有规则逐字不变(零回归,现有画布连不上的仍然连不上)。
const srcIsPromptOut = !!(src && src.data && src.data.outKind === 'prompt')
// 相册(2026-11-26):声明 outKind:'images' ⇒ 下游当作「图片来源」参与规则(能进生图/组合/中继)。
const srcIsImagesOut = !!(src && src.data && src.data.outKind === 'images')
const st = srcIsPromptOut ? 'prompt' : (srcIsImagesOut ? 'ref' : src.type)
// 相册自己只接受文本类输入(提示词/文本/组合/批量/中继):它自带图片,不吃别人的图。
if (dst && dst.data && dst.data.outKind === 'images' && st !== 'prompt' && st !== 'textout' && st !== 'combine' && st !== 'batch' && st !== 'relay' && !srcIsPromptOut) return '相册节点只接受提示词/文本类输入'
// batch 多输出:不同来源端口可连到同一目标;普通节点同对仅一条边
if (src.type !== 'batch' && hasEdge) return '这两个节点已经连接'
// 提示词节点原来只收参考图 / 中继(避免提示词串联);样式节点要能进来做二次编辑,单独放行
if (dst.type === 'prompt' && st !== 'ref' && st !== 'relay' && !srcIsPromptOut) return '提示词节点只能接收参考图或中继节点'
if (dst.type === 'llm' && st !== 'prompt' && st !== 'relay') return '润色节点只能接收提示词'
if (dst.type === 'textout' && st !== 'relay' && st !== 'llm' && st !== 'combine' && st !== 'batch' && !srcIsPromptOut) return '文本节点只能接收润色、组合或连接节点'
if (dst.type === 'combine' && st !== 'relay' && st !== 'prompt' && st !== 'textout' && st !== 'llm' && st !== 'ref' && st !== 'batch') return '组合节点不支持此来源'
if (dst.type === 'gen' && st !== 'prompt' && st !== 'relay' && st !== 'ref' && st !== 'textout' && st !== 'combine' && st !== 'batch') return '生图节点不支持此来源'
if (dst.type === 'layer' && st !== 'prompt' && st !== 'relay' && st !== 'ref' && st !== 'textout' && st !== 'combine' && st !== 'batch') return '分层节点不支持此来源'
if (dst.type === 'out' && !isImageProducer(src)) return '输出节点只能接收配置 / 分层节点'
if (dst.type === 'batch' && st !== 'relay' && st !== 'prompt' && st !== 'textout' && st !== 'combine' && st !== 'llm') return '连接节点不支持此来源'
if (dst.type === 'relay') return ''
if (dst.type === 'ref') return '图片节点只能作为来源,不接受连线'
return ''
}
const distToSeg = (p, a, b) => {
const dx = b.x - a.x, dy = b.y - a.y
const len2 = dx * dx + dy * dy
let t = len2 ? ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2 : 0
t = Math.max(0, Math.min(1, t))
const cx = a.x + t * dx, cy = a.y + t * dy
return Math.hypot(p.x - cx, p.y - cy)
}
// ── 需要注入依赖的一组(P1 拆分批 3)────────────────────────────────────────
const create = (deps) => {
const D = deps || {}
const need = (name) => {
const fn = D[name]
if (typeof fn !== 'function') throw new Error('IWBCanvasGeometry 缺少注入依赖: ' + name)
return fn
}
const nodeTypeH = need('nodeTypeH')
const nodeWidth = need('nodeWidth')
const isBatchSrc = need('isBatchSrc')
const batchPortTop = need('batchPortTop')
// 批量端口排序用(同一目标节点的多个来源按画布位置排序,保证端口顺序稳定)
const compareCanvasTextOrder = need('compareCanvasTextOrder')
function areNodeEqual(prev, next) {
const stableDuringDrag = prev.dragging && next.dragging && prev.node === next.node
// v3.87.16:缩放期间,**非被拖节点**只要自身 node 对象没变就可以跳过渲染。
// 根因:缩放每帧生成新的 nodes 数组,而下面要求 prev.nodes === next.nodes →
// 除被拖节点外全部判定"不相等" → 每帧重建全部节点体(有图节点的结果网格最贵,
// 实测 2 个图节点 × 61 步 = 121 次无谓重建)。放宽仅限"正在进行缩放"这一小段窗口。
const stableDuringResize = !!(prev.resizing && next.resizing && !prev.sizing && !next.sizing && prev.node === next.node)
// v3.87.39:画布缩放窗口内,非被拖/被缩放节点只要自身 node 未变即可跳过渲染
// (缩放不改变任何节点数据,只有 nodes 数组引用在变 ⇒ 内容必然相同)
const stableDuringZoom = !!(prev.zooming && next.zooming && prev.node === next.node)
return prev.node === next.node
&& prev.selected === next.selected
&& prev.draggingNode === next.draggingNode
&& prev.measuredH === next.measuredH
&& prev.busy === next.busy
&& prev.progress === next.progress
&& prev.sourceBusy === next.sourceBusy
&& prev.sourceProgress === next.sourceProgress
&& prev.connTarget === next.connTarget
&& prev.sizing === next.sizing
&& prev.resizing === next.resizing
&& prev.zooming === next.zooming
&& (stableDuringDrag || stableDuringResize || stableDuringZoom || prev.edges === next.edges)
&& (stableDuringDrag || stableDuringResize || stableDuringZoom || prev.nodes === next.nodes)
&& prev.batchSources === next.batchSources
&& prev.thumbRev === next.thumbRev // v3.87.61:小图派生完成后必须重建节点体(否则缩略图换不上 ✗)
&& prev.typesRev === next.typesRev // 2026-11-14:插件注册 render 后必须重建(否则插件节点停在兜底体:只剩一段文本)
&& prev.config === next.config
&& prev.lodLow === next.lodLow
}
function computeEdgePath(ed, graph, nodeMap, measuredH, pathCache) {
const src = nodeMap.get(ed.from), dst = nodeMap.get(ed.to)
if (!src || !dst) return null
const hOf = (n) => (measuredH && measuredH[n.id]) || n.h || nodeTypeH(n.type)
const batchSig = (src.type === 'batch' || dst.type === 'batch')
? ((graph && graph.incomingByNode.get(dst.id)) || []).map((e) => {
const n = graph && graph.byId && graph.byId.get(e.from)
return n ? (n.id + ':' + n.x + ':' + n.y) : ''
}).sort().join(',')
: ''
const key = (src.type === 'batch' || dst.type === 'batch')
? ('b' + ed.id + '|' + src.x + '|' + src.y + '|' + hOf(src) + '|' + dst.x + '|' + dst.y + '|' + hOf(dst) + '|' + (ed.batchSrcId || '') + '|' + batchSig)
: (ed.id + '|' + src.x + '|' + src.y + '|' + (src.w || '') + '|' + hOf(src) + '|' + dst.x + '|' + dst.y + '|' + hOf(dst))
const hit = pathCache.get(key)
if (hit) return hit
const dh = hOf(dst)
const inY = dst.type === 'prompt' ? Math.max(46, dh * 0.3) : dh / 2
let x1 = src.x + nodeWidth(src), y1 = src.y + hOf(src) / 2
let x2 = dst.x, y2 = dst.y + inY
if (src.type === 'batch' && ed.batchSrcId) {
const bsrcs = ((graph && graph.incomingByNode.get(src.id)) || []).map((e) => graph && graph.byId.get(e.from)).filter((n) => isBatchSrc(n, graph && graph.edges, graph && graph.nodes)).slice().sort(compareCanvasTextOrder)
const idx = bsrcs.findIndex((s) => s.id === ed.batchSrcId)
if (idx >= 0) y1 = src.y + batchPortTop(idx, Math.max(1, bsrcs.length), hOf(src))
}
if (dst.type === 'batch') {
const bsrcs = ((graph && graph.incomingByNode.get(dst.id)) || []).map((e) => graph && graph.byId.get(e.from)).filter((n) => isBatchSrc(n, graph && graph.edges, graph && graph.nodes)).slice().sort(compareCanvasTextOrder)
const idx = bsrcs.findIndex((s) => s.id === ed.from)
if (idx >= 0) y2 = dst.y + batchPortTop(idx, Math.max(1, bsrcs.length), hOf(dst))
}
const dx = Math.max(40, (x2 - x1) / 2)
const d = 'M ' + x1 + ' ' + y1 + ' C ' + (x1 + dx) + ' ' + y1 + ', ' + (x2 - dx) + ' ' + y2 + ', ' + x2 + ' ' + y2
if (pathCache.size > 3000) pathCache.clear()
pathCache.set(key, d)
return d
}
return { computeEdgePath, areNodeEqual }
}
// 插件建节点时的坐标语义:null/undefined/非有限数 ⇒ 交给宿主 findSpot 找位。
// 为什么不让插件自己算:它只有节点 x/y,拿不到 viewport(pan/zoom) 与各节点实测高度,
// 排出来的位置会跑到视口外或压在已有节点上(style-source 1.1.1 之前的实际表现)。
const wantsDefaultSpot = (x, y) => x === null || x === undefined || y === null || y === undefined ||
!Number.isFinite(Number(x)) || !Number.isFinite(Number(y))
// 屏幕坐标 → 画布世界坐标(插件「拖到画布上松手建节点」用)。
// 为什么必须由宿主算:viewport(pan/zoom)与画布容器位置只有宿主知道,插件拿不到;
// 反过来让插件传屏幕坐标进来,宿主换算后建节点 ⇒ 插件不必碰 viewport,语义也和 createNode 的
// 「x/y 是世界坐标」保持一致。
const parseWorldTransform = (transform) => {
const m = /translate\((-?[\d.]+)px,\s*(-?[\d.]+)px\)\s*scale\(([\d.]+)\)/.exec(String(transform || ''))
if (!m) return { x: 0, y: 0, scale: 1 }
const scale = Number(m[3])
return { x: Number(m[1]), y: Number(m[2]), scale: scale > 0 ? scale : 1 }
}
// canvasRect:画布容器的 getBoundingClientRect()(世界层的父元素,通常铺满窗口)
const clientToWorld = (clientX, clientY, canvasRect, t) => {
const rect = canvasRect || { left: 0, top: 0 }
const vp = t || { x: 0, y: 0, scale: 1 }
const scale = vp.scale > 0 ? vp.scale : 1
return {
x: (Number(clientX) - (Number(rect.left) || 0) - (Number(vp.x) || 0)) / scale,
y: (Number(clientY) - (Number(rect.top) || 0) - (Number(vp.y) || 0)) / scale,
scale: scale,
}
}
// 拖放落点吸附(插件「拖到画布上松手」用):松手点压住已有节点时,就近找一个**不重叠**的位置。
// 为什么不硬落:叠在一起的两个节点既看不清也不好拖开,用户还得手动挪——
// 与 findSpot 的「不叠节点」是同一条要求,只是这里**离落点尽量近**而不是跑到视口中心。
// 搜索:以落点为原点,按 (w+gap, h+gap) 的方阵环向外扫(最近优先);bounds 是允许的左上角范围
// (调用方把视口换算成世界坐标传进来),越界候选一律排在界内候选之后而不是直接丢弃。
const snapToFreeSpot = (drop, obstacles, opts) => {
const d = drop || {}
const w = Number(d.w) || 0
const h = Number(d.h) || 0
const x0 = Number(d.x)
const y0 = Number(d.y)
if (!Number.isFinite(x0) || !Number.isFinite(y0) || w <= 0 || h <= 0) return { x: x0, y: y0, snapped: false }
const gap = (opts && Number.isFinite(opts.gap)) ? Number(opts.gap) : 20
const rings = (opts && Number.isFinite(opts.rings)) ? Number(opts.rings) : 8
const bounds = opts && opts.bounds
const list = (Array.isArray(obstacles) ? obstacles : []).filter((o) => o &&
Number.isFinite(Number(o.x)) && Number.isFinite(Number(o.y)) && Number(o.w) > 0 && Number(o.h) > 0)
// gap 两侧都留:相邻节点之间至少 gap 的间隙(与 findSpot 的 20px 一致)
const hit = (x, y) => list.some((o) => x < o.x + o.w + gap && x + w + gap > o.x && y < o.y + o.h + gap && y + h + gap > o.y)
const inBounds = (x, y) => !bounds || (x >= bounds.minX - 0.5 && y >= bounds.minY - 0.5 && x <= bounds.maxX + 0.5 && y <= bounds.maxY + 0.5)
if (!hit(x0, y0)) return { x: x0, y: y0, snapped: false }
const stepX = Math.max(w + gap, 1)
const stepY = Math.max(h + gap, 1)
const cands = []
for (let gy = -rings; gy <= rings; gy++) {
for (let gx = -rings; gx <= rings; gx++) {
if (!gx && !gy) continue
const x = x0 + gx * stepX
const y = y0 + gy * stepY
cands.push({ x: x, y: y, out: inBounds(x, y) ? 0 : 1, dist: Math.hypot(gx * stepX, gy * stepY), ax: Math.abs(gx), ay: Math.abs(gy) })
}
}
cands.sort((a, b) => (a.out - b.out) || (a.dist - b.dist) || (a.ax - b.ax) || (a.ay - b.ay))
for (const c of cands) if (!hit(c.x, c.y)) return { x: Math.round(c.x), y: Math.round(c.y), snapped: true }
// 所有候选都被占(画布极小):贴到最右障碍外侧,至少不叠进节点里
let right = x0
for (const o of list) right = Math.max(right, o.x + o.w + gap)
return { x: Math.round(right), y: Math.round(y0), snapped: true }
}
// 复制节点落位(节点气泡「复制」/ 节点头部复制 / Ctrl+D / 右键菜单 / 组复制共用)。
// 为什么不能沿用「固定对角线错位」:偏移是常量像素(旧实现 56px),而节点宽 264~520 ——
// 480 宽的配置节点被复制体压住 88%×88%,复制体又渲染在源节点上层(DOM 在后),
// 于是原节点只剩左上一条细边可点,用户只能看见"复制完贴在一起、选不中"。
// 这里改成:逐圈外扩(右 → 下 → 左 → 右下/左下 → 右上/左上 → 上,"上方"排最后:往上跑会撞上游链路,
// 观感像"复制体跳到了原节点头顶"),逐格做**真实**重叠检测(含源节点本身,
// 与旧实现 `!ids.includes(existing.id)` 相反),并优先落在 bounds(视口)内;
// 整圈都在视口外才退回 snapToFreeSpot 的环形搜索。
const placeBeside = (anchor, obstacles, opts) => {
const a = anchor || {}
const ax = Number(a.x), ay = Number(a.y)
const w = Number(a.w), h = Number(a.h)
if (!Number.isFinite(ax) || !Number.isFinite(ay) || !(w > 0) || !(h > 0)) return { x: ax, y: ay, placed: false }
const gap = (opts && Number.isFinite(opts.gap)) ? Number(opts.gap) : 20
const bounds = opts && opts.bounds
const list = (Array.isArray(obstacles) ? obstacles : []).filter((o) => o &&
Number.isFinite(Number(o.x)) && Number.isFinite(Number(o.y)) && Number(o.w) > 0 && Number(o.h) > 0)
// 两侧都留 gap:相邻节点之间至少 gap 的间隙(与 snapToFreeSpot 同一口径)
const hit = (x, y) => list.some((o) => x < o.x + o.w + gap && x + w + gap > o.x && y < o.y + o.h + gap && y + h + gap > o.y)
const inB = (x, y) => !bounds || (x >= bounds.minX - 0.5 && y >= bounds.minY - 0.5 && x <= bounds.maxX + 0.5 && y <= bounds.maxY + 0.5)
const stepX = w + gap, stepY = h + gap
// 方向表 + 逐圈外扩:第 k 圈的所有候选都比第 k-1 圈远,所以"首个空位"天然就是最近的那格。
// 逐圈而不是只试 8 个方向一步:连按两次复制时,第二步要能落到"第一份复制体的下方",
// 否则候选全被占就只能靠 snapToFreeSpot 跳到很远的地方。
const dirs = [[1, 0], [0, 1], [-1, 0], [1, 1], [-1, 1], [1, -1], [-1, -1], [0, -1]]
const rings = (opts && Number.isFinite(opts.rings)) ? Number(opts.rings) : 6
let loose = null // 空着但在视口外:先记下,等确认视口内确实没位置再用
for (let k = 1; k <= rings; k++) {
for (const d of dirs) {
const x = ax + d[0] * stepX * k, y = ay + d[1] * stepY * k
if (hit(x, y)) continue
if (inB(x, y)) return { x: Math.round(x), y: Math.round(y), placed: true }
if (!loose) loose = [x, y]
}
}
if (loose) return { x: Math.round(loose[0]), y: Math.round(loose[1]), placed: true }
const out = snapToFreeSpot({ x: ax + stepX, y: ay, w: w, h: h }, list, { gap: gap, bounds: bounds, rings: 8 })
return { x: out.x, y: out.y, placed: true }
}
// 测量高度表裁剪(换画板时用):只删「不属于当前画板」的 id,**原地删键、不换对象**。
// 为什么不能 `refs.measuredH = {}`:NodeCard 的高度测量 effect 依赖数组是空数组(只在挂载时跑一次),
// 换画板时同一批节点 id 不变 ⇒ 组件不重新挂载、ResizeObserver 也不会因为高度没变而回调 ⇒
// 整表清空之后就永久为空,端口高度 / 连线端点 / 适应视图 / 复制落点全部退化成默认高度
// (实测提示词默认 216、实际 89)。原地删键还保证 session.measuredH 与 refs.measuredH 不各指一个对象。
const pruneMeasured = (measured, nodes) => {
// 节点表不是数组(首屏装载、异常数据)时**什么都不删**:留着旧值最多是多测几个节点,
// 而误清空会重演上面那个"永久为空"。
if (!measured || typeof measured !== 'object' || !Array.isArray(nodes)) return measured
const keep = new Set(nodes.map((n) => n && n.id).filter(Boolean))
for (const k in measured) if (!keep.has(k)) delete measured[k]
return measured
}
// ── LOD(低细节渲染)判据 ────────────────────────────────────────────────
// 判据是**节点在屏幕上的实际宽度**,不是全局 viewport.scale。
// 旧判据 `viewport.scale < 0.05` 只在极端缩放下才生效:800 节点的 fit 视图 scale ≈ 0.17,
// 每个节点屏幕宽只剩 264 × 0.17 ≈ 45px(textarea 里的字根本读不了),却仍然渲染完整节点体
// (textarea / 图片网格 / 按钮)。实测切一次画布 488ms,其中 react-dom 271ms + react 173ms,
// 业务逻辑(switchWs / normalizeNodes / composeWorkspaceList)只有 3.9ms —— 成本全在这个"看不见的细节"上。
// 按屏幕宽度判定后:fit 视图自动进入 LOD,放大回来看细节自动恢复,语义与「能不能看清」一致。
//
// 64px 的依据(实测校准过两轮):
// · 节点默认宽 264(NODE_W)→ 阈值约在 scale 0.24,即 12~13px 正文只剩 3.1~3.5px,不可能读;
// · 曾用 96px,但窄提示词节点(w=160,用户常手动调窄)在 scale 0.5 就会变灰块 ——
// 而 0.5 是**正常编辑**的档位,用户此刻还要看内容,所以 96 太激进(实测撞到,立刻回调)。
// · 800 节点 fit 视图 scale ≈ 0.2 ⇒ 264 × 0.2 = 53px,仍在 64 以下,该省的渲染照样省得掉。
// 中继节点豁免:它宽 72px(圆形),节点体就是一个圆环(ui-node-bodies.js 的 .iwb-relay-ring),
// 本身极轻;而且是连线的视觉锚点,变空白会让画布"看起来断线"。
const LOD_NODE_PX = 64
// 两档(v3.24.78,用户实测反馈「图片简化后无法判断节点内容」):
// · lite(本判据为真、但缩放 ≥ LOD_PLAIN_SCALE)→ 画一张代表图 / 首行文字,**看得出是哪个节点**;
// · plain(缩放 < 15%)→ 连图都不画,纯 CSS 占位。
// 用户原话「我需要再 15% 以下才会开始简化节点」:15% 是**全局缩放**判据(此时节点屏幕宽普遍 < 30px,
// 缩略图也只有几十像素,没有信息量);15% 以上只要节点够宽就保留内容,而不是一律灰块。
const LOD_PLAIN_SCALE = 0.15
const lodLowOf = (viewport, node, nodeWidth) => {
if (!node || node.type === 'relay') return false
const s = Number(viewport && viewport.scale)
if (!Number.isFinite(s) || s <= 0) return false
const w = Number(nodeWidth && nodeWidth(node))
if (!Number.isFinite(w) || w <= 0) return false
return s * w < LOD_NODE_PX
}
// 返回 '' | 'lite' | 'plain'('' = 完整渲染)。plain 只看全局缩放,不看节点宽度 ——
// 缩到 15% 以下时再宽的节点也只剩一两百像素,没必要为它单独留完整交互体。
const lodModeOf = (viewport, node, nodeWidth) => {
if (!node || node.type === 'relay') return ''
const s = Number(viewport && viewport.scale)
if (!Number.isFinite(s) || s <= 0) return ''
// v3.26.157:取消 30% 那档 lite —— 它在阈值附近来回切换,视觉上就是「画面常闪」。
// 现在只剩一档:<15% 切 plain,其余一律渲染完整节点体。
if (s < LOD_PLAIN_SCALE) return 'plain'
return ''
}
// ── 按钮缩放(v3.24.83)────────────────────────────────────────────────
// 底栏「−/+」与快捷键 +/- 共用这一条路径:一步一档 15%,**锚点固定为画布中心**。
// 为什么锚中心而不是鼠标:按钮点击时鼠标就停在按钮上(画布左下角),锚鼠标会把内容往右上角甩,
// 用户下一步必然要拖回来。锚中心的话,看得的那片内容原地不动 —— 与滚轮缩放的手感一致。
// 上下限与滚轮 / 适应视图保持一致(0.01 ~ 3):按钮不该成为把画布推到看不清的通道。
const ZOOM_STEP = 1.15
const ZOOM_MIN = 0.01
const ZOOM_MAX = 3
const zoomStep = (viewport, dir, cw, ch) => {
const v = viewport || { x: 0, y: 0, scale: 1 }
const s0 = Number(v.scale) > 0 ? Number(v.scale) : 1
const s1 = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, s0 * (dir > 0 ? ZOOM_STEP : 1 / ZOOM_STEP)))
const k = s1 / s0
// 已经顶到上限/下限时 k === 1 ⇒ 视图完全不动(不会「按了没反应但画面跳一下」)
if (k === 1) return { x: Number(v.x) || 0, y: Number(v.y) || 0, scale: s1 }
const cx = (Number(cw) || 800) / 2, cy = (Number(ch) || 600) / 2
return { scale: s1, x: cx - (cx - (Number(v.x) || 0)) * k, y: cy - (cy - (Number(v.y) || 0)) * k }
}
// 「指针 = 内容左上角」→ findSpot 的 seed 语义(v3.24.74)。
// findSpot 的 seed 是节点**中心**:它按 `cx - w/2` 反推左上角,而 w/h 取的是
// nodeTypeH 的**估算值**(prompt 216,空提示词节点实测 ~90)。于是「把中心对准指针」
// 实际把视觉中心固定顶上去 63px —— 用户看到的是「贴出来总比鼠标高一大截」。
// 想让落点精确,只能改语义:指针就是内容左上角,再交给 findSpot 换成中心。
// 这么换算之后**不再依赖任何高度估算**:高度只影响「往下延伸多少」,不影响落点。
const seedFromTopLeft = (seed, w, h) => {
const x = Number(seed && seed.x), y = Number(seed && seed.y)
if (!Number.isFinite(x) || !Number.isFinite(y)) return seed
const ww = Number(w) || 0, hh = Number(h) || 0
return { x: x + ww / 2, y: y + hh / 2 }
}
// 把「以左上角定位的盒子」夹进视口的世界范围(粘贴节点组 / 多图栅格用)。
// 为什么需要:落点跟鼠标之后,在窗口右下角粘贴会把节点的右半截推出视口 ——
// 用户只看到一条边,比"离鼠标远一点"难处理得多。可见优先于"严格贴指针"。
// 盒子比视口还大时贴 minX/minY:宁可右/下溢出,也不要把左/上推到画布外(那样整块都看不见)。
const clampIntoBounds = (box, bounds) => {
const b = box || {}, bd = bounds || {}
let x = Number(b.x), y = Number(b.y)
if (!Number.isFinite(x) || !Number.isFinite(y)) return { x: b.x, y: b.y }
const w = Number(b.w) || 0, h = Number(b.h) || 0
const minX = Number(bd.minX), maxX = Number(bd.maxX)
const minY = Number(bd.minY), maxY = Number(bd.maxY)
if (Number.isFinite(minX) && Number.isFinite(maxX)) x = Math.min(Math.max(x, minX), Math.max(minX, maxX - w))
if (Number.isFinite(minY) && Number.isFinite(maxY)) y = Math.min(Math.max(y, minY), Math.max(minY, maxY - h))
return { x: Math.round(x), y: Math.round(y) }
}
// 插件「插入画布」落到可视区域中心(findSpot 会把节点丢左上角,常被左侧面板遮住)。
// v3.26.109(内存 C):画布视口裁剪矩形。
// 动机:节点一旦挂上 <img>,浏览器就为它保留解码位图(1024 缩略图约 4MB、原图 6~20MB)。
// 原来统一 240px 边距 ⇒ 屏幕外一两屏的图仍常驻解码(实测 WebContent footprint 1.2G / 峰值 2.7G)。
// 现在带图节点只留 80px,同一时刻常驻解码的图片数量明显下降;纯文本节点仍用 240px,避免平移时文字闪。
// v3.26.143:参考 infinite-canvas 的 280px 缓冲;80px 会让图片节点在平移边缘反复卸载/重解码。
const CULL_PAD_WIDE = 280
const CULL_PAD_TIGHT = 280
const heavyNodeOf = (type) => {
const t = String(type || '')
return /^(ref|out|image|combine|batch)$/.test(t) || /^plugin:(album|gallery)/.test(t)
}
function cullRectsOf (canvasSize, viewport, extraPad) {
const w = Number(canvasSize && canvasSize.w) || 0
const h = Number(canvasSize && canvasSize.h) || 0
const s = Number(viewport && viewport.scale) || 0
if (!w || !h || !s) return null
const extra = Math.max(0, Number(extraPad) || 0)
const mk = (pad) => {
const p = pad + extra
return {
left: -viewport.x / s - p,
top: -viewport.y / s - p,
right: (w - viewport.x) / s + p,
bottom: (h - viewport.y) / s + p,
}
}
return { wide: mk(CULL_PAD_WIDE), tight: mk(CULL_PAD_TIGHT) }
}
function nodeVisibleIn (n, rects, opt) {
if (!rects || !n) return true
const o = opt || {}
if (o.drag && o.drag.start && o.drag.start[n.id] != null) return true
if (o.resize && o.resize.nodeId === n.id) return true
if (o.sel && o.sel.indexOf(n.id) >= 0) return true
// v3.26.156:平移期默认只挂载「起点窗口 + 当前窗口」并集内的节点(不再全量)。
// 全量挂载会把整个世界层撑到几十屏大小,WebKit 只能分块栅格化,平移时就会出现残块/拖影。
// o.mountAll 保留旧行为(诊断开关 iwb_pan_mount_all=1 时启用)。
if (o.pan && o.mountAll) return true
const r = heavyNodeOf(n.type) ? rects.tight : rects.wide
const nw = o.widthOf ? o.widthOf(n) : 0
const nh = o.heightOf ? o.heightOf(n) : 0
return n.x < r.right && n.x + nw > r.left && n.y < r.bottom && n.y + nh > r.top
}
const promptCenterSpot = (bridge, w, h) => {
try {
const c = typeof document !== 'undefined' ? document.querySelector('.iwb-canvas') : null
if (!c || !bridge || typeof bridge.screenToWorld !== 'function') return null
const r = c.getBoundingClientRect()
const p = bridge.screenToWorld(r.left + r.width / 2, r.top + r.height / 2)
return p ? { x: p.x - (w || 0) / 2, y: p.y - (h || 0) / 2 } : null
} catch (e) { return null }
}
// 边线 SVG 固定放在屏幕坐标系:宽度恒为视口 CSS 宽,不会按世界尺寸分配合成位图。
// 世界坐标由内部 <g class="iwb-edge-world"> 的 transform 负责;缩小画布时也不会让 SVG 变大。
function edgeLayerSize (canvasSize) {
return { w: Math.max(1, Number(canvasSize && canvasSize.w) || 800), h: Math.max(1, Number(canvasSize && canvasSize.h) || 600) }
}
function edgeLayerProps (canvasSize) {
const r = edgeLayerSize(canvasSize)
return { width: r.w, height: r.h, viewBox: '0 0 ' + r.w + ' ' + r.h, style: { left: 0, top: 0, width: r.w + 'px', height: r.h + 'px', overflow: 'hidden' } }
}
function edgeGroupTransform (viewport) {
const x = Number(viewport && viewport.x) || 0
const y = Number(viewport && viewport.y) || 0
const s = Number(viewport && viewport.scale) > 0 ? Number(viewport.scale) : 1
return 'translate(' + x + ',' + y + ') scale(' + s + ')'
}
function applyViewportDom (root, canvasSize, x, y, scale, gridOpts, opts) {
if (!root) return
const wl = root.querySelector && root.querySelector('.iwb-world')
if (wl) wl.style.transform = 'translate(' + x + 'px, ' + y + 'px) scale(' + scale + ')'
// v3.26.155:手势期间不写命中层 SVG 的 transform —— 每帧改一个装着上百条 path 的 <g>,
// WebKit 会把整层 SVG 重新布局+栅格化;它本来不可见(视觉在 canvas 上),停手后再对齐一次即可。
if (!(opts && opts.skipEdgeLayer)) applyEdgeLayerDom(root, canvasSize, x, y, scale)
const grid = root.querySelector ? root.querySelector('.iwb-grid') : null
if (!grid) return
const o = gridOpts || { base: 22, dot: 1.4, color: 'rgba(120,128,140,0.55)', on: true }
const G = global.IWBCanvasGrid
if (G && typeof G.applyTo === 'function') {
if (!o.on) { grid.style.display = 'none' } else { grid.style.display = ''; G.applyTo(grid, x, y, scale, o) }
} else {
grid.style.backgroundSize = (28 * scale) + 'px ' + (28 * scale) + 'px'
grid.style.backgroundPosition = x + 'px ' + y + 'px'
}
}
function applyEdgeLayerDom (root, canvasSize, x, y, scale) {
const g = root && root.querySelector ? root.querySelector('.iwb-edge-world') : null
if (g) g.setAttribute('transform', edgeGroupTransform({ x: x, y: y, scale: scale }))
}
global.IWBCanvasGeometry = Object.freeze({ connectReasonOf, cullRectsOf, nodeVisibleIn, heavyNodeOf, edgeLayerSize, edgeLayerProps, edgeGroupTransform, applyEdgeLayerDom, applyViewportDom, distToSeg, wantsDefaultSpot, promptCenterSpot, parseWorldTransform, clientToWorld, snapToFreeSpot, placeBeside, pruneMeasured, seedFromTopLeft, clampIntoBounds, lodLowOf, lodModeOf, zoomStep, LOD_NODE_PX, LOD_PLAIN_SCALE, ZOOM_STEP, ZOOM_MIN, ZOOM_MAX, create })
})(typeof window !== 'undefined' ? window : globalThis)