feat(release): v3.26.109 —— 内存/流畅度收敛 + 参考图修复 + 插件 sticky 1.0.10

- 内存:首帧前预热显示缩略图(避免整屏解码原图)、带图节点视口裁剪 240→80、
  DISPLAY_THUMB_MAX 640→1024、放大后不再切原图解码(上限 2× 缩略图长边)
- 参考图:修复 url 引用对象未解析导致的 [object Object] 破图;失效图改为明确占位(双击重新导入)
- 新增 {__cache}→{__blob} 迁移(只迁移可读字节,读不到不动)
- 图片节点按图片比例收边、内边距收窄
- 诊断:帧时长探针(正式包默认关闭,IWB_PERF_PROBE=1 才启用)、edge-drop 换板误报过滤、缓存计数
- 插件 sticky 1.0.10:移除左侧栏面板
This commit is contained in:
qiqi committed 2026-11-29 20:53:16 +08:00
1 parent 5ed1172064
commit 24eb1b69c9
23 files changed
+595 -193

No files matched your search

+11 -18
View File
@@ -2728,6 +2728,8 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct
} }
} catch (e) { /* 护栏失败不影响加载 */ } } catch (e) { /* 护栏失败不影响加载 */ }
try { if (CrashLog && CrashLog.breadcrumb) CrashLog.breadcrumb('board-load', String(w.id) + ' nodes=' + ((w.nodes || []).length) + ' loaded=' + wLoadedBoards.length + (reason ? ' via=' + reason : '')) } catch (e) { /* ignore */ } try { if (CrashLog && CrashLog.breadcrumb) CrashLog.breadcrumb('board-load', String(w.id) + ' nodes=' + ((w.nodes || []).length) + ' loaded=' + wLoadedBoards.length + (reason ? ' via=' + reason : '')) } catch (e) { /* ignore */ }
try { if (typeof window !== 'undefined' && window.IWBPerf) window.IWBPerf.tag('board') } catch (e) { /* ignore */ }
try { const MG = (typeof window !== 'undefined') ? window.IWBImageCacheMigrate : null; if (MG && typeof MG.once === 'function') MG.once(w, { read: iwbCacheRead, write: wImgRefWrite, bump: wImgUrlBump }).then(function (r) { try { if (r && r.total) { const S = (typeof window !== 'undefined') ? window.IWBStorageFile : null; if (S && S.logLine) S.logLine('cache-migrate ' + String(w.id) + ' ok=' + r.ok + ' fail=' + r.fail + ' total=' + r.total) } } catch (e) { /* ignore */ } }).catch(function () { /* ignore */ }) } catch (e) { /* 迁移失败不影响装载 */ }
return w return w
} }
async function wEvictLoadedBoards(keepIds, list, keepMax, sessionAware) { async function wEvictLoadedBoards(keepIds, list, keepMax, sessionAware) {
@@ -4862,7 +4864,7 @@ const tbCenterSeed = (type, refs) => {
// 只对**本地已有数据**(base64/dataURL)生成小图(同源,无 CORS 风险);远程 URL 原样返回 // 只对**本地已有数据**(base64/dataURL)生成小图(同源,无 CORS 风险);远程 URL 原样返回
// (跨域图无法安全缩放,浏览器也会因 canvas 污染拒绝 toDataURL)。 // (跨域图无法安全缩放,浏览器也会因 canvas 污染拒绝 toDataURL)。
// 首帧仍用原图(不会闪空图),小图就绪后由 wThumbBump 触发一次 re-render 换成小图。 // 首帧仍用原图(不会闪空图),小图就绪后由 wThumbBump 触发一次 re-render 换成小图。
const DISPLAY_THUMB_MAX = 640 // v3.26.34:768→640(见 image-display-thumb.js 注释) const DISPLAY_THUMB_MAX = 1024 // v3.26.109:640→1024。实测 WebContent footprint 1.2G/峰值 2.7G,主因是 LOD 判定 need=长边×缩放×dpr 超过 640 就解码原图(dpr=2 时节点宽 400px 就命中)。放大到 1024 后多数缩放档留在缩略图上
const DISPLAY_THUMB_CACHE_MAX = 300 const DISPLAY_THUMB_CACHE_MAX = 300
const displayThumbs = new Map() const displayThumbs = new Map()
const displayThumbPending = new Set() const displayThumbPending = new Set()
@@ -4940,7 +4942,7 @@ const tbCenterSeed = (type, refs) => {
const d = n && n.data const d = n && n.data
if (!d) continue if (!d) continue
const stable = wDisplayThumbKeyOf(d.data) const stable = wDisplayThumbKeyOf(d.data)
const v = wResolveImg(d.data) || d.url const v = wResolveImg(d.data) || wResolveImg(d.url)
if (!v || typeof v !== 'string' || v.indexOf('data:') === 0) continue if (!v || typeof v !== 'string' || v.indexOf('data:') === 0) continue
const key = stable || wDisplayThumbKey(v) const key = stable || wDisplayThumbKey(v)
if (!key || displayThumbs.has(key) || keys.indexOf(key) >= 0) continue if (!key || displayThumbs.has(key) || keys.indexOf(key) >= 0) continue
@@ -5039,6 +5041,9 @@ const tbCenterSeed = (type, refs) => {
try { out.tasksMB = wMB(wStrBytesOf((refs && refs.tasks) || [])) } catch (e) { out.tasksMB = -1 } try { out.tasksMB = wMB(wStrBytesOf((refs && refs.tasks) || [])) } catch (e) { out.tasksMB = -1 }
try { out.genRuns = refs && refs.genRuns ? refs.genRuns.size : 0; out.genRunsMB = wMB(wStrBytesOf(refs && refs.genRuns ? Array.from(refs.genRuns.values()) : [])) } catch (e) { out.genRunsMB = -1 } try { out.genRuns = refs && refs.genRuns ? refs.genRuns.size : 0; out.genRunsMB = wMB(wStrBytesOf(refs && refs.genRuns ? Array.from(refs.genRuns.values()) : [])) } catch (e) { out.genRunsMB = -1 }
try { out.thumbsMB = wMB(wStrBytesOf(Array.from(outThumbCache.values()))) } catch (e) { out.thumbsMB = -1 } try { out.thumbsMB = wMB(wStrBytesOf(Array.from(outThumbCache.values()))) } catch (e) { out.thumbsMB = -1 }
// 计数(objectURL 只有几十字符,按字符串量永远是 0 —— 这两行才是缓存的真实规模)
try { out.thumbsN = outThumbCache.size } catch (e) { out.thumbsN = -1 }
try { out.displayThumbsN = displayThumbs.size } catch (e) { out.displayThumbsN = -1 }
try { out.displayThumbsMB = wMB(wStrBytesOf(Array.from(displayThumbs.values()))) } catch (e) { out.displayThumbsMB = -1 } try { out.displayThumbsMB = wMB(wStrBytesOf(Array.from(displayThumbs.values()))) } catch (e) { out.displayThumbsMB = -1 }
try { out.groupsMB = wMB(wStrBytesOf(((refs && refs.groupSnapshots) || (refs && refs.savedGroups)) || [])) } catch (e) { out.groupsMB = -1 } try { out.groupsMB = wMB(wStrBytesOf(((refs && refs.groupSnapshots) || (refs && refs.savedGroups)) || [])) } catch (e) { out.groupsMB = -1 }
try { out.clipboardMB = wMB(wStrBytesOf(lsRawGet('iwb_clipboard', '') || '')) } catch (e) { out.clipboardMB = -1 } try { out.clipboardMB = wMB(wStrBytesOf(lsRawGet('iwb_clipboard', '') || '')) } catch (e) { out.clipboardMB = -1 }
@@ -6705,7 +6710,7 @@ const tbCenterSeed = (type, refs) => {
persistWs(list, id) persistWs(list, id)
} }
// ctx 在 **effect 执行时** 求值(渲染期求值会撞后声明 const 的 TDZ) // ctx 在 **effect 执行时** 求值(渲染期求值会撞后声明 const 的 TDZ)
const bootCtx = () => ({ APP_VERSION, CanvasStore, CrashLog, RuntimeMetrics, RuntimeRecovery, W_PURGE_ORIG_FLAG, activeWsIdRef, api, commitCanvas, displayThumbs, doFit, historySnapshotBytes, historyStore, hydrateAndReload, loadDemo, loadSavedGroups, lsGet, lsRawGet, lsRawSet, lsRemove, lsSet, migrateGenTaskIds, normalizeEdges, normalizeGroups, normalizeNodes, openTab, openTabsRef, outThumbCache, refreshOutputs, refs, setActiveWsId, setConfig, setLoaded, setMemUi, setPromptGroups, setPrompts, setResumePrompt, setServer, setWorkspaces, setWsRev, showToast, wDiagStats, wEvictLoadedBoards, wLoadedBoards, wMemoryComposition, wPurgeOutputOriginals, wSafeCompressStart }) const bootCtx = () => ({ APP_VERSION, CanvasStore, CrashLog, RuntimeMetrics, RuntimeRecovery, W_PURGE_ORIG_FLAG, activeWsIdRef, api, commitCanvas, displayThumbs, doFit, historySnapshotBytes, historyStore, hydrateAndReload, loadDemo, loadSavedGroups, lsGet, lsRawGet, lsRawSet, lsRemove, lsSet, migrateGenTaskIds, normalizeEdges, normalizeGroups, normalizeNodes, openTab, openTabsRef, outThumbCache, refreshOutputs, refs, setActiveWsId, setConfig, setLoaded, setMemUi, setPromptGroups, setPrompts, setResumePrompt, setServer, setWorkspaces, setWsRev, showToast, wDiagStats, wEvictLoadedBoards, wLoadedBoards, wMemoryComposition, wPreloadDisplayThumbs, wPurgeOutputOriginals, wSafeCompressStart })
IWBBootLoad.useBootLoad(bootCtx) IWBBootLoad.useBootLoad(bootCtx)
// ── 自动同步(applyLatest / syncOnce / 轮询 + BroadcastChannel)已外移到 src/runtime-workbench-logic.js(2026-11-06)── // ── 自动同步(applyLatest / syncOnce / 轮询 + BroadcastChannel)已外移到 src/runtime-workbench-logic.js(2026-11-06)──
@@ -7179,21 +7184,9 @@ const tbCenterSeed = (type, refs) => {
}, [edges, nodes]) }, [edges, nodes])
// 视口裁剪:大画布只渲染可见节点/连线/组(jsdom 无实际画布尺寸时全渲染,兼容测试) // 视口裁剪:大画布只渲染可见节点/连线/组(jsdom 无实际画布尺寸时全渲染,兼容测试)
// 视口裁剪矩形(useMemo:拖动时 viewport 不变则复用,避免每帧算除法) // 视口裁剪矩形(useMemo:拖动时 viewport 不变则复用,避免每帧算除法)
const cullRect = React.useMemo(() => (canvasSize.w && canvasSize.h) ? { // 视口裁剪:宽边距 240(纯文本节点),带图节点 80 —— 见 CanvasGeometry.cullRectsOf 注释
left: -viewport.x / viewport.scale - 240, const cullRects = React.useMemo(() => CanvasGeometry.cullRectsOf(canvasSize, viewport), [canvasSize.w, canvasSize.h, viewport.x, viewport.y, viewport.scale])
top: -viewport.y / viewport.scale - 240, const nodeVisible = (n) => CanvasGeometry.nodeVisibleIn(n, cullRects, { drag: refs.drag, resize: refs.resize, sel: sel, widthOf: nodeWidth, heightOf: hOf })
right: (canvasSize.w - viewport.x) / viewport.scale + 240,
bottom: (canvasSize.h - viewport.y) / viewport.scale + 240,
} : null, [canvasSize.w, canvasSize.h, viewport.x, viewport.y, viewport.scale])
const nodeVisible = (n) => {
if (!cullRect) return true
if (refs.drag && refs.drag.start && refs.drag.start[n.id] != null) return true
if (refs.resize && refs.resize.nodeId === n.id) return true
if (sel.includes(n.id)) return true
const nw = nodeWidth(n)
const nh = hOf(n)
return n.x < cullRect.right && n.x + nw > cullRect.left && n.y < cullRect.bottom && n.y + nh > cullRect.top
}
const visibleIds = new Set(nodes.filter(nodeVisible).map((n) => n.id)) const visibleIds = new Set(nodes.filter(nodeVisible).map((n) => n.id))
try { wSetScaleNow(viewport.scale) } catch (e) { /* ignore */ } try { wSetScaleNow(viewport.scale) } catch (e) { /* ignore */ }
+9 -8
View File
@@ -17,12 +17,12 @@
## 1. 速查(30 秒版) ## 1. 速查(30 秒版)
- 渲染是 **DOM-per-node**(不是 canvas 绘制);**视口裁剪已存在**,余量 **240px** (A) `app.js:12656-12659`。 - 渲染是 **DOM-per-node**(不是 canvas 绘制);**视口裁剪已存在**,余量 **240px**(v3.26.109 起带图节点收紧到 **80px**,见下) (A) `src/canvas-geometry.js` `cullRectsOf`。
- **平移 = 每帧 `setViewport`**;**拖动 = 直接写 DOM transform、不 `setNodes`**。**这两条不许互换**(见 §9)。 - **平移 = 每帧 `setViewport`**;**拖动 = 直接写 DOM transform、不 `setNodes`**。**这两条不许互换**(见 §9)。
- 图片**新写入主通道 = IndexedDB Blob `{__blob}` / key `imgblob_<hash>_<len>`** (A) `app.js:2143`;`{__cache}`(Cache Storage)为兜底;\`ref_\`(`app.js` 内定义的 `IDB_REF_PREFIX = 'ref_'`)为 legacy 形态 (A)。 - 图片**新写入主通道 = IndexedDB Blob `{__blob}` / key `imgblob_<hash>_<len>`** (A) `app.js:2143`;`{__cache}`(Cache Storage)为兜底;\`ref_\`(`app.js` 内定义的 `IDB_REF_PREFIX = 'ref_'`)为 legacy 形态 (A)。
- 大图判定:`isBigDataUrl` = `data:` 且 `length > 3000` (A) `app.js:2018`;**画布保存保留阈值** `< 16384` 才原样保留 (A) `app.js:2182`。**两处阈值并存,含义不同**。 - 大图判定:`isBigDataUrl` = `data:` 且 `length > 3000` (A) `app.js:2018`;**画布保存保留阈值** `< 16384` 才原样保留 (A) `app.js:2182`。**两处阈值并存,含义不同**。
- 单测是**源码契约测试**:`tests/` 目录共 **493** 处源码文本钉点(`source.includes` / `source.indexOf` / `/re/.test(source)`),分布在 **20** 个文件(其中 `iwb-v32-web-test.js` 一个就占 **407**)→ **结构性重构会先打红测试**。**该数字已由 `tests/source-text-ratchet-test.js` 的「只减不增」棘轮守门**(2026-10-20 起守卫范围从 1 个文件扩到全目录:新增任何一处源码文本钉点都会打红)。**2026-11-12 复算**(`npm run audit:pins`,v3.24.76):二分 STRUCT **417** / NAME **76**;形态 **POS 403 / NEG 87 / COUNT 3**;难度 **易 62 / 中 316 / 难 115**。钉点减法第一批(v3.24.72)把 **537 → 505**:8 条探针钉点改为「门禁内 spec 是否真的读该计数器」、5 条改为运行时断言(生产态 `window` 上无探针)、10 条改为 DOM 断言(质量档位禁用 / 传输页无三模式按钮 / 模型项 title)、4 条改为运行时对象断言(健康检查两域、策略对象冻结)、其余 9 条有同文件 DOM 等价断言或仅剩 NEG。第二批(v3.24.76)把 **505 → 493**:94-5~7 三条「多标签释放语义」(10 处正则)换成 `tests/iwb-tabs-release.spec.js` 的 3 条真 e2e,剩 1 条「消费方契约」(断言该 spec 在门禁内且 spec 源码真的读两个探针);另 2 条 `wPurgeIntent.add` 钉点改为读 `src/workspace-purge.js`。**这一批一换就查出 3 个真缺陷**(objectURL 从未释放 / 彻底删除留孤儿标签 · session / 刷新后误回收打开标签的图)—— 见 CHANGELOG v3.24.76。 - 单测是**源码契约测试**:`tests/` 目录共 **493** 处源码文本钉点(`source.includes` / `source.indexOf` / `/re/.test(source)`),分布在 **20** 个文件(其中 `iwb-v32-web-test.js` 一个就占 **407**)→ **结构性重构会先打红测试**。**该数字已由 `tests/source-text-ratchet-test.js` 的「只减不增」棘轮守门**(2026-10-20 起守卫范围从 1 个文件扩到全目录:新增任何一处源码文本钉点都会打红)。**2026-11-12 复算**(`npm run audit:pins`,v3.24.76):二分 STRUCT **417** / NAME **76**;形态 **POS 403 / NEG 87 / COUNT 3**;难度 **易 62 / 中 316 / 难 115**。钉点减法第一批(v3.24.72)把 **537 → 505**:8 条探针钉点改为「门禁内 spec 是否真的读该计数器」、5 条改为运行时断言(生产态 `window` 上无探针)、10 条改为 DOM 断言(质量档位禁用 / 传输页无三模式按钮 / 模型项 title)、4 条改为运行时对象断言(健康检查两域、策略对象冻结)、其余 9 条有同文件 DOM 等价断言或仅剩 NEG。第二批(v3.24.76)把 **505 → 493**:94-5~7 三条「多标签释放语义」(10 处正则)换成 `tests/iwb-tabs-release.spec.js` 的 3 条真 e2e,剩 1 条「消费方契约」(断言该 spec 在门禁内且 spec 源码真的读两个探针);另 2 条 `wPurgeIntent.add` 钉点改为读 `src/workspace-purge.js`。**这一批一换就查出 3 个真缺陷**(objectURL 从未释放 / 彻底删除留孤儿标签 · session / 刷新后误回收打开标签的图)—— 见 CHANGELOG v3.24.76。
- `app.js` = 单 IIFE **8,329 行**(**双层预算**:绝对上限 8,329 / 占总源码 ≤ 40%,现 **26.1%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **2,174 行**(上限 **2,179**,余量 5;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **117** 个模块 / 23,637 行,`sourceModules` 117 项;v3.24.68 新增 `clipboard-graph.js`,v3.24.74 新增 `image-admit.js`,v3.24.75 新增 `image-dedupe.js`,v3.24.76 新增 `workspace-purge.js`,v3.24.79 新增 `generation-provider-ping.js`,v3.24.80 删除无调用的 `createWBFlushViewport` 17 行)。 - `app.js` = 单 IIFE **8,322 行**(**双层预算**:绝对上限 8,329 / 占总源码 ≤ 40%,现 **25.7%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **2,162 行**(上限 **2,179**,余量 17;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **119** 个模块 / 24,088 行,`sourceModules` 119 项;v3.24.68 新增 `clipboard-graph.js`,v3.24.74 新增 `image-admit.js`,v3.24.75 新增 `image-dedupe.js`,v3.24.76 新增 `workspace-purge.js`,v3.24.79 新增 `generation-provider-ping.js`,v3.24.80 删除无调用的 `createWBFlushViewport` 17 行)。
- 门禁:`npm run verify` = `verify:ci`(`build` → `node --check app.js` → `node --check dist/app.js` → `check-dist.js` → `lint`(ESLint 正确性规则,`src/` + `app.js`,P4-16a)→ `test:unit` → `test` → `test:facts`)+ `test:e2e` (A) `package.json`。 - 门禁:`npm run verify` = `verify:ci`(`build` → `node --check app.js` → `node --check dist/app.js` → `check-dist.js` → `lint`(ESLint 正确性规则,`src/` + `app.js`,P4-16a)→ `test:unit` → `test` → `test:facts`)+ `test:e2e` (A) `package.json`。
## 2. 门禁与环境现状 ## 2. 门禁与环境现状
@@ -43,8 +43,9 @@
- **DOM-per-node**:每个节点一个 DOM 元素;不是 canvas 重绘。 - **DOM-per-node**:每个节点一个 DOM 元素;不是 canvas 重绘。
- **视口裁剪已存在**(不是"待做优化"): - **视口裁剪已存在**(不是"待做优化"):
- 余量 `240`px(左/上/右/下各 +240,世界坐标)(A) `app.js:12656-12659` - 余量:纯文本节点 `240`px;**带图节点(ref/out/image/combine/batch/plugin:album|gallery)`80`px** (A) `src/canvas-geometry.js` `CULL_PAD_WIDE` / `CULL_PAD_TIGHT`
- 公式 `left: -vp.x/vp.scale - 240`、`right: (w - vp.x)/vp.scale + 240` (A) `app.js:12655-12660` - 公式 `left: -vp.x/vp.scale - pad`、`right: (w - vp.x)/vp.scale + pad`(pad 按节点类型取宽/紧)(A) `cullRectsOf`
- 为什么分两档(v3.26.109):节点挂上 `<img>` 后浏览器会保留解码位图(1024 缩略图约 4MB、原图 6~20MB);240px 的宽余量意味着屏幕外一两屏的图片仍在解码,实测 WebContent physical footprint 1.2G / 峰值 2.7G
- 关闭条件:`canvasSize.w/h` 为 0 时 `cullRect = null`(jsdom/测试全渲染)(A) `app.js:12655,12662` - 关闭条件:`canvasSize.w/h` 为 0 时 `cullRect = null`(jsdom/测试全渲染)(A) `app.js:12655,12662`
- 豁免:拖拽中 `refs.drag.start[id]`、缩放中 `refs.resize.nodeId`、已选中 `sel.includes` (A) `app.js:12663-12665` - 豁免:拖拽中 `refs.drag.start[id]`、缩放中 `refs.resize.nodeId`、已选中 `sel.includes` (A) `app.js:12663-12665`
- 循环对不可见元素 **`continue`** 跳过(O(n) 布尔过滤,**不是 O(n) 渲染**)(O) `app.js:12684,12705` - 循环对不可见元素 **`continue`** 跳过(O(n) 布尔过滤,**不是 O(n) 渲染**)(O) `app.js:12684,12705`
@@ -58,7 +59,7 @@
|---|---|---| |---|---|---|
| objectURL 缓存 | `W_OBJURL_MAX = 50`(FIFO,驱逐即 revoke) | (A) `app.js:4105` | | objectURL 缓存 | `W_OBJURL_MAX = 50`(FIFO,驱逐即 revoke) | (A) `app.js:4105` |
| blob 引用缓存 | `W_BLOBREF_MAX = 50` | (A) `app.js:4111` | | blob 引用缓存 | `W_BLOBREF_MAX = 50` | (A) `app.js:4111` |
| 显示缩略图缓存 | `DISPLAY_THUMB_CACHE_MAX = 300`;`DISPLAY_THUMB_MAX = 640` | (A) `app.js:4573 / 4572` | | 显示缩略图缓存 | `DISPLAY_THUMB_CACHE_MAX = 300`;`DISPLAY_THUMB_MAX = 1024`(v3.26.109:640→1024,避免 dpr=2 时解码原图) | (A) `app.js:4573 / 4572` |
| 预览派生缓存 | `PREVIEW_CACHE_MAX = 200`(FIFO,**淘汰即 revoke**);`PREVIEW_MAX_EDGE = 1024` | (A) `app.js:4592 / 4591`;淘汰 revoke `4595-4599` | | 预览派生缓存 | `PREVIEW_CACHE_MAX = 200`(FIFO,**淘汰即 revoke**);`PREVIEW_MAX_EDGE = 1024` | (A) `app.js:4592 / 4591`;淘汰 revoke `4595-4599` |
| 图库缩略图缓存 | `outThumbCacheMax = 400` | (A) `app.js:1980` | | 图库缩略图缓存 | `outThumbCacheMax = 400` | (A) `app.js:1980` |
| Blob 仓库内存 LRU | `DEFAULT_BLOB_CACHE_MAX = 200` | (A) `src/image-blob-store.js:51` | | Blob 仓库内存 LRU | `DEFAULT_BLOB_CACHE_MAX = 200` | (A) `src/image-blob-store.js:51` |
@@ -167,7 +168,7 @@
- 同一张图被 3 个节点引用、hydrate 成 3 个不同 objectURL 时,preview/display 缓存各自 miss → 重复解码(与 F2 相邻)。 - 同一张图被 3 个节点引用、hydrate 成 3 个不同 objectURL 时,preview/display 缓存各自 miss → 重复解码(与 F2 相邻)。
- **F10|`refs.genScheduler` 是桩** (A) → 未接线,暂无运行时影响(P3)。 - **F10|`refs.genScheduler` 是桩** (A) → 未接线,暂无运行时影响(P3)。
- **F11|已建但未接线的模块层(2026-10-17 接线审计;2026-10-18 复核更正)** (A) - **F11|已建但未接线的模块层(2026-10-17 接线审计;2026-10-18 复核更正)** (A)
- **判定法**:`global.X =` / `root.X =` 判「导出」;跨文件裸引用判「读」;排除自合并(`src/runtime-constants.js:9`)。`app.js` 是**唯一生产消费者**(无 HTML 入口;`sw.js` 不引用模块全局)。**117 个模块中 59 个导出**被 `app.js` 读取;其余为未接线 / 仅测试 / 零引用(见下)。 - **判定法**:`global.X =` / `root.X =` 判「导出」;跨文件裸引用判「读」;排除自合并(`src/runtime-constants.js:9`)。`app.js` 是**唯一生产消费者**(无 HTML 入口;`sw.js` 不引用模块全局)。**119 个模块中 59 个导出**被 `app.js` 读取;其余为未接线 / 仅测试 / 零引用(见下)。
- **仅被测试引用(9 模块 + 2 导出)**:`canvas-domain`、`generation-retry`、`generation-service`、`runtime-recovery-runner`、`runtime-state-bridge`、`runtime-store`、`storage-reconcile`、`storage-result`、`workspace-service`;导出 `IWBStorageHealthFactory`、`IWBPluginHostFactory`。(`storage-result` 是**存储层共享结果类型**,被 6 个存储模块读取,**非死代码**;`runtime-store` 为状态模型 epic 地基。) - **仅被测试引用(9 模块 + 2 导出)**:`canvas-domain`、`generation-retry`、`generation-service`、`runtime-recovery-runner`、`runtime-state-bridge`、`runtime-store`、`storage-reconcile`、`storage-result`、`workspace-service`;导出 `IWBStorageHealthFactory`、`IWBPluginHostFactory`。(`storage-result` 是**存储层共享结果类型**,被 6 个存储模块读取,**非死代码**;`runtime-store` 为状态模型 epic 地基。)
- **app.js 零引用(1 模块 + 3 导出)**:模块 `generation-controller`;导出 `IWBRuntimeMetricsFactory`、`IWBStorageRuntimeFactory`、`IWBUIComponents`。`canvas-relations` 已随 `06cf211` 删除(本文档早前把它列为"唯一可删者",实际已删)。零引用证据 = `grep -rn "<名字>" .`(排除 `node_modules|dist|vendor|test-results`)**只命中其自身赋值行**。 - **app.js 零引用(1 模块 + 3 导出)**:模块 `generation-controller`;导出 `IWBRuntimeMetricsFactory`、`IWBStorageRuntimeFactory`、`IWBUIComponents`。`canvas-relations` 已随 `06cf211` 删除(本文档早前把它列为"唯一可删者",实际已删)。零引用证据 = `grep -rn "<名字>" .`(排除 `node_modules|dist|vendor|test-results`)**只命中其自身赋值行**。
- **半接线 / 未接线**:`IWBRuntimeStateBridge` **无 app.js 引用(仅测试)**;`IWBRuntimeRunContext` **已接线**(`runNode` 读取运行上下文);`IWBGenerationController` 是完整但**从未被调用**的工厂;`ModularWorkspaceStore`(`app.js` 内)是 `storage-workspace` 的**预留接线 seam**(当前无下游使用,保留);`window.IWBImageFolder` 自注册后读回(装载路径)。 - **半接线 / 未接线**:`IWBRuntimeStateBridge` **无 app.js 引用(仅测试)**;`IWBRuntimeRunContext` **已接线**(`runNode` 读取运行上下文);`IWBGenerationController` 是完整但**从未被调用**的工厂;`ModularWorkspaceStore`(`app.js` 内)是 `storage-workspace` 的**预留接线 seam**(当前无下游使用,保留);`window.IWBImageFolder` 自注册后读回(装载路径)。
@@ -183,7 +184,7 @@
| `storage-reconcile` | 存储对账(`createReconciler`/`check`) | 内联对账 | 存储层收口 | | `storage-reconcile` | 存储对账(`createReconciler`/`check`) | 内联对账 | 存储层收口 |
| `runtime-recovery-runner` | 执行恢复候选(`candidate`/`valid`/`run`) | 内联恢复 | 断点恢复 | | `runtime-recovery-runner` | 执行恢复候选(`candidate`/`valid`/`run`) | 内联恢复 | 断点恢复 |
| `canvas-domain` | 画布域模型(`commit`/`updateNode`/`deleteNodes`…) | `CanvasStore` 那一套 | Workbench 解耦(P2-9) | | `canvas-domain` | 画布域模型(`commit`/`updateNode`/`deleteNodes`…) | `CanvasStore` 那一套 | Workbench 解耦(P2-9) |
- **耦合面已冻结**:`tests/architecture-boundary-guard-test.js`(进 `npm run test:unit` 末环)冻结 app.js↔src 耦合面(**96** 项)与 `sourceModules` 顺序(**117** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。 - **耦合面已冻结**:`tests/architecture-boundary-guard-test.js`(进 `npm run test:unit` 末环)冻结 app.js↔src 耦合面(**98** 项)与 `sourceModules` 顺序(**119** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。
## 12. 易踩的坑 ## 12. 易踩的坑
@@ -254,7 +255,7 @@
**信任模型(必须明示)**:形态 A 的插件是**可信代码**(与核心同权限、无沙箱);启停与设置是 UX 与可维护性手段,**不是安全边界**(同 §13.27 教训:前端开关一定可被绕过)。 **信任模型(必须明示)**:形态 A 的插件是**可信代码**(与核心同权限、无沙箱);启停与设置是 UX 与可维护性手段,**不是安全边界**(同 §13.27 教训:前端开关一定可被绕过)。
**守门与快照**:`tests/architecture-boundary-guard-test.js` 冻结「app.js ↔ src 耦合面」(**96** 项)与 `sourceModules` 顺序(**117** 项);新增模块、新增耦合、新增 dev 探针都**必须有意重生成对应快照**(`IWB_WRITE_BOUNDARY_SNAPSHOT=1`)。契约与行为的可执行验证在 `tests/plugin-host-test.js`(宿主单测)与 `tests/_plugin-host-probe.spec.js`(真实浏览器探针,`_` 前缀 + `iwb-dev-probe`,不进 34 门禁)。 **守门与快照**:`tests/architecture-boundary-guard-test.js` 冻结「app.js ↔ src 耦合面」(**98** 项)与 `sourceModules` 顺序(**119** 项);新增模块、新增耦合、新增 dev 探针都**必须有意重生成对应快照**(`IWB_WRITE_BOUNDARY_SNAPSHOT=1`)。契约与行为的可执行验证在 `tests/plugin-host-test.js`(宿主单测)与 `tests/_plugin-host-probe.spec.js`(真实浏览器探针,`_` 前缀 + `iwb-dev-probe`,不进 34 门禁)。
**关键陷阱**:`normalizeNodes`(现位于 `src/canvas-normalize.js`)会**静默丢弃**不在 `NODE_H` 里的节点类型 ⇒ 新增节点类型必须先登记 `NODE_H`,否则节点一刷新就消失(§13.27 规则三的同一失败模式)。 **关键陷阱**:`normalizeNodes`(现位于 `src/canvas-normalize.js`)会**静默丢弃**不在 `NODE_H` 里的节点类型 ⇒ 新增节点类型必须先登记 `NODE_H`,否则节点一刷新就消失(§13.27 规则三的同一失败模式)。
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "image-workbench-web", "name": "image-workbench-web",
"private": true, "private": true,
"version": "3.26.108", "version": "3.26.109",
"description": "Browser-based node canvas image workbench", "description": "Browser-based node canvas image workbench",
"scripts": { "scripts": {
"build": "node scripts/build.js && node scripts/copy-plugins.js", "build": "node scripts/build.js && node scripts/copy-plugins.js",
+3 -3
View File
@@ -75,9 +75,9 @@
}, },
{ {
"id": "sticky", "id": "sticky",
"file": "plugin-sticky.f5f77ac81467.js", "file": "plugin-sticky.64987dea4f2a.js",
"version": "1.0.8", "version": "1.0.10",
"integrity": "sha256-9fd6yBRnWxcDNDN1G+KywL9vp5JN9CaTMja4s5pK1As=" "integrity": "sha256-ZJh96k8qK/ES2r3BazTFxMr2CHD66VRlZQfpj15hIrk="
}, },
{ {
"id": "style-source", "id": "style-source",
@@ -397,89 +397,19 @@
if (st.dot.style.background !== bg) st.dot.style.background = bg if (st.dot.style.background !== bg) st.dot.style.background = bg
} }
// ---------------- 面板 ---------------- // ⚠️ 不要给便签加左侧栏面板(用户 2026-11-29 再次确认,此前 11-28 做过一次又被改回来):
var ctxForPanel = null // 一旦向宿主登记「面板」,资源面板就会多出一个「便利贴」标签页。插入便利贴走画布右键菜单,不走面板。
var noteList = []
function refreshList() {
if (!ctxForPanel) return
var host = ctxForPanel.__stickyPanelRoot
if (!host || typeof host.innerHTML !== 'undefined' && !host.innerHTML && !host.appendChild) return
var list = host.querySelector ? host.querySelector('.iwb-sticky-list') : null
if (!list) return
// 尽力从画布读回便利贴节点(只读画布能力给了 getNodes)
var nodes = []
try {
var api = ctxRef && ctxRef.canvas
if (api && typeof api.getNodes === 'function') nodes = api.getNodes() || []
} catch (e) { nodes = [] }
var mine = nodes.filter(function (n) { return String(n.type || '').indexOf('plugin:sticky:') === 0 })
// 用最近插入的本地记录补足(getNodes 快照不含自定义状态没关系,这里只显示文本)
var seen = {}
var rows = []
mine.concat(noteList).forEach(function (n) {
var key = n.id
if (!key || seen[key]) return
seen[key] = 1
var text = String((n.data && n.data.text) || '').replace(/\s+/g, ' ').slice(0, 30) || '(空便利贴)'
rows.push({ id: key, text: text })
})
while (list.firstChild) list.removeChild(list.firstChild)
rows.slice(-20).forEach(function (r) {
var row = el('div', { className: 'iwb-sticky-row' })
row.appendChild(el('span', { className: 'iwb-sticky-row-txt' }, r.text))
var go = el('button', { className: 'iwb-sticky-go', type: 'button' }, '定位')
go.addEventListener('click', function () {
try { if (ctxRef && ctxRef.canvas && typeof ctxRef.canvas.focusNode === 'function') ctxRef.canvas.focusNode(r.id) } catch (e) { /* noop */ }
})
row.appendChild(go)
list.appendChild(row)
})
}
function mountPanel(host, ctx) {
ensureStyle()
ctxForPanel = ctx
host.textContent = ''
host.style.minWidth = '0'; host.style.minHeight = '0'; host.style.height = '100%'
var wrap = el('div', { className: 'iwb-sticky-panel' })
wrap.appendChild(el('div', { className: 'iwb-sticky-panel-tip' },
'在画布上放一张便利贴:字调大当说明标题,字调小放多行正文。点右下角拖动手柄可改变便签大小。'))
var add = el('button', { className: 'iwb-sticky-add', type: 'button' }, '+ 插入便利贴')
add.addEventListener('click', function () { insertNote() })
wrap.appendChild(add)
var list = el('div', { className: 'iwb-sticky-list' })
wrap.appendChild(list)
host.appendChild(wrap)
ctxForPanel.__stickyPanelRoot = host
refreshList()
}
function insertNote() {
var api = ctxRef && ctxRef.canvas
if (!api || typeof api.createNode !== 'function') return null
var id = api.createNode('plugin:sticky:sticky', null, null, {
text: '', fontSize: DEFAULT_SIZE, fontWeight: 400, bgColor: DEFAULT_BG,
})
if (id) {
noteList.push({ id: id, data: { text: '' } })
refreshList()
}
return id
}
function dispose() { function dispose() {
ctxRef = null ctxRef = null
ctxForPanel = null
noteList = []
} }
global.IWBPluginHost.register({ global.IWBPluginHost.register({
id: 'sticky', id: 'sticky',
name: '便利贴', name: '便利贴',
version: '1.0.8', version: '1.0.10',
apiVersion: 1, apiVersion: 1,
capabilities: ['panels', 'nodeTypes', 'canvas'], capabilities: ['nodeTypes', 'canvas'],
}, function (ctx) { }, function (ctx) {
ctxRef = ctx ctxRef = ctx
if (ctx.nodes && typeof ctx.nodes.register === 'function') { if (ctx.nodes && typeof ctx.nodes.register === 'function') {
@@ -492,14 +422,6 @@
render: renderSticky, render: renderSticky,
}) })
} }
if (ctx.ui && typeof ctx.ui.registerPanel === 'function') {
ctx.ui.registerPanel({
id: 'sticky',
title: '便利贴',
icon: 'note',
mount: mountPanel,
})
}
return { dispose: dispose } return { dispose: dispose }
}) })
})(typeof window !== 'undefined' ? window : globalThis) })(typeof window !== 'undefined' ? window : globalThis)
+6 -1
View File
@@ -103,6 +103,8 @@ const sourceModules = [
'theme-tokens.js', 'theme-tokens.js',
'canvas-grid.js', 'canvas-grid.js',
'image-display-thumb.js', 'image-display-thumb.js',
'image-cache-migrate.js',
'runtime-frame-probe.js',
'image-remote-cache.js', 'image-remote-cache.js',
'gallery-sync.js', 'gallery-sync.js',
'image-thumb-pick.js', 'image-thumb-pick.js',
@@ -188,7 +190,10 @@ if (sourcemap) {
} }
// Banner 在 minify 之后前置,避免被压缩器移除。 // Banner 在 minify 之后前置,避免被压缩器移除。
appBundle = '/*! IWB ' + version + ' */\n' + appBundle // 帧时长探针默认不进正式包(对外版本不写性能日志):只有 IWB_PERF_PROBE=1 才打开。
// 探针模块本身保留在源码里,正式包只是不启动它的 rAF 循环(零开销)。
const perfProbeOn = process.env.IWB_PERF_PROBE === '1'
appBundle = '/*! IWB ' + version + ' */\n' + (perfProbeOn ? 'window.__IWB_PERF_PROBE__=1;\n' : '') + appBundle
fs.writeFileSync(path.join(dist, 'app.js'), appBundle) fs.writeFileSync(path.join(dist, 'app.js'), appBundle)
/* 设计 token 必须排在最前:src/design-tokens.css 是生成的静态快照(:root / .theme-dark), /* 设计 token 必须排在最前:src/design-tokens.css 是生成的静态快照(:root / .theme-dark),
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "image-workbench" name = "image-workbench"
version = "3.26.108" version = "3.26.109"
description = "无限画布 · 生图工作台桌面版" description = "无限画布 · 生图工作台桌面版"
authors = ["malongan"] authors = ["malongan"]
license = "" license = ""
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
"productName": "image-workbench", "productName": "image-workbench",
"version": "3.26.108", "version": "3.26.109",
"identifier": "com.malongan.imageworkbench", "identifier": "com.malongan.imageworkbench",
"build": { "build": {
"frontendDist": "../dist", "frontendDist": "../dist",
+36 -1
View File
@@ -354,6 +354,41 @@
} }
// 插件「插入画布」落到可视区域中心(findSpot 会把节点丢左上角,常被左侧面板遮住)。 // 插件「插入画布」落到可视区域中心(findSpot 会把节点丢左上角,常被左侧面板遮住)。
// v3.26.109(内存 C):画布视口裁剪矩形。
// 动机:节点一旦挂上 <img>,浏览器就为它保留解码位图(1024 缩略图约 4MB、原图 6~20MB)。
// 原来统一 240px 边距 ⇒ 屏幕外一两屏的图仍常驻解码(实测 WebContent footprint 1.2G / 峰值 2.7G)。
// 现在带图节点只留 80px,同一时刻常驻解码的图片数量明显下降;纯文本节点仍用 240px,避免平移时文字闪。
const CULL_PAD_WIDE = 240
const CULL_PAD_TIGHT = 80
const heavyNodeOf = (type) => {
const t = String(type || '')
return /^(ref|out|image|combine|batch)$/.test(t) || /^plugin:(album|gallery)/.test(t)
}
function cullRectsOf (canvasSize, viewport) {
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 mk = (pad) => ({
left: -viewport.x / s - pad,
top: -viewport.y / s - pad,
right: (w - viewport.x) / s + pad,
bottom: (h - viewport.y) / s + pad,
})
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
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) => { const promptCenterSpot = (bridge, w, h) => {
try { try {
const c = typeof document !== 'undefined' ? document.querySelector('.iwb-canvas') : null const c = typeof document !== 'undefined' ? document.querySelector('.iwb-canvas') : null
@@ -363,5 +398,5 @@
return p ? { x: p.x - (w || 0) / 2, y: p.y - (h || 0) / 2 } : null return p ? { x: p.x - (w || 0) / 2, y: p.y - (h || 0) / 2 } : null
} catch (e) { return null } } catch (e) { return null }
} }
global.IWBCanvasGeometry = Object.freeze({ connectReasonOf, 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 }) global.IWBCanvasGeometry = Object.freeze({ connectReasonOf, cullRectsOf, nodeVisibleIn, heavyNodeOf, 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) })(typeof window !== 'undefined' ? window : globalThis)
+6 -2
View File
@@ -41,12 +41,16 @@
// v3.26.109 诊断:连线在没有任何「删除」动作的情况下变少时,留一条带调用栈的日志。 // v3.26.109 诊断:连线在没有任何「删除」动作的情况下变少时,留一条带调用栈的日志。
// 用户实测「生图出来后配置节点的连线自己断了」,光看代码找不到唯一路径,先把证据留下。 // 用户实测「生图出来后配置节点的连线自己断了」,光看代码找不到唯一路径,先把证据留下。
const noteEdgeDrop = (before, after, meta) => { const noteEdgeDrop = (before, after, meta, nodesAfter) => {
try { try {
if (!Array.isArray(before) || !Array.isArray(after) || after.length >= before.length) return if (!Array.isArray(before) || !Array.isArray(after) || after.length >= before.length) return
const kept = new Set(after.map((e) => e && e.id)) const kept = new Set(after.map((e) => e && e.id))
const gone = before.filter((e) => e && !kept.has(e.id)) const gone = before.filter((e) => e && !kept.has(e.id))
if (!gone.length) return if (!gone.length) return
// 换画板/整表替换不是「连线自己断了」:旧边的两个端点在新画板里都找不到 ⇒ 直接跳过,
// 否则每次切板都会刷一条 n=90/140 的假告警(2026-11-29 日志实测刷屏,干扰真问题定位)。
const alive = new Set((nodesAfter || []).map((n) => n && n.id))
if (alive.size && gone.every((e) => !alive.has(e.from) && !alive.has(e.to))) return
const why = String((meta && (meta.reason || meta.kind)) || '') const why = String((meta && (meta.reason || meta.kind)) || '')
const list = gone.slice(0, 3).map((e) => String(e.id) + ':' + String(e.from) + '>' + String(e.to)).join(',') const list = gone.slice(0, 3).map((e) => String(e.id) + ':' + String(e.from) + '>' + String(e.to)).join(',')
const rewired = before.filter((e) => { const n = after.find((x) => x && e && x.id === e.id); return n && (n.from !== e.from || n.to !== e.to) }) const rewired = before.filter((e) => { const n = after.find((x) => x && e && x.id === e.id); return n && (n.from !== e.from || n.to !== e.to) })
@@ -69,7 +73,7 @@
const commit = (next, meta) => { const commit = (next, meta) => {
if (destroyed) return cloneSnapshot(state) if (destroyed) return cloneSnapshot(state)
const previous = state const previous = state
try { noteEdgeDrop((previous && previous.edges) || [], (normalize(next) || {}).edges || [], meta) } catch (e) { /* ignore */ } try { const nx = normalize(next) || { nodes: [], edges: [] }; noteEdgeDrop((previous && previous.edges) || [], nx.edges || [], meta, nx.nodes) } catch (e) { /* ignore */ }
state = normalize(next) state = normalize(next)
revision += 1 revision += 1
state.rev = revision state.rev = revision
+58
View File
@@ -0,0 +1,58 @@
/* image-cache-migrate.js —— {__cache} → {__blob} 一次性物化(2026-11-29)
*
* 为什么:Cache Storage 是**按站点隔离**的。网页版把图写进 https://iwb.maqiart.eu.org 的缓存,
* 桌面端跑在 tauri://localhost,读不到 → 图片变成破图图标(用户实测 146 个节点受影响)。
* 所以只要某个 {__cache} 引用**还能读出来**,就立刻把字节复制进资料目录({__blob} 主通道),
* 从此不再依赖 Cache Storage。
*
* 纪律:
* · 只改「能读到字节」的引用;读不到就原地不动(绝不写坏数据)。
* · 每个画板对象只跑一次(WeakSet),避免反复 hydrate 时重复读盘。
* · 就地改 node.data 里的引用对象(宿主下一次自动保存即落盘)。
*/
;(function (global) {
'use strict'
const done = new WeakSet()
// 收集所有 {__cache} 引用对象(引用本身是可变对象,直接原地改)
function collect (value, out) {
if (!value || typeof value !== 'object') return
if (Array.isArray(value)) { for (const v of value) collect(v, out); return }
if (typeof value.__cache === 'string' && value.__cache) { out.push(value); return }
for (const k of Object.keys(value)) collect(value[k], out)
}
function once (board, deps) {
const d = deps || {}
if (!board || !board.id || done.has(board)) return Promise.resolve({ skipped: true })
if (typeof d.read !== 'function' || typeof d.write !== 'function') return Promise.resolve({ skipped: true })
done.add(board)
const refs = []
collect(board.nodes, refs)
if (!refs.length) return Promise.resolve({ total: 0, ok: 0, fail: 0 })
let ok = 0
let fail = 0
const step = (i) => {
if (i >= refs.length) {
if (ok && typeof d.bump === 'function') { try { d.bump() } catch (e) { /* ignore */ } }
return { total: refs.length, ok: ok, fail: fail }
}
const ref = refs[i]
return Promise.resolve()
.then(() => d.read(ref.__cache))
.then((dataUrl) => (dataUrl ? d.write(dataUrl) : null))
.then((next) => {
if (next && typeof next === 'object' && (next.__blob || next.__cache || next.__file)) {
delete ref.__cache
Object.assign(ref, next)
ok++
} else { fail++ }
})
.catch(() => { fail++ })
.then(() => step(i + 1))
}
return Promise.resolve().then(() => step(0)).catch(() => ({ total: refs.length, ok: ok, fail: fail }))
}
global.IWBImageCacheMigrate = { once: once, _collect: collect }
})(typeof window !== 'undefined' ? window : globalThis)
+6 -2
View File
@@ -14,8 +14,11 @@
function create (opts) { function create (opts) {
const o = opts || {} const o = opts || {}
// v3.26.34:显示缩略图 640px / WebP 0.72 —— 原来 768px+0.86 单张 500~900KB,49 张 24MB。 // v3.26.109:显示缩略图 1024px / WebP 0.72。
const max = Math.max(64, Number(o.max) || 640) // 640 时代的问题是不够用:画布 LOD 规则 need=渲染长边×缩放×dpr,dpr=2 时节点宽 400px 就需要 800
// ⇒ 直接改解码原图(一张 1.9MB 原图解出来 6~20MB,实测 WebContent footprint 冲到 1.2G)。
// 1024 让多数缩放档留在缩略图上;单张约 60~110KB,缓存 300 张约 30MB,远小于原图解码。
const max = Math.max(64, Number(o.max) || 1024)
const cacheMax = Math.max(16, Number(o.cacheMax) || 300) const cacheMax = Math.max(16, Number(o.cacheMax) || 300)
const concurrency = Math.max(1, Number(o.concurrency) || 2) const concurrency = Math.max(1, Number(o.concurrency) || 2)
const cache = o.cache const cache = o.cache
@@ -37,6 +40,7 @@
// ① 优先路径:字节 → bitmap → 缩放 → WebP Blob → objectURL // ① 优先路径:字节 → bitmap → 缩放 → WebP Blob → objectURL
const runBitmap = async (key, v) => { const runBitmap = async (key, v) => {
try { window.IWBPerf && window.IWBPerf.tag('thumb') } catch (e) { /* ignore */ }
if (typeof fetch !== 'function' || typeof createImageBitmap !== 'function') return false if (typeof fetch !== 'function' || typeof createImageBitmap !== 'function') return false
const resp = await fetch(v) const resp = await fetch(v)
if (!resp || !resp.ok) return false if (!resp || !resp.ok) return false
+7 -2
View File
@@ -31,14 +31,19 @@
return typeof d.rawKeyOf === 'function' ? d.rawKeyOf(str) : '' return typeof d.rawKeyOf === 'function' ? d.rawKeyOf(str) : ''
} }
// 屏幕上需要的长边 = 渲染长边 × 缩放 × dpr;超过缩略图长边才用原图 // 屏幕上需要的长边 = 渲染长边 × 缩放 × dpr。
// v3.26.111(内存):**有缩略图就不再为了“再清晰一点”去解码原图**,最多忍到 2× 缩略图长边;
// 原来一超过 max(1024)就整屏切原图 —— 实测放大到 2× 时 90 个节点同时解 4K 原图,
// WebContent footprint 冲到 1.2G / 峰值 2.6G,缩放停手那一下也最卡。
// 现在放大后是缩略图“放大显示”(1.3~2× 轻微发虚),换取解码量恒定。
const ORIG_HARD_CAP = Math.max(1200, max * 2)
function srcForNode (v, renderedLongEdge, scale) { function srcForNode (v, renderedLongEdge, scale) {
const key = keyOf(v) const key = keyOf(v)
const thumb = key && cache ? cache.get(key) : '' const thumb = key && cache ? cache.get(key) : ''
const dpr = (typeof global.devicePixelRatio === 'number' && global.devicePixelRatio > 0) ? global.devicePixelRatio : 1 const dpr = (typeof global.devicePixelRatio === 'number' && global.devicePixelRatio > 0) ? global.devicePixelRatio : 1
const s = Number(scale) const s = Number(scale)
const need = Math.max(1, Number(renderedLongEdge) || 0) * (Number.isFinite(s) && s > 0 ? s : 1) * dpr const need = Math.max(1, Number(renderedLongEdge) || 0) * (Number.isFinite(s) && s > 0 ? s : 1) * dpr
if (thumb && need <= max) return thumb if (thumb && need <= ORIG_HARD_CAP) return thumb
const orig = (v && typeof v === 'object') const orig = (v && typeof v === 'object')
? ((typeof d.resolveImg === 'function' ? d.resolveImg(v) : '') || '') ? ((typeof d.resolveImg === 'function' ? d.resolveImg(v) : '') || '')
: String(v || '') : String(v || '')
+25 -1
View File
@@ -12,7 +12,7 @@
function useBootLoad(ctx) { function useBootLoad(ctx) {
React.useEffect(() => { React.useEffect(() => {
const { APP_VERSION, CanvasStore, CrashLog, RuntimeMetrics, RuntimeRecovery, W_PURGE_ORIG_FLAG, activeWsIdRef, api, commitCanvas, displayThumbs, doFit, historySnapshotBytes, historyStore, hydrateAndReload, loadDemo, loadSavedGroups, lsGet, lsRawGet, lsRawSet, lsRemove, lsSet, migrateGenTaskIds, normalizeEdges, normalizeGroups, normalizeNodes, openTab, openTabsRef, outThumbCache, refreshOutputs, refs, setActiveWsId, setConfig, setLoaded, setMemUi, setPromptGroups, setPrompts, setResumePrompt, setServer, setWorkspaces, setWsRev, showToast, wDiagStats, wEvictLoadedBoards, wLoadedBoards, wMemoryComposition, wPurgeOutputOriginals, wSafeCompressStart } = ctx() const { APP_VERSION, CanvasStore, CrashLog, RuntimeMetrics, RuntimeRecovery, W_PURGE_ORIG_FLAG, activeWsIdRef, api, commitCanvas, displayThumbs, doFit, historySnapshotBytes, historyStore, hydrateAndReload, loadDemo, loadSavedGroups, lsGet, lsRawGet, lsRawSet, lsRemove, lsSet, migrateGenTaskIds, normalizeEdges, normalizeGroups, normalizeNodes, openTab, openTabsRef, outThumbCache, refreshOutputs, refs, setActiveWsId, setConfig, setLoaded, setMemUi, setPromptGroups, setPrompts, setResumePrompt, setServer, setWorkspaces, setWsRev, showToast, wDiagStats, wEvictLoadedBoards, wLoadedBoards, wMemoryComposition, wPreloadDisplayThumbs, wPurgeOutputOriginals, wSafeCompressStart } = ctx()
// 数据永久保留:一次性把当前工作台存储备份为 legacy;若主数据缺失/损坏且存在 legacy 则恢复 // 数据永久保留:一次性把当前工作台存储备份为 legacy;若主数据缺失/损坏且存在 legacy 则恢复
try { try {
const cur = lsRawGet('iwb_web_workspaces', null) const cur = lsRawGet('iwb_web_workspaces', null)
@@ -39,6 +39,21 @@
} }
}).catch(() => {}) }).catch(() => {})
loadSavedGroups() loadSavedGroups()
// 启动内存探针(2026-11-29):状态栏那个数只反映 JS 堆(performance.memory),
// 解码位图 / 合成层 / 原生侧完全不算在内,所以和活动监视器差很多是正常的。
// 这里把「各结构 MB + DOM 里的 img 个数 + 堆」写进 _boot.log,重启一次就能看出是哪一块在涨。
const wBootMemLog = (tag) => {
try {
const S = (typeof window !== 'undefined') ? window.IWBStorageFile : null
if (!S || typeof S.logLine !== 'function') return
const pm = (typeof performance !== 'undefined' && performance.memory) ? performance.memory : null
const heap = pm ? Math.round(pm.usedJSHeapSize / 1048576) : -1
let comp = {}
try { comp = (typeof wMemoryComposition === 'function') ? wMemoryComposition(refs) : {} } catch (e) { comp = { err: 1 } }
const domImgs = (typeof document !== 'undefined' && document.images) ? document.images.length : -1
S.logLine('mem ' + tag + ' heap=' + heap + 'MB domImgs=' + domImgs + ' ' + JSON.stringify(comp))
} catch (e) { /* 诊断失败不影响启动 */ }
}
// 跨标签页节点组同步:本 tab 保存 → 其他 tab 立即刷新(storage 事件 + BroadcastChannel 兜底) // 跨标签页节点组同步:本 tab 保存 → 其他 tab 立即刷新(storage 事件 + BroadcastChannel 兜底)
const onGsStorage = (e) => { const onGsStorage = (e) => {
if (e.key === 'iwb_web_groups' || e.key === 'iwb_web_groupgroups') loadSavedGroups() if (e.key === 'iwb_web_groups' || e.key === 'iwb_web_groupgroups') loadSavedGroups()
@@ -47,6 +62,9 @@
let gsBC = null let gsBC = null
try { if (typeof BroadcastChannel !== 'undefined') { gsBC = new BroadcastChannel('iwb_groups_sync'); gsBC.onmessage = () => loadSavedGroups() } } catch (err) { /* ignore */ } try { if (typeof BroadcastChannel !== 'undefined') { gsBC = new BroadcastChannel('iwb_groups_sync'); gsBC.onmessage = () => loadSavedGroups() } } catch (err) { /* ignore */ }
refreshOutputs(100) refreshOutputs(100)
wBootMemLog('after-refreshOutputs')
// 启动 2 秒后再采一次:此时画板已渲染、DOM 里的 img 才是真实峰值
setTimeout(() => wBootMemLog('ready-2s'), 2000)
// 初始化超时兜底:本地工作台读取异常/挂起时,保证进入已加载界面,避免 splash 一直转圈。 // 初始化超时兜底:本地工作台读取异常/挂起时,保证进入已加载界面,避免 splash 一直转圈。
let wsLoadTimer = null let wsLoadTimer = null
const ensureLoaded = () => { const ensureLoaded = () => {
@@ -62,6 +80,7 @@
setWsRev(r.rev || null) setWsRev(r.rev || null)
try { const F = window.IWBImageFileRef; if (F && F.grantKnown) await F.grantKnown(r.workspaces) } catch (e) { /* 授权失败:相册/组合按缺图提示 */ } try { const F = window.IWBImageFileRef; if (F && F.grantKnown) await F.grantKnown(r.workspaces) } catch (e) { /* 授权失败:相册/组合按缺图提示 */ }
setWorkspaces(r.workspaces.map((w) => ({ ...w, nodes: w.nodes || [], edges: w.edges || [], groups: w.groups || [] }))) setWorkspaces(r.workspaces.map((w) => ({ ...w, nodes: w.nodes || [], edges: w.edges || [], groups: w.groups || [] })))
wBootMemLog('after-workspaces')
// 上次生成中断(24 小时内)→ 提示可续跑(已完成的结果已持久化,不重跑) // 上次生成中断(24 小时内)→ 提示可续跑(已完成的结果已持久化,不重跑)
try { try {
const rr = lsGet('iwb_web_running', null) const rr = lsGet('iwb_web_running', null)
@@ -99,6 +118,11 @@
try { savedActive = lsRawGet('iwb_ws_active', null) } catch (e) { /* ignore */ } try { savedActive = lsRawGet('iwb_ws_active', null) } catch (e) { /* ignore */ }
const active = r.workspaces.find((w) => w.id === savedActive) || r.workspaces.find((w) => w.id === r.activeId) || r.workspaces[0] const active = r.workspaces.find((w) => w.id === savedActive) || r.workspaces.find((w) => w.id === r.activeId) || r.workspaces[0]
setActiveWsId(active.id); openTab(active.id) // S12:初始活动画布也进标签列表 setActiveWsId(active.id); openTab(active.id) // S12:初始活动画布也进标签列表
// v3.26.109(内存 D):首帧前先把显示缩略图准备好。
// 原来 loadWsInto 用 setTimeout(0) 预热 ⇒ 第一帧就已经用**原图**解码(实测 WebContent 峰值 2.6G),
// 缩略图晚到也只是换 src,解码过的原图仍被 WebKit 留着。改成渲染前 await。
try { await wPreloadDisplayThumbs(active.nodes) } catch (e) { /* 预热失败照常启动 */ }
wBootMemLog('after-thumbs')
const ns = normalizeNodes(active.nodes) const ns = normalizeNodes(active.nodes)
if (ns.length) { if (ns.length) {
const es0 = normalizeEdges(active.edges) const es0 = normalizeEdges(active.edges)
+79
View File
@@ -0,0 +1,79 @@
/* frame-probe.js —— 帧时长探针(2026-11-29)
*
* 目的:真机上定位「哪一下卡」。代码侧已经确认平移/拖拽/滚轮都只改 DOM,
* 浏览器无头环境也测不出卡顿(合成画布 120 节点仍是 60fps),所以必须回到真机采数据。
*
* 做法:requestAnimationFrame 连续测帧间隔,只统计 >50ms 的长帧;
* 每分钟最多写一条汇总到 _boot.log(没有长帧就不写,闲置零噪声):
* perf 60s frames=3600 long=4 max=180ms tags=zoom:3,save:1 domImgs=94
*
* 标签由各热路径主动打点:zoom(缩放提交)/ board(切画板)/ save(保存)/ preview(预览)/ thumb(生成缩略图)。
* 窗口不可见时 rAF 自动暂停,不产生开销。
*/
;(function (global) {
'use strict'
const LONG_MS = 50
const TAG_TTL = 900
// 测试可覆写:window.__IWB_PERF_WINDOW_MS__(默认 60s 一条汇总)
const WINDOW_MS = Number(global.__IWB_PERF_WINDOW_MS__) > 0 ? Number(global.__IWB_PERF_WINDOW_MS__) : 60000
let tagName = ''
let tagAt = 0
let raf = 0
let last = 0
let bucket = null
const recent = [] // 最近 20 条,便于诊断页/自动化测试直接读(不影响落盘)
const logLine = (line) => {
try {
recent.push(line)
if (recent.length > 20) recent.shift()
const S = global.IWBStorageFile
if (S && typeof S.logLine === 'function') { S.logLine(line); return }
if (global.console && global.console.warn) global.console.warn('[iwb] ' + line)
} catch (e) { /* ignore */ }
}
const blank = () => ({ at: Date.now(), n: 0, long: 0, max: 0, tags: Object.create(null) })
function tag (name) { tagName = String(name || ''); tagAt = Date.now() }
function flush (now) {
if (!bucket || now - bucket.at < WINDOW_MS) return
if (bucket.long > 0) {
const tags = Object.keys(bucket.tags).map((k) => k + ':' + bucket.tags[k]).join(',')
const imgs = (global.document && global.document.images) ? global.document.images.length : -1
logLine('perf ' + Math.round((now - bucket.at) / 1000) + 's frames=' + bucket.n + ' long=' + bucket.long +
' max=' + Math.round(bucket.max) + 'ms tags=' + (tags || '-') + ' domImgs=' + imgs)
}
bucket = blank()
}
function tick (t) {
raf = global.requestAnimationFrame(tick)
const dt = t - last
last = t
// 首帧、标签页休眠恢复、窗口最小化回来时 dt 会非常大,不算进统计
if (!(dt > 0) || dt > 3000) return
bucket.n++
if (dt > LONG_MS) {
bucket.long++
if (dt > bucket.max) bucket.max = dt
const name = (Date.now() - tagAt < TAG_TTL) ? tagName : 'idle'
bucket.tags[name] = (bucket.tags[name] || 0) + 1
}
flush(Date.now())
}
function start () {
if (raf || typeof global.requestAnimationFrame !== 'function') return
bucket = blank()
last = global.performance && global.performance.now ? global.performance.now() : Date.now()
raf = global.requestAnimationFrame(tick)
}
global.IWBPerf = { tag: tag, start: start, recent: recent }
// 默认不启动:正式包(对外)不能往 _boot.log 写性能采样。
// 只有构建时 IWB_PERF_PROBE=1 注入 window.__IWB_PERF_PROBE__,
// 或显式设置 localStorage.iwb_perf_probe='1' 时才开启(排查用)。
const wantProbe = global.__IWB_PERF_PROBE__ === 1 || global.__IWB_PERF_PROBE__ === true
if (wantProbe && typeof global.requestAnimationFrame === 'function') start()
})(typeof window !== 'undefined' ? window : globalThis)
+2
View File
@@ -497,6 +497,7 @@
// ── saveNow ────────────────────────────────────────────── // ── saveNow ──────────────────────────────────────────────
async function saveNow(ctx, override, requestedWsId) { async function saveNow(ctx, override, requestedWsId) {
try { window.IWBPerf && window.IWBPerf.tag('save') } catch (e) { /* ignore */ }
const { activeWsId, activeWsIdRef, applyLatest, clearSaveRecovery, composeWorkspaceList, edges, groups, nodes, refs, rememberSaveRecovery, saveDebounced, server, sessionsStore, setNotice, setSaveState, setWorkspaces, setWsRev, workspaces, wsRev, wsRevRef } = ctx const { activeWsId, activeWsIdRef, applyLatest, clearSaveRecovery, composeWorkspaceList, edges, groups, nodes, refs, rememberSaveRecovery, saveDebounced, server, sessionsStore, setNotice, setSaveState, setWorkspaces, setWsRev, workspaces, wsRev, wsRevRef } = ctx
iwbDebugCounter('saveNow', { explicit: !!override, nodes: override && override.nodes ? override.nodes.length : refs.nodes.length }) iwbDebugCounter('saveNow', { explicit: !!override, nodes: override && override.nodes ? override.nodes.length : refs.nodes.length })
const saveWsId = requestedWsId || activeWsIdRef.current || activeWsId const saveWsId = requestedWsId || activeWsIdRef.current || activeWsId
@@ -1347,6 +1348,7 @@
const live = refs.viewportLive const live = refs.viewportLive
refs.viewportLive = null refs.viewportLive = null
if (!live) return if (!live) return
try { window.IWBPerf && window.IWBPerf.tag('zoom') } catch (e) { /* ignore */ }
try { setViewport({ x: live.x, y: live.y, scale: live.scale }) } catch (e4) { /* ignore */ } try { setViewport({ x: live.x, y: live.y, scale: live.scale }) } catch (e4) { /* ignore */ }
}, 110) }, 110)
} catch (e5) { /* ignore */ } } catch (e5) { /* ignore */ }
+249 -56
View File
@@ -204,15 +204,45 @@ function EdgePath(props) {
function ImagePreview(props) { function ImagePreview(props) {
const list = (props.list && props.list.length) ? props.list : (props.src ? [props.src] : []) const list = (props.list && props.list.length) ? props.list : (props.src ? [props.src] : [])
const idx = Math.max(0, Math.min(props.idx || 0, Math.max(0, list.length - 1))) 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] const entry = list[idx]
// 当前显示用 URL:缩略图先出(秒显),空闲后再换原图;初值空串,由下面 effect 填入
const [cur, setCur] = useState('')
// 原图叠层:不复用 <img src> 直接替换 —— 换 src 必然整体重绘,观感是「小图糊一遍、大图再清一遍」。
// 现在缩略图当前景底图,原图解码完成后浮在上面淡入,观感是「同一张图逐渐变清晰」。
const [top, setTop] = useState('')
const [topIn, setTopIn] = useState(false)
// 显示框宽高比:缩略图自然尺寸只有 320px,若让 <img> 用 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 wheelRef = useRef(null)
const baseImgRef = useRef(null)
const wheelAtRef = useRef(0) 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 urlsRef = useRef(new Map()) // key -> { url, own }
const orderRef = useRef([]) // 保留顺序(最多 4 张,超出 revoke 最旧) const orderRef = useRef([])
// 当前张「原图解析完成」后的 src(objectURL / dataURL / 图床 URL)。复制时优先用它, const resolvedRef = useRef('') // 当前张「原图」解析结果(复制/下载优先用它)
// 避免拿还在等解析的占位缩略图,也避免把「条目引用对象」直接丢给 fetch。
const resolvedRef = useRef('')
const releaseKey = (key) => { const releaseKey = (key) => {
const it = urlsRef.current.get(key) const it = urlsRef.current.get(key)
if (!it) return if (!it) return
@@ -225,67 +255,202 @@ function ImagePreview(props) {
for (const key of Array.from(urlsRef.current.keys())) releaseKey(key) for (const key of Array.from(urlsRef.current.keys())) releaseKey(key)
urlsRef.current.clear(); orderRef.current = [] 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 entryKeyOf = (e) => 'out:' + (e.origIdb || '') + '|' + (e.idb || '') + '|' + (e.url || '') + '|' + (e.name || '')
const placeholderOf = (e) => (typeof e === 'string' ? e : ((e && (e.thumb || e.url)) || '')) const placeholderOf = (e) => (typeof e === 'string' ? e : ((e && (e.thumb || e.url)) || ''))
// 解析一张:原图(origIdb)优先 → 缩略图(idb)→ 图床 url;dataURL 转 Blob + objectURL,堆里不留 base64 // 把 IDB 取回的值统一转成 <img> 能用的 URL:Blob → objectURL;dataURL → Blob → objectURL
const resolveEntry = (e) => { const urlOfValue = (v, key, kind) => {
if (!e || typeof e === 'string' || !e.__gallery) return Promise.resolve(placeholderOf(e)) if (!v) return Promise.resolve('')
const key = entryKeyOf(e) if (typeof v === 'object' && typeof v.size === 'number') {
const hit = urlsRef.current.get(key) try { return Promise.resolve(remember(key, URL.createObjectURL(v), v, kind)) } catch (e) { return Promise.resolve('') }
if (hit) return Promise.resolve(hit.url) }
const ph = placeholderOf(e) const s = String(v)
return (e.origIdb ? IDB.get(e.origIdb).catch(() => null) : Promise.resolve(null)) if (s.indexOf('data:') !== 0) return Promise.resolve(s) // 图床/本地 URL 直接用
.then((v) => v || (e.idb ? IDB.get(e.idb).catch(() => null) : null)) return wBlobFromDataUrl(s).then((b) => {
.then(async (b64) => { if (!b) return ''
const raw = b64 || e.url || '' try { return remember(key, URL.createObjectURL(b), b, kind) } catch (e) { return '' }
if (!raw) return ph }).catch(() => '')
if (String(raw).indexOf('data:') !== 0) return String(raw) // 图床 URL 直接显示
const blob = await wBlobFromDataUrl(raw)
if (!blob) return ph
// 注册 Blob:预览里的「复制」拿到的就是这个 objectURL,
// 而线上 CSP 禁止 fetch(blob:),必须能从注册表直接取回原 Blob
const url = wRegisterBlobUrl(blob)
if (!url) return ph
urlsRef.current.set(key, { url, own: true })
orderRef.current.push(key)
while (orderRef.current.length > 4) releaseKey(orderRef.current[0])
return url
})
.catch(() => ph)
} }
const [cur, setCur] = useState(() => placeholderOf(entry)) // 兜底:只有 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)
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 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) : '') const entryKeyStr = (typeof entry === 'string') ? ('s:' + entry.length + ':' + entry.slice(0, 32)) : (entry ? entryKeyOf(entry) : '')
const go = (delta) => { const ni = (idx + delta + list.length) % list.length; props.onNav && props.onNav(ni) } // 邻张预取:只在停稳后做(滚动中预取等于白读),只进 objectURL 缓存、不改变当前显示
// v3.26.110:滚轮切图(上一张/下一张)。必须用原生非 passive 监听, const prefetchAround = (i) => {
// React 的 onWheel 是被动绑定,preventDefault 会无效(页面会跟着滚)。 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(() => { useEffect(() => {
const host = wheelRef.current const host = wheelRef.current
if (!host || list.length < 2) return if (!host || list.length < 2) return
const onWheel = (e) => { const onWheel = (e) => {
if (!e.deltaY) return if (!e.deltaY) return
e.preventDefault()
const now = Date.now() const now = Date.now()
if (now - wheelAtRef.current < 140) return // 触控板连续滚动时不要一张张飞过去 if (now - wheelAtRef.current < 140) return
wheelAtRef.current = now wheelAtRef.current = now
go(e.deltaY > 0 ? 1 : -1) go(e.deltaY > 0 ? 1 : -1)
} }
host.addEventListener('wheel', onWheel, { passive: false }) host.addEventListener('wheel', onWheel, { passive: true })
return () => { try { host.removeEventListener('wheel', onWheel) } catch (e) { /* ignore */ } } return () => { try { host.removeEventListener('wheel', onWheel) } catch (e) { /* ignore */ } }
}, [idx, list.length]) }, [list.length, idx])
// 当前张:先用已有 320px 缩略图/图床 url 占位,原图解析完成后替换 // 换列表(新一轮预览)时回到 props.idx
useEffect(() => { setIdx(Math.max(0, Math.min(props.idx || 0, Math.max(0, list.length - 1)))) }, [list])
// 当前张:先用缩略图秒出画面;连续滚轮期间不做重活,停 300ms 空闲后再把原图换上来
useEffect(() => { useEffect(() => {
let alive = true const my = ++seqRef.current
resolvedRef.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)) setCur(placeholderOf(entry))
resolveEntry(entry).then((u) => { if (alive && u) { resolvedRef.current = u; setCur(u) } }).catch(() => {}) loadThumb(entry).then((u) => { if (live() && u) setCur(u) }).catch(() => {})
return () => { alive = false } // 关键:滚动中**一张原图都不读**。每步读 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]) }, [idx, list.length, entryKeyStr])
// 预取相邻 ±1(只进缓存,不改变当前显示)
useEffect(() => { useEffect(() => {
if (list.length < 2) return if (!topIn) return undefined
const around = [list[(idx + 1) % list.length], list[(idx - 1 + list.length) % list.length]] const t = setTimeout(() => setSharp(true), 260) // 略大于 220ms 淡入
for (const e of around) if (e && typeof e !== 'string') resolveEntry(e).catch(() => {}) return () => clearTimeout(t)
}, [idx, list.length, entryKeyStr]) }, [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 并清空 // 关闭/卸载:revoke 全部 objectURL 并清空
useEffect(() => () => releaseAll(), []) useEffect(() => () => releaseAll(), [])
// 键盘:←/→ 切换预览,Esc 关闭 // 键盘:←/→ 切换预览,Esc 关闭
@@ -297,9 +462,21 @@ function ImagePreview(props) {
} }
window.addEventListener('keydown', onKey) window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey) return () => window.removeEventListener('keydown', onKey)
}, [idx, list.length]) }, [list.length, idx])
if (!list.length) return null if (!list.length) return null
const src = cur || placeholderOf(entry) 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) 只作最后回退, // 复制源:优先「本地已解析源」(原图 objectURL / 缩略图 dataURL),远程 http(s) 只作最后回退,
// 避免 fetch 远程图床被 CORS 拦下。src 与 <img src> 同源(组件内已解析),不把条目对象丢给 fetch。 // 避免 fetch 远程图床被 CORS 拦下。src 与 <img src> 同源(组件内已解析),不把条目对象丢给 fetch。
const copySrc = (() => { const copySrc = (() => {
@@ -310,7 +487,22 @@ function ImagePreview(props) {
})() })()
return el('div', { className: 'iwb-imgpreview', ref: wheelRef, onPointerDown: (e) => { if (e.target === e.currentTarget) props.onClose() } }, 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, list.length > 1 ? el('button', { className: 'iwb-prev-nav iwb-prev-left', title: '上一张(← 或滚轮向上)', onClick: (e) => { e.stopPropagation(); go(-1) } }, '‹') : null,
el('img', { src, alt: '预览', onClick: (e) => e.stopPropagation(), onKeyDown: () => {} }), 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, 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('div', { className: 'iwb-prev-bar', onClick: (e) => e.stopPropagation() },
el('span', { className: 'iwb-prev-count' }, (idx + 1) + ' / ' + list.length), el('span', { className: 'iwb-prev-count' }, (idx + 1) + ' / ' + list.length),
@@ -320,10 +512,9 @@ function ImagePreview(props) {
onClick: async () => { onClick: async () => {
try { try {
// 与图库条目复制共用同一个实现(app.js 的 copyImageToClipboard),不再各写一份。 // 与图库条目复制共用同一个实现(app.js 的 copyImageToClipboard),不再各写一份。
// v3.24.65:先等一次原图解析(resolveEntry 命中缓存时是同步返回)—— 否则刚点开就复制, // 先取原图**字节**(不是 URL):CSP 禁 fetch(blob:),只有真 Blob 才稳;占位缩略图只作兜底。
// 拿到的是 320px 占位缩略图;SVG 也只有在原图解析后才注册成 Blob 供光栅化。 const blob = await loadOriginalBlob(entry).catch(() => null)
const resolved = await resolveEntry(entry).catch(() => '') await copyImageToClipboard(blob || copySrc)
await copyImageToClipboard(resolved || copySrc)
props.onFlash && props.onFlash('已复制图片到剪贴板(PNG),可在画布空白处粘贴为参考图节点') props.onFlash && props.onFlash('已复制图片到剪贴板(PNG),可在画布空白处粘贴为参考图节点')
} catch (e) { props.onFlash && props.onFlash('复制失败:' + String((e && e.message) || e)) } } catch (e) { props.onFlash && props.onFlash('复制失败:' + String((e && e.message) || e)) }
}, },
@@ -333,8 +524,10 @@ function ImagePreview(props) {
title: '下载当前图片', title: '下载当前图片',
onClick: async () => { onClick: async () => {
// 同上:原图优先,占位缩略图只作最后兜底(此前 SVG 的原图在这里被下成 320px jpeg) // 同上:原图优先,占位缩略图只作最后兜底(此前 SVG 的原图在这里被下成 320px jpeg)
const resolved = await resolveEntry(entry).catch(() => '') // downloadUrl 只吃 URL:把字节登记成**可取回**的 objectURL(wBlobRefGet 能反查),否则下载链路取不到 Blob
downloadUrl(resolved || src, 'image.png') const blob = await loadOriginalBlob(entry).catch(() => null)
const blobUrl = (blob && typeof wRegisterBlobUrl === 'function') ? wRegisterBlobUrl(blob) : ''
downloadUrl(blobUrl || src, 'image.png')
}, },
}, I('download'), ' 下载'), }, I('download'), ' 下载'),
), ),
+48 -3
View File
@@ -58,6 +58,32 @@
// ── relay ────────────────────────────────────────────── // ── relay ──────────────────────────────────────────────
// v3.26.111(用户):图片节点外框要跟着图片比例走,边缘也要窄。
// 图片按宽度自适应(CSS 去掉了 340px 高度上限)后,把节点的 minHeight 放回最小值,
// 让 height:auto 按内容收边 —— 竖图不再上下留白、横图不再被默认 252 撑高。
// 每个节点只做一次(data.fitH 打标),之后用户手动拉伸不会被覆盖。
// 极端比例(超长竖图)改为收窄节点宽度,避免一张图占满一屏。
function fitRefNodeOnce (e, node, onUpdate) {
try {
const img = e && e.currentTarget
if (!img || !node || typeof onUpdate !== 'function') return
const nw = img.naturalWidth
const nh = img.naturalHeight
if (!nw || !nh) return
// ⚠️ 只改节点尺寸,**绝不重写 node.data**:2026-11-29 实测重写一次就把参考图弄坏了
// (data 里可能是引用对象 {__blob}/{__cache},整体覆盖会让图片变成占位图标)。
const curH = Number(node.h) || 0
if (curH && Math.abs(curH - 252) > 1) return // 已贴合过或用户手动调过高度,不再动
const aspect = nw / nh
const baseW = Number(node.w) || 320
const padX = 16
const maxImgH = 720
let w = baseW
if ((Math.max(120, baseW - padX)) / aspect > maxImgH) w = Math.round(maxImgH * aspect) + padX
onUpdate(node.id, { w: w, h: 56 })
} catch (err) { /* 自适应失败不影响显示 */ }
}
function renderRelayBody(node, props, ctx) { function renderRelayBody(node, props, ctx) {
return el('div', { className: 'iwb-node-body iwb-relay-body' }, return el('div', { className: 'iwb-node-body iwb-relay-body' },
el('span', { className: 'iwb-relay-ring' }, null), el('span', { className: 'iwb-relay-ring' }, null),
@@ -650,7 +676,9 @@
function renderRefBody(node, props, ctx) { function renderRefBody(node, props, ctx) {
const { onUpdate, stop } = ctx const { onUpdate, stop } = ctx
const d = node.data || {} const d = node.data || {}
const src = wResolveImg(d.localRef) || wResolveImg(d.data) || d.url // 第三兜底也必须过 wResolveImg:C3 之后 url 可能是引用对象 {__blob}/{__cache},
// 直接 String() 会变成 "[object Object]" ⇒ <img> 破图(2026-11-29 实测 45 个节点踩中)。
const src = wResolveImg(d.localRef) || wResolveImg(d.data) || wResolveImg(d.url)
const hasImg = !!src const hasImg = !!src
const commitRefUrl = (event) => { const commitRefUrl = (event) => {
const root = event && event.currentTarget && event.currentTarget.closest ? event.currentTarget.closest('.iwb-ref-body') : null const root = event && event.currentTarget && event.currentTarget.closest ? event.currentTarget.closest('.iwb-ref-body') : null
@@ -689,7 +717,24 @@
return el('div', { className: 'iwb-node-body iwb-ref-body' }, return el('div', { className: 'iwb-node-body iwb-ref-body' },
hasImg hasImg
? el('div', { className: 'iwb-ref-show' }, ? el('div', { className: 'iwb-ref-show' },
el('img', { className: 'iwb-ref-single', decoding: 'async', fetchPriority: 'low', src: wPreviewUrlOf((typeof wImgSrcForNode === 'function' ? wImgSrcForNode : wDisplayThumbOf)(wThumbSrc(src), Math.min(320, (props.node && props.node.w) || 280))), alt: '图片', draggable: false, onError: (e) => { try { const ov = wThumbSrc(src); if (ov && e.currentTarget && e.currentTarget.src !== ov) e.currentTarget.src = ov } catch (err) { /* ignore */ } }, title: '双击放大 · 单击可拖动' }), el('img', { className: 'iwb-ref-single', decoding: 'async', fetchPriority: 'low', src: wPreviewUrlOf((typeof wImgSrcForNode === 'function' ? wImgSrcForNode : wDisplayThumbOf)(wThumbSrc(src), Math.min(320, (props.node && props.node.w) || 280))), alt: '图片', draggable: false, onLoad: (e) => { fitRefNodeOnce(e, props.node, onUpdate) }, onError: (e) => {
// 第一次失败先退回原图;第二次仍失败 → 标记容器,换成「源已失效 · 双击重新导入」占位
// (用户 2026-11-29:破图图标会被误当成渲染 bug,必须明确告知是图片源丢了)
try {
const img = e.currentTarget
if (img && img.dataset && img.dataset.fb !== '1') {
img.dataset.fb = '1'
const ov = wThumbSrc(src)
if (ov && img.src !== ov) { img.src = ov; return }
}
const host = img && img.closest ? img.closest('.iwb-ref-show') : null
if (host) host.classList.add('is-broken')
} catch (err) { /* ignore */ }
}, title: '双击放大 · 单击可拖动' }),
el('div', { className: 'iwb-ref-broken', title: '图片源已失效,双击重新导入', onDoubleClick: (e) => { e.stopPropagation(); if (refFileInput) refFileInput.click() } },
el('span', { className: 'iwb-ref-broken-t' }, '图片源已失效'),
el('span', { className: 'iwb-ref-broken-s' }, '双击重新导入'),
),
(typeof d.url === 'string' && d.url) ? el('div', { className: 'iwb-ref-url-current', title: d.url }, 'URL 图片') : null, (typeof d.url === 'string' && d.url) ? el('div', { className: 'iwb-ref-url-current', title: d.url }, 'URL 图片') : null,
) )
: el('div', { className: 'iwb-ref-emptybox', title: '单击选中 · 双击上传图片', onDoubleClick: (e) => { e.stopPropagation(); if (refFileInput) refFileInput.click() } }, : el('div', { className: 'iwb-ref-emptybox', title: '单击选中 · 双击上传图片', onDoubleClick: (e) => { e.stopPropagation(); if (refFileInput) refFileInput.click() } },
@@ -1119,7 +1164,7 @@
function lodThumbOf(node) { function lodThumbOf(node) {
const d = node.data || {} const d = node.data || {}
if (node.type === 'ref') { if (node.type === 'ref') {
const s = wResolveImg(d.data) || d.url const s = wResolveImg(d.data) || wResolveImg(d.url)
return s ? wThumbSrc(s) : '' return s ? wThumbSrc(s) : ''
} }
if (node.type === 'gen') { if (node.type === 'gen') {
+20 -1
View File
@@ -324,7 +324,7 @@ button { font-family: inherit; }
.iwb-task-ref { object-fit: cover; border-radius: var(--iwb-radius-chip); border: 1px solid var(--iwb-border); cursor: zoom-in; } .iwb-task-ref { object-fit: cover; border-radius: var(--iwb-radius-chip); border: 1px solid var(--iwb-border); cursor: zoom-in; }
.iwb-ref-head { display: flex; align-items: center; gap: var(--iwb-space-8); margin-bottom: var(--iwb-space-4); } .iwb-ref-head { display: flex; align-items: center; gap: var(--iwb-space-8); margin-bottom: var(--iwb-space-4); }
.iwb-ref-single { width: 100%; min-height: 60px; max-height: 340px; object-fit: contain; object-position: center; border-radius: var(--iwb-radius-chip); border: 1px solid var(--iwb-border); background: var(--iwb-field); cursor: move; } .iwb-ref-single { width: 100%; height: auto; min-height: 48px; max-height: none; object-fit: contain; object-position: center; border-radius: var(--iwb-radius-chip); border: 1px solid var(--iwb-border); background: var(--iwb-field); cursor: move; }
.iwb-history { position: absolute; left: 12px; right: 12px; bottom: 46px; background: var(--iwb-panel); border: 1px solid var(--iwb-border); border-radius: var(--iwb-radius-panel); z-index: 30; box-shadow: var(--iwb-elevation-2); padding: 8px 12px; max-height: 180px; display: flex; flex-direction: column; } .iwb-history { position: absolute; left: 12px; right: 12px; bottom: 46px; background: var(--iwb-panel); border: 1px solid var(--iwb-border); border-radius: var(--iwb-radius-panel); z-index: 30; box-shadow: var(--iwb-elevation-2); padding: 8px 12px; max-height: 180px; display: flex; flex-direction: column; }
.iwb-history-grid { display: flex; gap: 8px; overflow-x: auto; padding: 8px 2px; flex: 1; } .iwb-history-grid { display: flex; gap: 8px; overflow-x: auto; padding: 8px 2px; flex: 1; }
.iwb-history-item { position: relative; flex: 0 0 110px; } .iwb-history-item { position: relative; flex: 0 0 110px; }
@@ -345,6 +345,12 @@ button { font-family: inherit; }
.iwb-ref-url-input { min-width: 0; flex: 1 1 auto; font-size: var(--iwb-font-xs); } .iwb-ref-url-input { min-width: 0; flex: 1 1 auto; font-size: var(--iwb-font-xs); }
.iwb-ref-url-current { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--iwb-text2); font-size: var(--iwb-font-2xs); } .iwb-ref-url-current { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--iwb-text2); font-size: var(--iwb-font-2xs); }
.iwb-ref-show { flex: 1 1 auto; min-height: 0; display: flex; align-items: center; justify-content: center; } .iwb-ref-show { flex: 1 1 auto; min-height: 0; display: flex; align-items: center; justify-content: center; }
/* v3.26.111:图片源失效的明确占位(破图图标会被误认为渲染 bug) */
.iwb-ref-broken { display: none; flex-direction: column; align-items: center; justify-content: center; gap: var(--iwb-space-4); width: 100%; min-height: 120px; border: 1px dashed var(--iwb-border); border-radius: var(--iwb-radius-chip); background: var(--iwb-field); color: var(--iwb-text2); }
.iwb-ref-broken-t { font-size: var(--iwb-font-sm); }
.iwb-ref-broken-s { font-size: var(--iwb-font-xs); opacity: 0.8; }
.iwb-ref-show.is-broken .iwb-ref-single { display: none; }
.iwb-ref-show.is-broken .iwb-ref-broken { display: flex; }
.iwb-ref-miniactions .iwb-btn { font-size: var(--iwb-font-2xs); padding: var(--iwb-space-2) var(--iwb-space-6); text-decoration: none; } .iwb-ref-miniactions .iwb-btn { font-size: var(--iwb-font-2xs); padding: var(--iwb-space-2) var(--iwb-space-6); text-decoration: none; }
.iwb-task-ref { width: 28px; height: 28px; } .iwb-task-ref { width: 28px; height: 28px; }
.iwb-refmini { position: relative; } .iwb-refmini { position: relative; }
@@ -535,6 +541,8 @@ button { font-family: inherit; }
/* ---- 参考图节点:图片随框自适应 / 底部操作栏 / 固定高度填满 ---- */ /* ---- 参考图节点:图片随框自适应 / 底部操作栏 / 固定高度填满 ---- */
.iwb-ref-body { display: flex; flex-direction: column; gap: var(--iwb-space-6); min-height: 0; position: relative; } .iwb-ref-body { display: flex; flex-direction: column; gap: var(--iwb-space-6); min-height: 0; position: relative; }
/* v3.26.111:图片节点的内边距收窄(用户:外框边缘宽了一点)。只在参考图节点上收紧,其他节点不动。 */
.iwb-ref-body { padding: var(--iwb-space-6) var(--iwb-space-8); }
.iwb-ref-foot { flex: 0 0 auto; display: flex; align-items: center; justify-content: space-between; gap: var(--iwb-space-6); } .iwb-ref-foot { flex: 0 0 auto; display: flex; align-items: center; justify-content: space-between; gap: var(--iwb-space-6); }
.iwb-node-fixed .iwb-ref-single { flex: 1 1 auto; min-height: 0; max-height: none; height: auto; } .iwb-node-fixed .iwb-ref-single { flex: 1 1 auto; min-height: 0; max-height: none; height: auto; }
.iwb-node-fixed .iwb-ref-show { flex: 1 1 auto; min-height: 0; } .iwb-node-fixed .iwb-ref-show { flex: 1 1 auto; min-height: 0; }
@@ -968,6 +976,17 @@ body .iwb-history-embedded .iwb-history-item.iwb-history-selected:hover img {
.iwb-imgpreview { position: fixed; inset: 0; background: rgba(10, 12, 18, 0.92); z-index: var(--iwb-z-preview); display: flex; align-items: center; justify-content: center; cursor: zoom-out; } .iwb-imgpreview { position: fixed; inset: 0; background: rgba(10, 12, 18, 0.92); z-index: var(--iwb-z-preview); display: flex; align-items: center; justify-content: center; cursor: zoom-out; }
/* 预览图自适应宽+高:同时约束横向与纵向,保持宽高比居中显示,不溢出(图库预览已取完整原图,可能很大/超高/超宽) */ /* 预览图自适应宽+高:同时约束横向与纵向,保持宽高比居中显示,不溢出(图库预览已取完整原图,可能很大/超高/超宽) */
.iwb-imgpreview img { max-width: 92vw; max-height: 88vh; width: auto; height: auto; object-fit: contain; border-radius: 8px; box-shadow: 0 8px 40px rgba(0,0,0,0.5); cursor: default; } .iwb-imgpreview img { max-width: 92vw; max-height: 88vh; width: auto; height: auto; object-fit: contain; border-radius: 8px; box-shadow: 0 8px 40px rgba(0,0,0,0.5); cursor: default; }
/* 预览两层叠加:底图=缩略图(秒显、与最终图同一个框),叠层=原图(解码完成后淡入)。
为什么不直接换 <img src>:换 src 是整块重绘,用户看到「先糊一遍、再清一遍」两次显示,很跳。 */
.iwb-prev-stage { position: relative; display: inline-flex; align-items: center; justify-content: center; max-width: 92vw; max-height: 88vh; }
/* 定框后两层都要填满同一个框:缩略图被放大到最终尺寸(不再只有 320px 宽),原图再淡入覆盖 */
.iwb-prev-stage.is-sized { flex: 0 0 auto; }
.iwb-prev-stage.is-sized img { display: block; object-fit: contain; }
/* 底图是 320px 放大,直接铺满会有明显像素块:先糊一点(2px,只做柔化不做雾化),原图淡入后自然被盖掉。 */
.iwb-prev-stage.is-blur img { filter: blur(1px); }
.iwb-prev-layer { position: absolute; inset: 0; background-repeat: no-repeat; background-position: center; background-size: contain; border-radius: var(--iwb-radius-control); box-shadow: var(--iwb-elevation-3); opacity: 0; transition: opacity 220ms ease; pointer-events: none; }
.iwb-prev-layer.is-in { opacity: 1; }
@media (prefers-reduced-motion: reduce) { .iwb-prev-layer { transition: none; } }
.iwb-prev-nav { position: fixed; top: 50%; transform: translateY(-50%); width: 46px; height: 64px; border: none; border-radius: 8px; background: rgba(255, 255, 255, 0.1); color: #fff; font-size: 30px; cursor: pointer; z-index: 101; } .iwb-prev-nav { position: fixed; top: 50%; transform: translateY(-50%); width: 46px; height: 64px; border: none; border-radius: 8px; background: rgba(255, 255, 255, 0.1); color: #fff; font-size: 30px; cursor: pointer; z-index: 101; }
.iwb-prev-nav:hover { background: rgba(255, 255, 255, 0.22); } .iwb-prev-nav:hover { background: rgba(255, 255, 255, 0.22); }
.iwb-prev-left { left: 18px; } .iwb-prev-left { left: 18px; }
+16 -10
View File
@@ -48,8 +48,8 @@ const NUMERIC = [
['W_OBJURL_MAX', appJs, 50], ['W_OBJURL_MAX', appJs, 50],
['W_BLOBREF_MAX', appJs, 50], ['W_BLOBREF_MAX', appJs, 50],
['DISPLAY_THUMB_CACHE_MAX', appJs, 300], ['DISPLAY_THUMB_CACHE_MAX', appJs, 300],
// v3.26.34:缩略图 640px(768 时单张 500~900KB) // v3.26.109:缩略图 1024px(640 时 dpr=2、节点 400px 就会解码原图 → footprint 峰值 2.7G)
['DISPLAY_THUMB_MAX', appJs, 640], ['DISPLAY_THUMB_MAX', appJs, 1024],
['outThumbCacheMax', appJs, 400], ['outThumbCacheMax', appJs, 400],
['W_MAX_LOADED_BOARDS', appJs, 2], ['W_MAX_LOADED_BOARDS', appJs, 2],
['W_SESSION_MAX', sessStore, 5], ['W_SESSION_MAX', sessStore, 5],
@@ -72,16 +72,22 @@ assert("IDB_REF_PREFIX = 'ref_'(legacy 形态)", /const IDB_REF_PREFIX = 're
assert("文档记录了 IDB_REF_PREFIX = 'ref_'", factsDoc.includes("IDB_REF_PREFIX = 'ref_'")) assert("文档记录了 IDB_REF_PREFIX = 'ref_'", factsDoc.includes("IDB_REF_PREFIX = 'ref_'"))
assert('W_IMG_BLOB_PRIMARY_DEFAULT = true(新写入主通道启用)', /const W_IMG_BLOB_PRIMARY_DEFAULT = true/.test(appJs)) assert('W_IMG_BLOB_PRIMARY_DEFAULT = true(新写入主通道启用)', /const W_IMG_BLOB_PRIMARY_DEFAULT = true/.test(appJs))
// ── 3. 视口裁剪余量:必须是 240,且不得回退成 560 ───────────────────────── // ── 3. 视口裁剪余量:宽边距 240 / 带图节点 80,且不得回退成 560 ─────────────
// v3.26.109:cullRect 从 app.js 收编到 src/canvas-geometry.js(cullRectsOf),
// 带图节点改用 80 的紧边距,减少屏幕外节点常驻的解码位图(内存 C)。
console.log('3) 视口裁剪余量(禁止把 v3.80.0 的 ±560 写回来)') console.log('3) 视口裁剪余量(禁止把 v3.80.0 的 ±560 写回来)')
const cullStart = appJs.indexOf('const cullRect = React.useMemo') const geomJs = read('src/canvas-geometry.js')
const cullEnd = appJs.indexOf('const nodeVisible = (n) =>') const cullStart = geomJs.indexOf('const CULL_PAD_WIDE = 240')
assert('定位到 cullRect 代码块', cullStart > 0 && cullEnd > cullStart) const cullEnd = geomJs.indexOf('function nodeVisibleIn')
assert('定位到 cullRectsOf 代码块', cullStart > 0 && cullEnd > cullStart)
if (cullStart > 0 && cullEnd > cullStart) { if (cullStart > 0 && cullEnd > cullStart) {
const cull = appJs.slice(cullStart, cullEnd) const cull = geomJs.slice(cullStart, cullEnd)
const has240 = (cull.match(/- 240|\+ 240/g) || []).length assert('宽边距常量是 240', /CULL_PAD_WIDE = 240/.test(cull))
assert('cullRect 恰好 4 处 240(left/top 减、right/bottom 加)', has240 === 4, '实际 ' + has240) assert('带图节点紧边距是 80', /CULL_PAD_TIGHT = 80/.test(cull))
assert('cullRect 不含 560(历史值已废止)', !/560/.test(cull)) const hasPad = (cull.match(/- pad|\+ pad/g) || []).length
assert('裁剪矩形 4 条边都按 pad 收放', hasPad === 4, '实际 ' + hasPad)
assert('裁剪矩形不含 560(历史值已废止)', !/560/.test(cull))
assert('app.js 只做装配(不再内联 cullRect 数值)', !/const cullRect = React\.useMemo/.test(appJs))
assert('文档记录了 240 余量', factsDoc.includes('240')) assert('文档记录了 240 余量', factsDoc.includes('240'))
assert('文档未把 560 当现值', !/余量.{0,6}560/.test(factsDoc)) assert('文档未把 560 当现值', !/余量.{0,6}560/.test(factsDoc))
} }
+2
View File
@@ -26,6 +26,7 @@
"IWBGenerationSizePolicy", "IWBGenerationSizePolicy",
"IWBGenerationState", "IWBGenerationState",
"IWBImageBlobStore", "IWBImageBlobStore",
"IWBImageCacheMigrate",
"IWBImageCompress", "IWBImageCompress",
"IWBImageDisplayThumb", "IWBImageDisplayThumb",
"IWBImageFileRef", "IWBImageFileRef",
@@ -35,6 +36,7 @@
"IWBMiniMapFit", "IWBMiniMapFit",
"IWBNativeClipboard", "IWBNativeClipboard",
"IWBNodeBodies", "IWBNodeBodies",
"IWBPerf",
"IWBPluginApiImages", "IWBPluginApiImages",
"IWBPluginData", "IWBPluginData",
"IWBPluginGallery", "IWBPluginGallery",
+2
View File
@@ -75,6 +75,8 @@
"theme-tokens.js", "theme-tokens.js",
"canvas-grid.js", "canvas-grid.js",
"image-display-thumb.js", "image-display-thumb.js",
"image-cache-migrate.js",
"runtime-frame-probe.js",
"image-remote-cache.js", "image-remote-cache.js",
"gallery-sync.js", "gallery-sync.js",
"image-thumb-pick.js", "image-thumb-pick.js",
+3
View File
@@ -7,6 +7,9 @@
// 纪律:只增不减;新增全局导出后若 typecheck 报 TS2339,就在这里补一行。 // 纪律:只增不减;新增全局导出后若 typecheck 报 TS2339,就在这里补一行。
interface Window { interface Window {
// 帧时长探针(v3.26.111)
IWBPerf?: any
IWBImageCacheMigrate?: any
// 桌面壳 / 外观(v3.25.14) // 桌面壳 / 外观(v3.25.14)
IWBUIShell?: any IWBUIShell?: any
IWBUIApearance?: any IWBUIApearance?: any