/* 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, wOutNameOf, 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 wOutNameOf = d.wOutNameOf 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), ) } // 底栏「插件节点」入口:拼图图标 + 点开列出所有插件节点(2026-11-26) function PluginAddButton(props) { const [open, setOpen] = useState(false) const boxRef = useRef(null) useEffect(() => { if (!open) return undefined const onDoc = (e) => { if (boxRef.current && !boxRef.current.contains(e.target)) setOpen(false) } const onKey = (e) => { if (e.key === 'Escape') setOpen(false) } document.addEventListener('pointerdown', onDoc, true) document.addEventListener('keydown', onKey) return () => { document.removeEventListener('pointerdown', onDoc, true); document.removeEventListener('keydown', onKey) } }, [open]) const list = (Array.isArray(props.variants) ? props.variants : []).filter((pv) => pv && pv.toolbar !== 'hide') return el('span', { className: 'iwb-plugin-add-wrap', ref: boxRef }, el('button', { className: 'iwb-btn iwb-plugin-add' + (open ? ' iwb-btn-on' : ''), 'data-tip': '插件节点(相册 / 网页 / 样式…)', 'aria-label': '插件节点', 'aria-haspopup': 'menu', 'aria-expanded': open ? 'true' : 'false', onPointerDown: (e) => e.stopPropagation(), onClick: () => setOpen((x) => !x), }, I('puzzle')), open ? el('div', { className: 'iwb-plugin-add-menu', role: 'menu' }, list.map((pv) => el('button', { key: pv.id, className: 'iwb-ctx-item', role: 'menuitem', onClick: () => { setOpen(false); if (typeof props.onPick === 'function') props.onPick(pv.id) }, }, I(pv.icon || 'puzzle'), el('span', { className: 'iwb-btn-text' }, pv.title || pv.id))), ) : 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')), // 插件节点入口(2026-11-26):拼图图标按钮 + 弹出列表。 // 不用文字下拉(用户裁定:插件入口只用图标),也不用弹层库:一个按钮 + 一个绝对定位列表即可。 (Array.isArray(props.pluginVariants) && props.pluginVariants.length) ? el(PluginAddButton, { variants: props.pluginVariants, onPick: props.onAddPlugin, I }) : null, ), // 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' : '') // 双击连线 = 断开连线:这是用户明确要保留的操作习惯(2026-11-28 确认),不要删。 const hnd = { onPointerDown: (e) => { e.stopPropagation(); onSelect(ed.id) }, onDoubleClick: (e) => { e.stopPropagation(); onDelete(ed.id) }, onPointerEnter: () => { if (typeof props.onHover === 'function') props.onHover(ed.id) }, onPointerLeave: () => { if (typeof props.onHover === 'function') props.onHover('') }, } return el('g', { 'data-edge-id': ed.id }, el('path', { key: ed.id + '_hit', className: 'iwb-edge-hit', d, fill: 'none', ...hnd }), // 视觉由 canvas 层画;保留一个 display:none 的旧路径节点给 e2e/选择器兼容(不参与绘制)。 el('path', { key: ed.id, className: cls, d, fill: 'none', style: props.visual === false ? { display: 'none' } : undefined, title: '点击选中(Delete 断开)· 双击直接断开', ...hnd }), ) } function ImagePreview(props) { const list = (props.list && props.list.length) ? props.list : (props.src ? [props.src] : []) const maxIdx = Math.max(0, list.length - 1) // v3.26.109:下标由预览自己持有 —— 以前每切一张都 setPreview(...),会把整个 Workbench 重渲染一遍, // 连续滚轮时这就是每步的固定开销。props.idx 只在「换了一份列表」时作为初始值。 try { window.IWBPerf && window.IWBPerf.tag('preview') } catch (e) { /* ignore */ } const [idx, setIdx] = useState(() => Math.max(0, Math.min(props.idx || 0, maxIdx))) const entry = list[idx] // 当前显示用 URL:缩略图先出(秒显),空闲后再换原图;初值空串,由下面 effect 填入 const [cur, setCur] = useState('') // 原图叠层:不复用 直接替换 —— 换 src 必然整体重绘,观感是「小图糊一遍、大图再清一遍」。 // 现在缩略图当前景底图,原图解码完成后浮在上面淡入,观感是「同一张图逐渐变清晰」。 const [top, setTop] = useState('') const [topIn, setTopIn] = useState(false) // 显示框宽高比:缩略图自然尺寸只有 320px,若让 用 width:auto,会先显示成一张小图、 // 等原图到了再撑大 —— 尺寸跳变。这里先按比例算出**最终框**,两层都填满它,位置与大小全程不变。 const [ratio, setRatio] = useState(() => (entry && entry.w > 0 && entry.h > 0) ? (entry.w / entry.h) : 0) // 底图是 320px 放大,像素块很明显。等原图期间给它加糊,视觉上是「虚 → 实」而不是「马赛克 → 实」。 // 原图确实取不到(旧数据/图床)就把糊去掉,宁可看马赛克也别永久糊着。 const [noOrig, setNoOrig] = useState(false) // 原图淡入完成后撤掉底图的模糊 + 放大(已被完全盖住,撤掉只为不留无用的滤镜与越界尺寸) const [sharp, setSharp] = useState(false) const ratioCacheRef = useRef(new Map()) // 条目 key -> 宽高比:滚回来时立刻有框,不用再等 onLoad const wheelRef = useRef(null) const baseImgRef = useRef(null) const wheelAtRef = useRef(0) const seqRef = useRef(0) // 切图序号:新的一步让旧请求的结果作废(可取消) const upgradeTimerRef = useRef(0) // 空闲升原图的定时器 const prefetchRef = useRef(0) // 停稳后预取邻张原图(只进缓存,不上屏) // 缓存策略(按「图片浏览器」分工): // · 缩略图 21KB/张 ⇒ 常驻,滚动回看直接命中,不再读盘; // · 原图 1.9MB/张 ⇒ 只留最近 10 张,滚动时不断产生/回收会成为新的抖动源。 // 双上限:张数 + 字节。用户反馈「不卡了但内存偏高」——解码位图与 Blob 都常驻, // 只按张数计会在 6MB 大图上失控,所以再加一层字节预算(原图 24MB / 缩略图 8MB)。 const CACHE_ORIG_MAX = 4 const CACHE_THUMB_MAX = 300 const CACHE_ORIG_BYTES = 12 * 1024 * 1024 const CACHE_THUMB_BYTES = 6 * 1024 * 1024 const urlsRef = useRef(new Map()) // key -> { url, own } const orderRef = useRef([]) 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 = [] } // 缓存项同时记住原 Blob:预览里的「复制/下载」要拿真字节。 // 不能只把 objectURL 丢给 wBlobFromSrc —— 线上 CSP connect-src 'self' https: 会拦 fetch(blob:)。 const remember = (key, url, blob, kind) => { const size = (blob && typeof blob.size === 'number') ? blob.size : 0 urlsRef.current.set(key, { url, own: true, blob: blob || null, kind: kind || 'orig', size }) orderRef.current.push(key) // 同类淘汰:先按张数,再按字节,从最老的开始(缩略图 21KB 级,原图 1.9MB 级) const tune = (isThumb) => { const maxCount = isThumb ? CACHE_THUMB_MAX : CACHE_ORIG_MAX const maxBytes = isThumb ? CACHE_THUMB_BYTES : CACHE_ORIG_BYTES let count = 0 let bytes = 0 for (const k of orderRef.current) { const it = urlsRef.current.get(k) if (!it || (it.kind === 'thumb') !== isThumb) continue count++; bytes += it.size || 0 } for (const k of orderRef.current.slice()) { if (count <= maxCount && bytes <= maxBytes) break const it = urlsRef.current.get(k) if (!it || (it.kind === 'thumb') !== isThumb) continue count--; bytes -= (it.size || 0) releaseKey(k) } } tune(false) tune(true) return url } const cachedOf = (key) => { const hit = urlsRef.current.get(key); return hit ? hit.url : '' } const cachedBlobOf = (key) => { const hit = urlsRef.current.get(key); return (hit && hit.blob) ? hit.blob : null } const entryKeyOf = (e) => 'out:' + (e.origIdb || '') + '|' + (e.idb || '') + '|' + (e.url || '') + '|' + (e.name || '') const placeholderOf = (e) => (typeof e === 'string' ? e : ((e && (e.thumb || e.url)) || '')) // 把 IDB 取回的值统一转成 能用的 URL:Blob → objectURL;dataURL → Blob → objectURL const urlOfValue = (v, key, kind) => { if (!v) return Promise.resolve('') if (typeof v === 'object' && typeof v.size === 'number') { try { return Promise.resolve(remember(key, URL.createObjectURL(v), v, kind)) } catch (e) { return Promise.resolve('') } } const s = String(v) if (s.indexOf('data:') !== 0) return Promise.resolve(s) // 图床/本地 URL 直接用 return wBlobFromDataUrl(s).then((b) => { if (!b) return '' try { return remember(key, URL.createObjectURL(b), b, kind) } catch (e) { return '' } }).catch(() => '') } // 兜底:只有 dataURL / http(s) 字符串时也要给出可显示 URL。 // 图库条目在「没落 idb 键」的旧数据/夹具里只有 data: 缩略图 —— 以前这条路会把 dataURL 解成 Blob // 再 createObjectURL(预览里检测到的 src 是 blob:),这里保留同一语义,别退回 data: 直挂。 const urlOfFallback = (str, key, kind) => { if (!str) return Promise.resolve('') const sv = String(str) if (sv.indexOf('data:') !== 0) return Promise.resolve(sv) // 内容签名做键:同一张 dataURL 被缩略图/原图两条路请求时只解一次 const fkey = 'fb:' + sv.length + ':' + sv.slice(0, 24) + sv.slice(-12) const hit = cachedOf(fkey) if (hit) return Promise.resolve(hit) return wBlobFromDataUrl(sv).then((b) => { if (!b) return '' try { return remember(fkey, URL.createObjectURL(b), b, kind) } catch (e) { return '' } }).catch(() => '') } // 小图(缩略图):先出画面。desktop 下 IDB.get 可能是 dataURL(几万字节),也可能直接是 Blob const loadThumb = (e) => { if (!e || typeof e === 'string' || !e.__gallery) return Promise.resolve(placeholderOf(e)) const key = 'thumb:' + entryKeyOf(e) const hit = cachedOf(key); if (hit) return Promise.resolve(hit) if (!e.idb) return urlOfFallback(placeholderOf(e), key, 'thumb') return Promise.resolve(IDB.get(e.idb)) .then((v) => urlOfValue(v, key, 'thumb')) .then((u) => u || urlOfFallback(placeholderOf(e), key, 'thumb')) .catch(() => urlOfFallback(placeholderOf(e), key, 'thumb')) } // 原图:优先 getBlob(字节直出 Blob,不再 base64 往返);老存储退回到 dataURL 路径 const loadOriginal = (e) => { if (!e || typeof e === 'string' || !e.__gallery) return Promise.resolve(placeholderOf(e)) const key = 'orig:' + entryKeyOf(e) const hit = cachedOf(key); if (hit) return Promise.resolve(hit) // 2026-12-03(用户裁定「本地优先」):没有 origIdb 的老记录,直接按行名读 images/gallery 原图(原生解码), // 不再退回 320 缩略图、也不直连远程;返回的是宿主持有的 objectURL,不进本组件的回收表。 const SF = (typeof window !== 'undefined') ? window.IWBStorageFile : null if (!e.origIdb && e.name && SF && typeof SF.galleryOriginalOf === 'function') { return Promise.resolve(SF.galleryOriginalOf({ name: e.name, origIdb: e.origIdb }, 2048)) .then((g) => (g && g.url) || '') .catch(() => '') .then((u) => u || urlOfFallback(e.url || placeholderOf(e), key, 'orig')) } const idbKey = e.origIdb || e.idb if (!idbKey) return urlOfFallback(e.url || placeholderOf(e), key, 'orig') const p = (typeof IDB.getBlob === 'function') ? IDB.getBlob(idbKey) : IDB.get(idbKey) return Promise.resolve(p) .then((v) => urlOfValue(v, key, 'orig')) .then((u) => u || urlOfFallback(e.url || placeholderOf(e), key, 'orig')) .catch(() => urlOfFallback(e.url || placeholderOf(e), key, 'orig')) } // 取原图**字节**(复制/下载用)。命中缓存直接给 Blob;否则走 getBlob / dataURL 解码。 // 与 loadOriginal 分开:显示只要 URL,剪贴板/另存要 Blob,两条路径都不要 fetch(blob:)。 const loadOriginalBlob = (e) => { if (!e || typeof e === 'string' || !e.__gallery) return Promise.resolve(null) const key = 'orig:' + entryKeyOf(e) const hit = cachedBlobOf(key) if (hit) return Promise.resolve(hit) // 只有 dataURL(旧数据/夹具、图床条目)时直接解出字节 const asBlobOf = (v) => { if (!v) return null if (typeof v === 'object' && typeof v.size === 'number') return v const str = String(v) if (str.indexOf('data:') !== 0) return null return wBlobFromDataUrl(str) } const fallbackStr = e.url || placeholderOf(e) const SF2 = (typeof window !== 'undefined') ? window.IWBStorageFile : null if (!e.origIdb && e.name && SF2 && typeof SF2.galleryOriginalBlob === 'function') { return Promise.resolve(SF2.galleryOriginalBlob({ name: e.name, origIdb: e.origIdb })).then((b) => b || null).catch(() => null) } const idbKey = e.origIdb || e.idb if (!idbKey) return Promise.resolve(asBlobOf(fallbackStr)).then((b) => ((b && b.size) ? b : null)).catch(() => null) const p = (typeof IDB.getBlob === 'function') ? IDB.getBlob(idbKey) : IDB.get(idbKey) return Promise.resolve(p).then((v) => { const b = asBlobOf(v) if (b) return b return Promise.resolve(asBlobOf(fallbackStr)) }).then((b) => ((b && typeof b.size === 'number') ? b : null)).catch(() => null) } // 先把原图解码完成再往上叠:否则叠层出现的瞬间浏览器还在解码,仍会掉帧/闪一下白 const preloadDecoded = (u) => new Promise((resolve) => { if (!u) { resolve(''); return } try { const im = new Image() im.onload = () => resolve(u) im.onerror = () => resolve('') im.src = u } catch (e) { resolve('') } }) const entryKeyStr = (typeof entry === 'string') ? ('s:' + entry.length + ':' + entry.slice(0, 32)) : (entry ? entryKeyOf(entry) : '') // 邻张预取:只在停稳后做(滚动中预取等于白读),只进 objectURL 缓存、不改变当前显示 const prefetchAround = (i) => { clearTimeout(prefetchRef.current) if (list.length < 2) return prefetchRef.current = setTimeout(() => { const nb = [list[(i + 1) % list.length], list[(i - 1 + list.length) % list.length]] for (const e of nb) { try { loadOriginal(e).catch(() => '') } catch (err) { /* ignore */ } } }, 400) } const go = (delta) => { if (list.length < 2) return; setIdx((i) => (i + delta + list.length) % list.length) } // 滚轮切图:passive 监听 —— 预览层自己不会滚动,之前用非 passive + preventDefault // 会让合成器每个 wheel 事件都等主线程,主线程一忙整块界面就“卡住”。 useEffect(() => { const host = wheelRef.current if (!host || list.length < 2) return const onWheel = (e) => { if (!e.deltaY) return const now = Date.now() if (now - wheelAtRef.current < 140) return wheelAtRef.current = now go(e.deltaY > 0 ? 1 : -1) } host.addEventListener('wheel', onWheel, { passive: true }) return () => { try { host.removeEventListener('wheel', onWheel) } catch (e) { /* ignore */ } } }, [list.length, idx]) // 换列表(新一轮预览)时回到 props.idx useEffect(() => { setIdx(Math.max(0, Math.min(props.idx || 0, Math.max(0, list.length - 1)))) }, [list]) // 当前张:先用缩略图秒出画面;连续滚轮期间不做重活,停 300ms 空闲后再把原图换上来 useEffect(() => { const my = ++seqRef.current const live = () => seqRef.current === my resolvedRef.current = '' setTop('') setTopIn(false) setNoOrig(false) setSharp(false) // 已知来源优先;都没有就**沿用上一张的比例**(宁可短暂套错比例,也不要退回 320px 小图) const known = ratioCacheRef.current.get(entryKeyStr) || ((entry && entry.w > 0 && entry.h > 0) ? (entry.w / entry.h) : 0) if (known) setRatio(known) setCur(placeholderOf(entry)) loadThumb(entry).then((u) => { if (live() && u) setCur(u) }).catch(() => {}) // 关键:滚动中**一张原图都不读**。每步读 1.9MB 会在快速滑动时堆成 IO 风暴(用户实测「卡住」)。 // 现在只有停手 120ms 才发起原图读取;滚动过程只命中常驻的 21KB 缩略图缓存。 clearTimeout(upgradeTimerRef.current) upgradeTimerRef.current = setTimeout(() => { loadOriginal(entry).then((u) => { if (!live()) return null if (!u) { setNoOrig(true); return null } resolvedRef.current = u return preloadDecoded(u).then((ok) => { if (!live() || !ok) return setTop(ok) // 下一帧再打开过渡,保证从 opacity:0 起算(同帧设置会被合并成“直接出现”) requestAnimationFrame(() => { if (seqRef.current === my) setTopIn(true) }) prefetchAround(idx) }) }).catch(() => { if (live()) setNoOrig(true) }) }, 120) return () => { clearTimeout(upgradeTimerRef.current); clearTimeout(prefetchRef.current) } }, [idx, list.length, entryKeyStr]) useEffect(() => { if (!topIn) return undefined const t = setTimeout(() => setSharp(true), 260) // 略大于 220ms 淡入 return () => clearTimeout(t) }, [topIn]) // onLoad 兜底:src 命中缓存(dataURL / 已解码的 objectURL)时,图片可能在 React 绑定回调前就 complete, // onLoad 永远不触发 —— 比例学不到,框就定不下来,又退回 320px 小图。每次换 src 都补查一次 complete。 useEffect(() => { const img = baseImgRef.current if (!img || !img.complete || !img.naturalWidth || !img.naturalHeight) return const r = img.naturalWidth / img.naturalHeight if (entryKeyStr) ratioCacheRef.current.set(entryKeyStr, r) if (Math.abs(r - ratio) > 0.005) setRatio(r) }, [cur, 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) }, [list.length, idx]) if (!list.length) return null const src = cur || placeholderOf(entry) // 框宽度按比例取「92vw 与 88vh·比例」的较小值,高度由 aspect-ratio 推出,永远不超 88vh const stageStyle = ratio > 0 ? { width: 'min(92vw, calc(88vh * ' + ratio.toFixed(5) + '))', maxWidth: '92vw', maxHeight: '88vh', aspectRatio: String(ratio) } : null // 图没报 w/h 时,用缩略图加载完后的自然尺寸补上(缩略图与原图同比例) const onBaseLoad = (e) => { const img = e && e.currentTarget const nw = img && img.naturalWidth const nh = img && img.naturalHeight if (!nw || !nh) return const r = nw / nh if (entryKeyStr) ratioCacheRef.current.set(entryKeyStr, r) if (Math.abs(r - ratio) > 0.005) setRatio(r) } // 复制源:优先「本地已解析源」(原图 objectURL / 缩略图 dataURL),远程 http(s) 只作最后回退, // 避免 fetch 远程图床被 CORS 拦下。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', ref: wheelRef, 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('div', { className: 'iwb-prev-stage' + (stageStyle ? ' is-sized' : '') + ((stageStyle && !noOrig && !sharp) ? ' is-blur' : ''), style: stageStyle || undefined }, el('img', { ref: baseImgRef, src, alt: '预览', style: stageStyle ? { width: '100%', height: '100%' } : undefined, onLoad: onBaseLoad, onClick: (e) => e.stopPropagation(), onKeyDown: () => {}, }), top ? el('div', { className: 'iwb-prev-layer' + (topIn ? ' is-in' : ''), style: { backgroundImage: 'url("' + top + '")' }, onClick: (e) => e.stopPropagation(), }) : null, ), 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),不再各写一份。 // 先取原图**字节**(不是 URL):CSP 禁 fetch(blob:),只有真 Blob 才稳;占位缩略图只作兜底。 const blob = await loadOriginalBlob(entry).catch(() => null) await copyImageToClipboard(blob || 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) // downloadUrl 只吃 URL:把字节登记成**可取回**的 objectURL(wBlobRefGet 能反查),否则下载链路取不到 Blob const blob = await loadOriginalBlob(entry).catch(() => null) const blobUrl = (blob && typeof wRegisterBlobUrl === 'function') ? wRegisterBlobUrl(blob) : '' // 2026-12-03:预览下载同样走图库行名(图库条目直接用行名,其余按 url 查),未落地才回退 image.png const dlName = (entry && entry.__gallery && entry.name) ? String(entry.name) : ((typeof wOutNameOf === 'function' && wOutNameOf(entry && entry.url)) || 'image.png') downloadUrl(blobUrl || src, dlName) }, }, I('download'), ' 下载'), ), ) } global.IWBUICanvasView = { inject, I, Minimap, ToolbarBottom, EdgePath, ImagePreview } })(typeof window !== 'undefined' ? window : globalThis)