Files
image-workbench-desktop/src/canvas-v3-node-layer.js
T

241 lines
11 KiB
JavaScript

/* canvas-v3-node-layer.js —— Canvas V3 图片节点静态层(2026-12-01,P1 垂直切片)
*
* 仅当 data-canvas-v3="on" 时由 app 挂载;未选中的 ref 节点由 canvas 画卡片/标题/图片,
* DOM 只保留一个透明 hit proxy。选中后恢复完整 NodeCard。
* 目标与限制见 docs/plans/canvas-v3-long-term.md。
*/
;(function (global) {
'use strict'
const React = global.React || {}
const el = (type, prop, ...children) => React.createElement(type, prop, ...children)
const useRef = React.useRef
const useEffect = React.useEffect
const useState = React.useState
const imgCache = new Map()
const perf = { lastMs: 0, frames: 0 }
function css (name, fallback) {
try {
const v = getComputedStyle(document.documentElement).getPropertyValue(name).trim()
return v || fallback
} catch (e) { return fallback }
}
function roundRect (ctx, x, y, w, h, r) {
const rr = Math.max(0, Math.min(r, w / 2, h / 2))
ctx.beginPath()
ctx.moveTo(x + rr, y)
ctx.arcTo(x + w, y, x + w, y + h, rr)
ctx.arcTo(x + w, y + h, x, y + h, rr)
ctx.arcTo(x, y + h, x, y, rr)
ctx.arcTo(x, y, x + w, y, rr)
ctx.closePath()
}
function imageOf (url, onLoad) {
if (!url) return null
let entry = imgCache.get(url)
if (!entry) {
entry = { img: new Image(), loaded: false }
entry.img.decoding = 'async'
entry.img.onload = () => { entry.loaded = true; if (typeof onLoad === 'function') onLoad() }
entry.img.onerror = () => { entry.failed = true; if (typeof onLoad === 'function') onLoad() }
entry.img.src = url
if (imgCache.size > 64) { const k = imgCache.keys().next().value; if (k !== undefined) imgCache.delete(k) }
imgCache.set(url, entry)
}
return entry
}
function drawUnsafe (canvas, o) {
if (!canvas || !o || typeof canvas.getContext !== 'function') return
const t0 = (typeof performance !== 'undefined' && performance.now) ? performance.now() : 0
const rect = canvas.getBoundingClientRect ? canvas.getBoundingClientRect() : null
const w = Math.max(1, Math.round((rect && rect.width) || canvas.clientWidth || 1))
const h = Math.max(1, Math.round((rect && rect.height) || canvas.clientHeight || 1))
const dpr = Math.min(2, (typeof devicePixelRatio === 'number' && devicePixelRatio > 0) ? devicePixelRatio : 1)
if (canvas.width !== Math.round(w * dpr) || canvas.height !== Math.round(h * dpr)) {
canvas.width = Math.round(w * dpr); canvas.height = Math.round(h * dpr)
}
const ctx = canvas.getContext('2d')
if (!ctx) return
ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
ctx.clearRect(0, 0, w, h)
const vp = o.viewport || { x: 0, y: 0, scale: 1 }
const scale = Number(vp.scale) > 0 ? Number(vp.scale) : 1
const nodes = Array.isArray(o.nodes) ? o.nodes : []
const sel = Array.isArray(o.sel) ? o.sel : []
const widthOf = typeof o.widthOf === 'function' ? o.widthOf : (n) => n.w || 240
const heightOf = typeof o.heightOf === 'function' ? o.heightOf : (n) => n.h || 220
const imageFor = typeof o.imageFor === 'function' ? o.imageFor : () => ''
const outThumbsFor = typeof o.outThumbsFor === 'function' ? o.outThumbsFor : () => []
const onImageLoad = o.onImageLoad
const types = Array.isArray(o.types) && o.types.length ? o.types : ['ref']
const isType = typeof o.isType === 'function' ? o.isType : (n) => types.indexOf(n.type) >= 0
const bg = css('--iwb-panel', '#ffffff')
const border = css('--iwb-border2', '#d7dbe2')
const text = css('--iwb-text2', '#5f6673')
const accent = css('--iwb-brand', '#6b7280')
const radius = 14
const headH = 34
ctx.setTransform(dpr * scale, 0, 0, dpr * scale, dpr * (Number(vp.x) || 0), dpr * (Number(vp.y) || 0))
ctx.lineJoin = 'round'
for (const n of nodes) {
if (!n || !isType(n) || sel.indexOf(n.id) >= 0) continue
const x = n.x, y = n.y, nw = widthOf(n), nh = heightOf(n)
const screenW = nw * scale
// LOD:极小节点只画底板,跳标题/文本/图片,避免 7000 节点缩放时做无用绘制。
if (screenW < 8) {
ctx.fillStyle = bg
ctx.fillRect(x, y, nw, nh)
continue
}
const lowDetail = screenW < 40
// 卡片
ctx.fillStyle = bg
roundRect(ctx, x, y, nw, nh, radius)
ctx.fill()
ctx.strokeStyle = border
ctx.lineWidth = 1 / scale
ctx.stroke()
// 标题
ctx.fillStyle = text
ctx.font = '600 ' + Math.max(10, 12 / scale * 0.9) + 'px -apple-system, BlinkMacSystemFont, "PingFang SC", sans-serif'
const title = String((n.data && (n.data.title || n.data.name)) || ({ ref: '参考图', prompt: '提示词', textout: '文本', combine: '组合', batch: '连接', relay: '中继', gen: '生成配置', layer: '分层', plugin: '插件' }[n.type] || (String(n.type).indexOf('plugin:') === 0 ? '插件' : '节点')))
if (!lowDetail) {
ctx.save()
ctx.beginPath(); ctx.rect(x + 10, y, Math.max(0, nw - 20), headH); ctx.clip()
ctx.fillText(title, x + 12, y + 21)
ctx.restore()
}
const pad = 10
const ix = x + pad, iy = y + headH, iw = Math.max(1, nw - pad * 2), ih = Math.max(1, nh - headH - pad)
if (lowDetail) continue
if (n.type === 'ref') {
// 图片区
const raw = n.data && (n.data.data || n.data.url)
const url = raw ? imageFor(n, raw) : ''
const entry = url ? imageOf(url, onImageLoad) : null
if (entry && entry.loaded && !entry.failed) {
const iw0 = entry.img.naturalWidth || iw
const ih0 = entry.img.naturalHeight || ih
const k = Math.min(iw / iw0, ih / ih0)
const dw = iw0 * k, dh = ih0 * k
try { ctx.drawImage(entry.img, ix + (iw - dw) / 2, iy + (ih - dh) / 2, dw, dh) } catch (e) { /* cross-origin */ }
} else {
ctx.fillStyle = css('--iwb-layer2', '#f1f2f4')
roundRect(ctx, ix, iy, iw, ih, 10)
ctx.fill()
ctx.fillStyle = text
ctx.font = Math.max(10, 12 / scale * 0.9) + 'px -apple-system, BlinkMacSystemFont, "PingFang SC", sans-serif'
ctx.fillText(entry && entry.failed ? '图片源失效' : '图片加载中…', ix + 12, iy + 24)
}
} else if (n.type === 'out') {
// 输出节点:画结果缩略图网格;没有结果时提示选中查看。
const urls = outThumbsFor(n) || []
if (urls.length) {
const cols = 2
const gap = 4
const cw = Math.max(1, (iw - gap) / cols)
const ch = cw * 0.75
for (let i = 0; i < Math.min(4, urls.length); i++) {
const col = i % cols, row = Math.floor(i / cols)
const x0 = ix + col * (cw + gap), y0 = iy + row * (ch + gap)
const entry = imageOf(imageFor(n, urls[i]), onImageLoad)
ctx.fillStyle = css('--iwb-layer2', '#f1f2f4')
roundRect(ctx, x0, y0, cw, ch, 6); ctx.fill()
if (entry && entry.loaded && !entry.failed) {
try { ctx.drawImage(entry.img, x0, y0, cw, ch) } catch (e) { /* ignore */ }
}
}
} else {
ctx.fillStyle = text
ctx.font = Math.max(10, 12 / scale * 0.9) + 'px -apple-system, BlinkMacSystemFont, "PingFang SC", sans-serif'
ctx.fillText('选中查看结果', ix + 2, iy + Math.max(14, 16 / scale))
}
} else if (n.type === 'layer') {
// 分层节点:画层列表;选中后由 NodeCard 负责完整图层操作。
const layers = (n.data && Array.isArray(n.data.layers)) ? n.data.layers : []
ctx.fillStyle = text
ctx.font = Math.max(10, 12 / scale * 0.9) + 'px -apple-system, BlinkMacSystemFont, "PingFang SC", sans-serif'
const lh = Math.max(14, 20 / scale)
let yy = iy + Math.max(14, 18 / scale)
for (let i = 0; i < Math.min(8, layers.length); i++) {
const name = String((layers[i] && layers[i].name) || ('图层 ' + (i + 1)))
ctx.fillText(name, ix + 2, yy)
yy += lh
if (yy > iy + ih) break
}
if (!layers.length) ctx.fillText('选中查看分层', ix + 2, iy + Math.max(14, 16 / scale))
} else {
// P2 文本节点:画截断文本,选中后由 NodeCard 负责编辑。
ctx.save()
ctx.beginPath(); ctx.rect(ix, iy, iw, ih); ctx.clip()
ctx.fillStyle = text
ctx.font = Math.max(10, 12 / scale * 0.9) + 'px -apple-system, BlinkMacSystemFont, "PingFang SC", sans-serif'
const rawText = String((n.data && (n.data.text || n.data.prompt || n.data.title)) || '')
const lineH = Math.max(12, 18 / scale)
const maxW = Math.max(20, iw - 4)
let line = ''
let ty = iy + Math.max(14, 16 / scale)
for (const ch of rawText) {
const next = line + ch
if (ctx.measureText(next).width > maxW && line) {
ctx.fillText(line, ix + 2, ty); ty += lineH; line = ch
if (ty > iy + ih) break
} else line = next
}
if (line && ty <= iy + ih) ctx.fillText(line, ix + 2, ty)
ctx.restore()
}
// 端口:ref 的 canvas 命中;P2 文本节点先只做 body 命中。
if (n.type === 'ref') {
const portR = Math.max(2, 4 / scale)
ctx.fillStyle = bg
ctx.strokeStyle = border
ctx.lineWidth = 1 / scale
for (const [px, py] of [[x, y + nh / 2], [x + nw, y + nh / 2]]) {
ctx.beginPath(); ctx.arc(px, py, portR, 0, Math.PI * 2); ctx.fill(); ctx.stroke()
}
}
void accent
}
if (t0) { perf.lastMs = (typeof performance !== 'undefined' && performance.now ? performance.now() : t0) - t0; perf.frames++ }
}
// 单帧绘制失败不能冒泡到 React effect;记录后保留上一帧,下一帧重试。
function draw (canvas, o) {
try {
drawUnsafe(canvas, o)
perf.lastError = ''
} catch (e) {
perf.lastError = String((e && e.message) || e)
}
}
function CanvasNodeLayer (props) {
const ref = useRef(null)
const latest = useRef(props)
latest.current = props
const [rev, setRev] = useState(0)
void rev
useEffect(() => {
const canvas = ref.current
if (!canvas) return
const p = latest.current || {}
draw(canvas, Object.assign({}, p, { onImageLoad: () => setRev((v) => v + 1) }))
if (typeof p.onReady === 'function') {
p.onReady(function (x, y, scale) {
const q = latest.current || {}
draw(canvas, Object.assign({}, q, { viewport: { x: x, y: y, scale: scale }, onImageLoad: () => setRev((v) => v + 1) }))
})
}
})
useEffect(() => () => { if (typeof props.onReady === 'function') props.onReady(null) }, [])
return el('canvas', { className: 'iwb-node-canvas', 'aria-hidden': 'true', ref: ref })
}
function stats () { return { drawMs: perf.lastMs, frames: perf.frames, images: imgCache.size, error: perf.lastError || '' } }
global.IWBCanvasV3NodeLayer = { CanvasNodeLayer, draw, stats }
})(typeof window !== 'undefined' ? window : globalThis)