From e3d2e449e14a630301175e92a820be352a07dff6 Mon Sep 17 00:00:00 2001 From: qiqi Date: Wed, 25 Nov 2026 07:12:55 +0800 Subject: [PATCH] =?UTF-8?q?feat(album):=20=E7=9B=B8=E5=86=8C=E8=8A=82?= =?UTF-8?q?=E7=82=B9=E5=AE=BF=E4=B8=BB=E4=BE=A7=E2=80=94=E2=80=94=E5=A4=9A?= =?UTF-8?q?=E5=9B=BE=E6=BA=90=E4=BB=BB=E5=8A=A1=E5=B1=95=E5=BC=80(?= =?UTF-8?q?=E4=B8=80=E5=9B=BE=E4=B8=80=E4=BB=BB=E5=8A=A1/=E6=89=B9?= =?UTF-8?q?=E9=87=8F=E5=88=86=E6=89=B9)+=E7=BB=84=E5=90=88=E6=89=87?= =?UTF-8?q?=E5=87=BA+ctx.images(=E5=BC=95=E7=94=A8/=E5=AF=BC=E5=85=A5)+{?= =?UTF-8?q?=5F=5Ffile}=E6=9C=AC=E5=9C=B0=E6=96=87=E4=BB=B6=E5=BC=95?= =?UTF-8?q?=E7=94=A8+=E4=BF=9D=E7=95=99=E5=8E=9F=E5=9B=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CONTRIBUTING.md | 4 +- app.js | 29 +- docs/standards/architecture-current-state.md | 8 +- package.json | 2 +- plugins/album/main.js | 552 +++++++++++++++++++ plugins/album/manifest.json | 16 + plugins/album/styles.css | 48 ++ plugins/index.json | 11 + scripts/build.js | 2 + scripts/sync-plugins-from-repo.js | 2 +- src-tauri/src/lib.rs | 25 +- src/canvas-geometry.js | 6 +- src/generation-task-graph.js | 63 ++- src/image-file-ref.js | 103 ++++ src/plugin-api-images.js | 68 +++ src/plugin-host.js | 2 +- tests/album-task-graph-test.js | 113 ++++ tests/fixtures/iwb-app-global-reads.json | 2 + tests/fixtures/iwb-source-modules-order.json | 2 + tests/plugin-host-test.js | 2 +- tests/source-text-ratchet-test.js | 15 +- types/iwb-globals.d.ts | 2 + 22 files changed, 1055 insertions(+), 22 deletions(-) create mode 100644 plugins/album/main.js create mode 100644 plugins/album/manifest.json create mode 100644 plugins/album/styles.css create mode 100644 src/image-file-ref.js create mode 100644 src/plugin-api-images.js create mode 100644 tests/album-task-graph-test.js diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index dd68e47..557503b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -40,7 +40,7 @@ build esbuild 打包到 dist/(单 dist/app.js = src/ 模块按序 node --check app.js 与 dist/app.js 语法 check-dist.js 产物体检 lint ESLint(src/ + app.js,正确性规则) -test:unit 125 个单测文件(jsdom 契约测试;2026-11-07 新增 sync-facts-guard(事实一致性)/ _helpers/source(统一源文本);2026-11-12 新增 provider-ping(测速 no-cors 兜底)) +test:unit 126 个单测文件(jsdom 契约测试;2026-11-07 新增 sync-facts-guard(事实一致性)/ _helpers/source(统一源文本);2026-11-12 新增 provider-ping(测速 no-cors 兜底)) test relay-task-graph-fixture + iwb-v32-web-test test:facts 事实基线守门(见 §5) typecheck 渐进类型检查(tsc --noEmit;范围 = src/*.js,不含 app.js) @@ -102,7 +102,7 @@ IWB_WRITE_BOUNDARY_SNAPSHOT=1 node tests/architecture-boundary-guard-test.js # | 守卫 | 位置 | 现在的上限 | |---|---|---| -| `app.js` 总行数 | `tests/source-text-ratchet-test.js` `MAX_APP_JS_LINES` | **9,134**(另守「占总源码 ≤ 40%」,见 `MAX_APP_JS_SHARE`) | +| `app.js` 总行数 | `tests/source-text-ratchet-test.js` `MAX_APP_JS_LINES` | **9,161**(另守「占总源码 ≤ 40%」,见 `MAX_APP_JS_SHARE`) | | `Workbench()` 行数 | 同上 `MAX_WORKBENCH_LINES` | **3,046** | | 单组件行数(不含 Workbench)| 同上 `MAX_APP_COMPONENT_LINES` | **423** | diff --git a/app.js b/app.js index 115c678..975b362 100644 --- a/app.js +++ b/app.js @@ -19,6 +19,8 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct // 生成结果精简/合并模块(src/generation-results-store.js)。⚠️ 必须在 IIFE 最顶部取: // 页面加载时就会跑一次保存,声明若在后面会命中 TDZ(异常被 catch 吞掉 ⇒ 落盘退回未精简的 result)。 const GenerationResults = (typeof window !== 'undefined' && window.IWBGenerationResults) || null + // 本地文件引用(2026-11-26 相册):{__file:'/abs/a.png'} 只存路径,按需读盘 + const IWImageFileRef = (typeof window !== 'undefined' && window.IWBImageFileRef) || null // ========== 桌面端(Tauri v2)适配层 ========== // 仅在 Tauri 内生效:网页版没有 window.__TAURI__ ⇒ 所有分支都走原逻辑,行为零变化。 @@ -882,9 +884,11 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct let wImgUrlBumpTimer = null function wIsBlobRef(v) { return !!(v && typeof v === 'object' && !Array.isArray(v) && typeof v.__blob === 'string' && v.__blob) } function wIsCacheRef(v) { return !!(v && typeof v === 'object' && !Array.isArray(v) && typeof v.__cache === 'string' && v.__cache) } + function wIsFileRef(v) { return !!(IWImageFileRef && IWImageFileRef.is(v)) } function wImgRefKey(v) { if (wIsBlobRef(v)) return 'b:' + String(v.__blob) if (wIsCacheRef(v)) return 'c:' + String(v.__cache) + if (wIsFileRef(v)) return 'f:' + String(v.__file) return '' } // 一张画布上几十张图会在同一帧内陆续解析完成:合并成一次节点级重渲染(避免 N 次 setState) @@ -907,7 +911,7 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct wImgUrlPending.add(key) const job = wIsBlobRef(v) ? (wImageBlobStore() ? wImageBlobStore().getBlob(v.__blob) : Promise.resolve(null)) - : iwbCacheBlob(v.__cache) + : (wIsFileRef(v) ? IWImageFileRef.readBlob(v.__file) : iwbCacheBlob(v.__cache)) // 解析 Promise 存进 wImgUrlPendingPromise ⇒ 供 wResolveImgAsync 等待(预览类操作需要 URL 字符串) const p = Promise.resolve(job).then((blob) => { wImgUrlPending.delete(key) @@ -979,6 +983,8 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct try { return await wImageBlobStore().resolveDataUrl(v.__blob) } catch (e) { return '' } } if (wIsCacheRef(v)) { try { return (await iwbCacheRead(v.__cache)) || '' } catch (e) { return '' } } + // 本地文件引用:生成/预览时按需读盘(用完即弃,不复制字节) + if (wIsFileRef(v)) { try { return (await IWImageFileRef.readDataUrl(v.__file)) || '' } catch (e) { return '' } } return '' } // 生成参考图参数:在**发请求前**解析成真实字节(本地文件名原样透传,不含字节) @@ -1002,6 +1008,14 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct const v = d[f] if (v && typeof v === 'object') { const got = await wImgRefDataUrl(v); if (got) d[f] = got } } + // 相册(outKind:'images'):items[].src 是引用对象,导出时同样还原成 base64 + if (d.outKind === 'images' && Array.isArray(d.items)) { + d.items = await Promise.all(d.items.map(async (it) => { + if (!it || !it.src || typeof it.src !== 'object') return it + const got = await wImgRefDataUrl(it.src) + return got ? Object.assign({}, it, { src: got }) : it + })) + } out.push(Object.assign({}, n, { data: d })) } return out @@ -4190,6 +4204,8 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct }) return } + // 保留原图(2026-11-26 相册):显式要求时不压缩,直接把原始字节引用化(分辨率不损失) + if (o.keepOriginal) { finalize(dataUrl); return } const noResizeMime = /^image\/(gif)$/i.test(srcMime) if (!canResize || noResizeMime) { finalize(dataUrl); return } let settled = false @@ -8921,6 +8937,17 @@ items.push(el('button', { key: 'bgc', className: 'iwb-ctx-item', onClick: (e) => grouplib: () => ((typeof window !== 'undefined' && window.IWBPluginGroupLib) ? window.IWBPluginGroupLib.api() : {}), promptlib: () => ((typeof window !== 'undefined' && window.IWBPluginPromptLib) ? window.IWBPluginPromptLib.api() : {}), // 插件文件能力(v3.26.36):沙箱目录 plugin-data//files,供插件自持图片 + // 插件图片能力(2026-11-26):相册需要「只引用本地文件」+「把字节写进宿主存储」两条 + images: (ctx) => { + const M = (typeof window !== 'undefined' && window.IWBPluginApiImages) ? window.IWBPluginApiImages : null + if (!M || !IWImageFileRef) return { canReference: () => false } + return M.create({ + fileRef: IWImageFileRef, + importDataUrl: (url, opts) => new Promise((resolve) => { try { wImportImage(url, opts || {}, (p) => resolve(p || { ok: false, error: 'import-failed' })) } catch (e) { resolve({ ok: false, error: 'import-threw' }) } }), + readDataUrl: (v) => (typeof v === 'string' ? Promise.resolve(v) : wImgRefDataUrl(v)), + thumbUrlOf: (v) => wDisplayThumbOf(v), + })(ctx) + }, files: (ctx) => { const F = (typeof window !== 'undefined' && window.IWBStorageFile) ? window.IWBStorageFile.pluginFiles : null const need = () => { if (!F) throw new Error('文件能力未就绪(资料目录尚未初始化)'); return F } diff --git a/docs/standards/architecture-current-state.md b/docs/standards/architecture-current-state.md index 817ada6..cb82eb5 100644 --- a/docs/standards/architecture-current-state.md +++ b/docs/standards/architecture-current-state.md @@ -22,7 +22,7 @@ - 图片**新写入主通道 = IndexedDB Blob `{__blob}` / key `imgblob__`** (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`。**两处阈值并存,含义不同**。 - 单测是**源码契约测试**:`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 **9,134 行**(**双层预算**:绝对上限 9,134 / 占总源码 ≤ 40%,现 **30.6%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **3,044 行**(上限 **3,046**,余量 2;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **108** 个模块 / 20,763 行,`sourceModules` 108 项;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 **9,161 行**(**双层预算**:绝对上限 9,161 / 占总源码 ≤ 40%,现 **30.4%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **3,044 行**(上限 **3,046**,余量 2;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **110** 个模块 / 20,999 行,`sourceModules` 110 项;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`。 ## 2. 门禁与环境现状 @@ -167,7 +167,7 @@ - 同一张图被 3 个节点引用、hydrate 成 3 个不同 objectURL 时,preview/display 缓存各自 miss → 重复解码(与 F2 相邻)。 - **F10|`refs.genScheduler` 是桩** (A) → 未接线,暂无运行时影响(P3)。 - **F11|已建但未接线的模块层(2026-10-17 接线审计;2026-10-18 复核更正)** (A) - - **判定法**:`global.X =` / `root.X =` 判「导出」;跨文件裸引用判「读」;排除自合并(`src/runtime-constants.js:9`)。`app.js` 是**唯一生产消费者**(无 HTML 入口;`sw.js` 不引用模块全局)。**108 个模块中 59 个导出**被 `app.js` 读取;其余为未接线 / 仅测试 / 零引用(见下)。 + - **判定法**:`global.X =` / `root.X =` 判「导出」;跨文件裸引用判「读」;排除自合并(`src/runtime-constants.js:9`)。`app.js` 是**唯一生产消费者**(无 HTML 入口;`sw.js` 不引用模块全局)。**110 个模块中 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 地基。) - **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` 自注册后读回(装载路径)。 @@ -183,7 +183,7 @@ | `storage-reconcile` | 存储对账(`createReconciler`/`check`) | 内联对账 | 存储层收口 | | `runtime-recovery-runner` | 执行恢复候选(`candidate`/`valid`/`run`) | 内联恢复 | 断点恢复 | | `canvas-domain` | 画布域模型(`commit`/`updateNode`/`deleteNodes`…) | `CanvasStore` 那一套 | Workbench 解耦(P2-9) | - - **耦合面已冻结**:`tests/architecture-boundary-guard-test.js`(进 `npm run test:unit` 末环)冻结 app.js↔src 耦合面(**89** 项)与 `sourceModules` 顺序(**108** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。 + - **耦合面已冻结**:`tests/architecture-boundary-guard-test.js`(进 `npm run test:unit` 末环)冻结 app.js↔src 耦合面(**91** 项)与 `sourceModules` 顺序(**110** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。 ## 12. 易踩的坑 @@ -254,7 +254,7 @@ **信任模型(必须明示)**:形态 A 的插件是**可信代码**(与核心同权限、无沙箱);启停与设置是 UX 与可维护性手段,**不是安全边界**(同 §13.27 教训:前端开关一定可被绕过)。 -**守门与快照**:`tests/architecture-boundary-guard-test.js` 冻结「app.js ↔ src 耦合面」(**89** 项)与 `sourceModules` 顺序(**108** 项);新增模块、新增耦合、新增 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 耦合面」(**91** 项)与 `sourceModules` 顺序(**110** 项);新增模块、新增耦合、新增 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 规则三的同一失败模式)。 diff --git a/package.json b/package.json index f827782..dcba53f 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ "app:build": "tauri build", "lint": "eslint src app.js", "test": "node tests/relay-task-graph-fixture-test.js && node tests/plugin-style-node-test.js && node tests/inherit-text-test.js", - "test:unit": "node tests/plugin-files-policy-test.js && node tests/theme-plugin-tokens-test.js && node tests/design-tokens-component-doc-test.js && node tests/theme-static-snapshot-test.js && node tests/overlay-layer-test.js && node tests/settings-scope-test.js && node tests/node-scope-test.js && node tests/appearance-v2-test.js && node tests/image-prompt-cover-test.js && node tests/unit-test.js && node tests/canvas-actions-test.js && node tests/canvas-performance-test.js && node tests/canvas-drag-performance-test.js && node tests/resize-observer-performance-test.js && node tests/node-drag-jank-test.js && node tests/edge-graph-performance-test.js && node tests/persistence-export-images-test.js && node tests/settings-hotkeys-size-presets-test.js && node tests/custom-size-validation-test.js && node tests/image-node-performance-test.js && node tests/drag-frame-performance-test.js && node tests/canvas-edge-memo-test.js && node tests/canvas-node-transform-test.js && node tests/canvas-dot-zoom-test.js && node tests/duplicate-ws-fresh-source-test.js && node tests/single-canvas-shell-test.js && node tests/navigation-layout-test.js && node tests/home-canvas-library-test.js && node tests/left-resource-layout-test.js && node tests/interface-hierarchy-test.js && node tests/three-page-layout-test.js && node tests/page-chrome-regression-test.js && node tests/task-cache-test.js && node tests/generation-endpoint-test.js && node tests/storage-config-shape-test.js && node tests/storage-zip-test.js && node tests/canvas-node-factory-test.js && node tests/runtime-error-test.js && node tests/runtime-lifecycle-test.js && node tests/runtime-fetch-test.js && node tests/runtime-channel-test.js && node tests/runtime-boundary-test.js && node tests/runtime-record-test.js && node tests/runtime-recovery-test.js && node tests/runtime-diagnostic-record-test.js && node tests/runtime-metrics-test.js && node tests/runtime-run-context-test.js && node tests/runtime-execution-context-test.js && node tests/storage-gc-canvas-refs-test.js && node tests/storage-health-test.js && node tests/generation-state-test.js && node tests/canvas-store-test.js && node tests/storage-result-test.js && node tests/storage-local-test.js && node tests/storage-domain-test.js && node tests/storage-runtime-test.js && node tests/storage-indexeddb-test.js && node tests/generation-scheduler-test.js && node tests/gallery-query-test.js && node tests/gallery-hydration-test.js && node tests/gallery-sync-test.js && node tests/image-blob-store-test.js && node tests/image-format-test.js && node tests/clipboard-graph-test.js && node tests/clipboard-graph-fallback-test.js && node tests/image-admit-test.js && node tests/image-dedupe-test.js && node tests/clipboard-kind-test.js && node tests/clipboard-paste-test.js && node tests/clipboard-copy-test.js && node tests/paste-once-test.js && node tests/list-e2e-specs-test.js && node tests/desktop-csp-loopback-test.js && node tests/architecture-boundary-guard-test.js && node tests/plugin-host-test.js && node tests/plugin-data-test.js && node tests/plugin-loader-test.js && node tests/plugin-bundle-test.js && node tests/plugin-install-test.js && node tests/plugin-gallery-render-test.js && node tests/plugin-gallery-recovery-test.js && node tests/plugin-gallery-ux-test.js && node tests/plugin-grouplib-render-test.js && node tests/plugin-promptlib-render-test.js && node tests/image-compress-test.js && node tests/storage-fallback-indexeddb-test.js && node tests/canvas-normalize-test.js && node tests/canvas-geometry-test.js && node tests/canvas-history-test.js && node tests/canvas-ops-test.js && node tests/canvas-text-test.js && node tests/history-store-test.js && node tests/plugin-integrity-test.js && node tests/workspace-sessions-store-test.js && node tests/workspace-list-test.js && node tests/workspace-purge-test.js && node tests/provider-ping-test.js && node tests/runtime-diagnostics-hotpath-test.js && node tests/storage-log-failure-test.js && node tests/storage-convergence-test.js && node tests/swallow-wiring-test.js && node tests/workbench-logic-test.js && node tests/storage-autobackup-test.js && node tests/storage-outputs-mutate-test.js && node tests/sync-facts-guard-test.js && node tests/e2e-fixed-waits-ratchet-test.js && node tests/shell-render-behavior-test.js && node tests/canvas-meta-notice-behavior-test.js && node tests/source-text-ratchet-test.js && node tests/plugin-theme-contract-test.js && node tests/prompt-md-roundtrip-test.js && node tests/generation-results-store-test.js && node tests/out-groups-order-test.js && node tests/native-overlay-park-test.js && node tests/ui-dock-sanitize-test.js && node tests/ui-minimap-fit-test.js && node tests/ui-workbench-hooks-test.js && node tests/plugin-scale-contract-test.js && node tests/design-token-ratchet-test.js && node tests/theme-contrast-test.js", + "test:unit": "node tests/plugin-files-policy-test.js && node tests/theme-plugin-tokens-test.js && node tests/design-tokens-component-doc-test.js && node tests/theme-static-snapshot-test.js && node tests/overlay-layer-test.js && node tests/settings-scope-test.js && node tests/node-scope-test.js && node tests/appearance-v2-test.js && node tests/image-prompt-cover-test.js && node tests/unit-test.js && node tests/canvas-actions-test.js && node tests/canvas-performance-test.js && node tests/canvas-drag-performance-test.js && node tests/resize-observer-performance-test.js && node tests/node-drag-jank-test.js && node tests/edge-graph-performance-test.js && node tests/persistence-export-images-test.js && node tests/settings-hotkeys-size-presets-test.js && node tests/custom-size-validation-test.js && node tests/image-node-performance-test.js && node tests/drag-frame-performance-test.js && node tests/canvas-edge-memo-test.js && node tests/canvas-node-transform-test.js && node tests/canvas-dot-zoom-test.js && node tests/duplicate-ws-fresh-source-test.js && node tests/single-canvas-shell-test.js && node tests/navigation-layout-test.js && node tests/home-canvas-library-test.js && node tests/left-resource-layout-test.js && node tests/interface-hierarchy-test.js && node tests/three-page-layout-test.js && node tests/page-chrome-regression-test.js && node tests/task-cache-test.js && node tests/album-task-graph-test.js && node tests/generation-endpoint-test.js && node tests/storage-config-shape-test.js && node tests/storage-zip-test.js && node tests/canvas-node-factory-test.js && node tests/runtime-error-test.js && node tests/runtime-lifecycle-test.js && node tests/runtime-fetch-test.js && node tests/runtime-channel-test.js && node tests/runtime-boundary-test.js && node tests/runtime-record-test.js && node tests/runtime-recovery-test.js && node tests/runtime-diagnostic-record-test.js && node tests/runtime-metrics-test.js && node tests/runtime-run-context-test.js && node tests/runtime-execution-context-test.js && node tests/storage-gc-canvas-refs-test.js && node tests/storage-health-test.js && node tests/generation-state-test.js && node tests/canvas-store-test.js && node tests/storage-result-test.js && node tests/storage-local-test.js && node tests/storage-domain-test.js && node tests/storage-runtime-test.js && node tests/storage-indexeddb-test.js && node tests/generation-scheduler-test.js && node tests/gallery-query-test.js && node tests/gallery-hydration-test.js && node tests/gallery-sync-test.js && node tests/image-blob-store-test.js && node tests/image-format-test.js && node tests/clipboard-graph-test.js && node tests/clipboard-graph-fallback-test.js && node tests/image-admit-test.js && node tests/image-dedupe-test.js && node tests/clipboard-kind-test.js && node tests/clipboard-paste-test.js && node tests/clipboard-copy-test.js && node tests/paste-once-test.js && node tests/list-e2e-specs-test.js && node tests/desktop-csp-loopback-test.js && node tests/architecture-boundary-guard-test.js && node tests/plugin-host-test.js && node tests/plugin-data-test.js && node tests/plugin-loader-test.js && node tests/plugin-bundle-test.js && node tests/plugin-install-test.js && node tests/plugin-gallery-render-test.js && node tests/plugin-gallery-recovery-test.js && node tests/plugin-gallery-ux-test.js && node tests/plugin-grouplib-render-test.js && node tests/plugin-promptlib-render-test.js && node tests/image-compress-test.js && node tests/storage-fallback-indexeddb-test.js && node tests/canvas-normalize-test.js && node tests/canvas-geometry-test.js && node tests/canvas-history-test.js && node tests/canvas-ops-test.js && node tests/canvas-text-test.js && node tests/history-store-test.js && node tests/plugin-integrity-test.js && node tests/workspace-sessions-store-test.js && node tests/workspace-list-test.js && node tests/workspace-purge-test.js && node tests/provider-ping-test.js && node tests/runtime-diagnostics-hotpath-test.js && node tests/storage-log-failure-test.js && node tests/storage-convergence-test.js && node tests/swallow-wiring-test.js && node tests/workbench-logic-test.js && node tests/storage-autobackup-test.js && node tests/storage-outputs-mutate-test.js && node tests/sync-facts-guard-test.js && node tests/e2e-fixed-waits-ratchet-test.js && node tests/shell-render-behavior-test.js && node tests/canvas-meta-notice-behavior-test.js && node tests/source-text-ratchet-test.js && node tests/plugin-theme-contract-test.js && node tests/prompt-md-roundtrip-test.js && node tests/generation-results-store-test.js && node tests/out-groups-order-test.js && node tests/native-overlay-park-test.js && node tests/ui-dock-sanitize-test.js && node tests/ui-minimap-fit-test.js && node tests/ui-workbench-hooks-test.js && node tests/plugin-scale-contract-test.js && node tests/design-token-ratchet-test.js && node tests/theme-contrast-test.js", "test:diagnostics": "node tests/runtime-diagnostics-hotpath-test.js", "test:facts": "node tests/architecture-facts-guard-test.js && node tests/release-records-test.js", "plugins:gc": "node scripts/plugins-publish.mjs --gc", diff --git a/plugins/album/main.js b/plugins/album/main.js new file mode 100644 index 0000000..ee7d8bf --- /dev/null +++ b/plugins/album/main.js @@ -0,0 +1,552 @@ +// 相册节点(2026-11-26,iwb-plugin: album) +// +// 一件事:把「多个图片节点」收成一个节点——宫格装 N 张本地图,接提示词/组合做批量生图。 +// +// 三条关键设计(都对宿主有依赖,别在插件里重造): +// ① 只引用不复制:item.src = { __file: '/abs/a.png' };宿主生成时才读盘(ctx.images.reference / dataUrl) +// ② 任务展开由宿主任务图做:data.outKind='images' + data.items,宿主按 albumMode 展开成 N 个任务 +// (一图一任务)或分批(批量,每组 ≤12 张);本插件只负责「数据 + 界面」 +// ③ 分页容量随节点尺寸实时算:拖大 = 一页装更多(装得下就隐藏分页条),缩小 = 自动多页; +// 只有 data.onlyPage 打开时才把可见区间写进 data.pageRange 交给宿主过滤 +;(function (global) { + 'use strict' + if (!global.IWBPluginHost) return + + const DENSITY = { S: 64, M: 48, L: 100 } + const GAP = 5 + const PAD_X = 16 // 宫格左右 padding 合计(与 styles.css 对齐) + const PAD_Y = 8 // 上下 padding 合计 + const BAR_H = 26 // 状态栏 + const TOOLS_H = 27 // 工具条 + const PAGER_H = 26 // 分页条 / 一页提示条 + const HINT_H = 24 // 批量模式提示行 + const THUMB_EDGE = 256 + const THUMB_Q = 0.8 + const IMG_EXT = ['png', 'jpg', 'jpeg', 'webp', 'gif', 'avif', 'bmp', 'svg'] + + const STATE = new WeakMap() // host 元素 → 渲染状态(一个容器一个实例) + + // ── 小工具 ────────────────────────────────────────────── + function el (tag, attrs, kids) { + const node = document.createElement(tag) + if (attrs) for (const k in attrs) { + const v = attrs[k] + if (v === null || v === undefined || v === false) continue + if (k === 'className') node.className = v + else if (k === 'text') node.textContent = v + else if (k === 'style' && typeof v === 'object') Object.assign(node.style, v) + else if (k.slice(0, 2) === 'on' && typeof v === 'function') node.addEventListener(k.slice(2).toLowerCase(), v) + else node.setAttribute(k, v === true ? '' : String(v)) + } + for (const kid of (Array.isArray(kids) ? kids : (kids ? [kids] : []))) { + if (kid === null || kid === undefined || kid === false) continue + node.appendChild(typeof kid === 'string' ? document.createTextNode(kid) : kid) + } + return node + } + function hash32 (s) { + let h = 0x811c9dc5 + const str = String(s || '') + for (let i = 0; i < str.length; i++) { h ^= str.charCodeAt(i); h = (h + ((h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24))) >>> 0 } + return ('00000000' + h.toString(16)).slice(-8) + } + const extOf = (p) => { const m = /\.([a-z0-9]{1,5})$/i.exec(String(p || '')); return m ? m[1].toLowerCase() : '' } + const isImagePath = (p) => IMG_EXT.indexOf(extOf(p)) >= 0 + const fileRefOf = (src) => (src && typeof src === 'object' && typeof src.__file === 'string') ? src.__file : '' + const nameOf = (p) => String(p || '').replace(/^.*[\\/]/, '') + const str = (v) => (v == null ? '' : String(v)) + + // ── 缩略图(插件私有缓存,几十 KB/张,不碰画布存储)──────────── + const thumbNameOf = (key) => 't-' + hash32(key) + '.jpg' + + function makeThumb (dataUrl) { + return new Promise((resolve) => { + try { + const img = new Image() + img.onload = () => { + try { + const scale = Math.min(1, THUMB_EDGE / Math.max(img.naturalWidth || 1, img.naturalHeight || 1)) + const w = Math.max(1, Math.round((img.naturalWidth || 1) * scale)) + const h = Math.max(1, Math.round((img.naturalHeight || 1) * scale)) + const cv = document.createElement('canvas') + cv.width = w; cv.height = h + const c2 = cv.getContext('2d') + c2.drawImage(img, 0, 0, w, h) + resolve(cv.toDataURL('image/jpeg', THUMB_Q)) + } catch (e) { resolve('') } + } + img.onerror = () => resolve('') + img.src = dataUrl + } catch (e) { resolve('') } + }) + } + + // ── 容量:随节点宽高实时算(放大 = 一页装更多)──────────────── + function capacityOf (width, height, density, hasHint) { + const target = DENSITY[density] || DENSITY.S + const innerW = Math.max(0, width - 4 - PAD_X) + const innerH = Math.max(0, height - 4 - BAR_H - TOOLS_H - PAGER_H - (hasHint ? HINT_H : 0) - PAD_Y) + const cols = Math.max(1, Math.floor((innerW + GAP) / (target + GAP))) + const cell = Math.floor((innerW - (cols - 1) * GAP) / cols) || target + const rows = Math.max(1, Math.floor((innerH + GAP) / (cell + GAP))) + return { cols, rows, cell: Math.max(20, cell), capacity: Math.max(1, cols * rows) } + } + + function measure (host) { + const rect = host.getBoundingClientRect() + return { width: Math.round(rect.width || 0), height: Math.round(rect.height || 0) } + } + + // ── 数据读写 ──────────────────────────────────────────── + function itemsOf (node) { + const d = (node && node.data) || {} + return Array.isArray(d.items) ? d.items : [] + } + function update (props, node, patch, snapshot) { + try { if (snapshot && typeof props.onSnapshot === 'function') props.onSnapshot() } catch (e) { /* 撤销快照失败不影响写入 */ } + try { props.onUpdate(node.id, patch) } catch (e) { /* 宿主不可写时保持只读 */ } + } + + // ── 外壳 ──────────────────────────────────────────────── + function buildShell (ctx, node, props, host) { + const st = { + nodeId: node.id, + thumbs: new Map(), // key → dataURL(内存缓存) + missing: new Set(), // 失联文件的 key + busy: '', + checkedMissing: false, + sig: '', + } + const bar = el('div', { className: 'iwb-album-bar' }) + const track = el('span', { className: 'iwb-album-track' }, el('i', null)) + const modeLabel = el('label', { className: 'iwb-album-toggle' }, track, document.createTextNode('一图一任务')) + modeLabel.addEventListener('pointerdown', (e) => e.stopPropagation()) + modeLabel.addEventListener('click', (e) => { + e.stopPropagation() + const d = (node && node.data) || {} + const next = d.albumMode === 'batch' ? 'per-image' : 'batch' + update(props, node, { albumMode: next }) + }) + const count = el('span', { className: 'iwb-album-count' }) + bar.appendChild(modeLabel); bar.appendChild(count) + + const btnAdd = el('button', { className: 'iwb-album-btn', title: '选择本地图片(桌面端只引用,不复制字节)' }, '+ 添加图片') + const btnDir = el('button', { className: 'iwb-album-btn', title: '按文件夹批量添加' }, '文件夹') + const btnSettle = el('button', { className: 'iwb-album-btn', title: '把引用复制进画布存储(删源文件/分享画布前用)' }, '固化') + const seg = el('span', { className: 'iwb-album-seg' }) + const segs = {} + for (const key of ['S', 'M', 'L']) { + const s = el('span', { title: key === 'S' ? '小格(默认)' : (key === 'M' ? '中格' : '大格') }, key) + s.addEventListener('click', (e) => { e.stopPropagation(); update(props, node, { density: key }) }) + segs[key] = s; seg.appendChild(s) + } + const tools = el('div', { className: 'iwb-album-tools' }, [btnAdd, btnDir, btnSettle, seg]) + + const hint = el('div', { className: 'iwb-album-hint' }) + const grid = el('div', { className: 'iwb-album-grid' }) + const empty = el('div', { className: 'iwb-album-empty' }, [ + el('div', { className: 'box' }, '+'), + el('div', null, '把图片拖到这里,或点「添加图片」选本地文件'), + el('div', { style: { fontSize: '10px', opacity: '.85' } }, '支持 PNG / JPG / WebP / GIF / AVIF / SVG'), + ]) + const pager = el('div', { className: 'iwb-album-pager' }) + const onepage = el('div', { className: 'iwb-album-onepage' }, '全部图片一页展示') + + host.textContent = '' + const root = el('div', { className: 'iwb-album' }, [bar, tools, hint, grid, empty, pager, onepage]) + host.appendChild(root) + Object.assign(st, { root, bar, track, count, btnAdd, btnDir, btnSettle, segs, grid, empty, pager, onepage, hint }) + + // 按钮绑定(用闭包里的当前 node/props:每次 sync 会更新 st.node/st.props) + btnAdd.addEventListener('pointerdown', (e) => e.stopPropagation()) + btnAdd.addEventListener('click', (e) => { e.stopPropagation(); pickFiles(ctx, st, host, false) }) + btnDir.addEventListener('pointerdown', (e) => e.stopPropagation()) + btnDir.addEventListener('click', (e) => { e.stopPropagation(); pickFiles(ctx, st, host, true) }) + btnSettle.addEventListener('pointerdown', (e) => e.stopPropagation()) + btnSettle.addEventListener('click', (e) => { e.stopPropagation(); settleAll(ctx, st) }) + + // 拖拽入图:桌面端拿不到绝对路径 ⇒ 按「方案 1」复制进画布存储 + host.addEventListener('dragover', (e) => { e.preventDefault(); e.stopPropagation() }) + host.addEventListener('drop', (e) => { + e.preventDefault(); e.stopPropagation() + const files = Array.from((e.dataTransfer && e.dataTransfer.files) || []) + if (files.length) importDropped(ctx, st, files) + }) + return st + } + + // ── 同步(宿主每次重渲染都会调用;必须可增量)────────────────── + function sync (ctx, st, node, props) { + st.node = node; st.props = props + const d = (node && node.data) || {} + const items = itemsOf(node) + const density = DENSITY[d.density] ? d.density : 'S' + const mode = d.albumMode === 'batch' ? 'batch' : 'per-image' + // 尺寸来源:节点显式 w/h → 宿主实测高度 → 插件默认值。 + // ⚠ 不能用 host.getBoundingClientRect() 当高度:插件节点体是内容撑开的(auto), + // 量到的是「当前内容」而不是「卡片能有多高」⇒ 容量永远算成 1 行。 + const measured = measure(st.root) + const cardW = Number(node.w) || Number(d.width) || measured.width || 300 + const cardH = Number(node.h) || Number(props.measuredH) || 470 + st.root.style.height = Math.max(120, Math.round(cardH) - 4) + 'px' + const cap = capacityOf(cardW, cardH, density, mode === 'batch') + const pages = Math.max(1, Math.ceil(items.length / cap.capacity)) + const page = Math.max(0, Math.min(pages - 1, Number(d.page) || 0)) + const from = page * cap.capacity + const to = Math.min(items.length, from + cap.capacity) + const selected = items.filter((it) => it && it.on !== false).length + + // 一图一任务开关 / 计数 / 密度高亮 / 固化可用性 + st.track.className = 'iwb-album-track' + (mode === 'per-image' ? ' on' : '') + st.count.innerHTML = '' + st.count.appendChild(document.createTextNode('已选 ')) + st.count.appendChild(el('b', null, String(selected))) + st.count.appendChild(document.createTextNode('/' + items.length + ' · 每页 ' + cap.capacity)) + for (const k in st.segs) st.segs[k].className = (density === k ? 'on' : '') + const hasFileRef = items.some((it) => fileRefOf(it && it.src)) + st.btnSettle.style.display = hasFileRef ? '' : 'none' + st.btnDir.style.display = (ctx.images && ctx.images.canReference()) || true ? '' : 'none' + if (st.busy) { st.btnAdd.textContent = st.busy } else { st.btnAdd.textContent = '+ 添加图片' } + + // 批量模式提示:N 张 → M 个任务(每组 ≤ 12) + if (mode === 'batch' && items.length) { + st.hint.style.display = '' + st.hint.innerHTML = '' + st.hint.appendChild(document.createTextNode('整本一次请求:')) + st.hint.appendChild(el('b', null, items.length + ' 张 → ' + Math.ceil(items.length / 12) + ' 个任务')) + st.hint.appendChild(document.createTextNode('(每组 ≤ 12 张)')) + } else st.hint.style.display = 'none' + + // 分页条 / 一页展示 + const showPager = pages > 1 + st.pager.style.display = showPager ? '' : 'none' + st.onepage.style.display = showPager ? 'none' : '' + if (!showPager) st.onepage.textContent = '全部 ' + items.length + ' 张一页展示 · 无需翻页' + if (showPager) { + st.pager.innerHTML = '' + const pg = el('span', { className: 'iwb-album-pg' }) + const prev = el('span', { title: '上一页' }, '‹') + const next = el('span', { title: '下一页' }, '›') + prev.addEventListener('click', (e) => { e.stopPropagation(); if (page > 0) update(st.props, st.node, { page: page - 1 }) }) + next.addEventListener('click', (e) => { e.stopPropagation(); if (page < pages - 1) update(st.props, st.node, { page: page + 1 }) }) + pg.appendChild(prev); pg.appendChild(el('b', null, (page + 1) + '/' + pages)); pg.appendChild(next) + st.pager.appendChild(pg) + const only = el('label', { className: 'iwb-album-mini' }, [ + el('span', { className: 'iwb-album-track' + (d.onlyPage === true ? ' on' : '') }, el('i', null)), + document.createTextNode('仅本页参与'), + ]) + only.addEventListener('pointerdown', (e) => e.stopPropagation()) + only.addEventListener('click', (e) => { + e.stopPropagation() + update(st.props, st.node, { onlyPage: !(d.onlyPage === true) }) + }) + st.pager.appendChild(only) + } + + // 仅本页参与:把可见区间写回 data.pageRange(宿主任务图据此过滤;关闭时清掉) + const wantRange = (d.onlyPage === true) ? [from, to] : null + const curRange = Array.isArray(d.pageRange) ? d.pageRange : null + const rangeChanged = (!!wantRange !== !!curRange) || (wantRange && curRange && (wantRange[0] !== curRange[0] || wantRange[1] !== curRange[1])) + if (rangeChanged || (Number(d.page) || 0) !== page) { + update(st.props, st.node, { page: page, pageRange: wantRange }) + } + + // 宫格(签名不变就不重建:避免每帧重排导致闪烁/丢拖拽态) + const sig = [node.id, density, page, cap.capacity, mode, items.length, d.onlyPage === true ? 1 : 0, + items.map((it) => (it && (fileRefOf(it.src) || it.name)) || '').join(','), Array.from(st.missing).join(',')].join('|') + if (sig !== st.sig) { + st.sig = sig + st.grid.innerHTML = '' + st.grid.style.gridTemplateColumns = 'repeat(' + cap.cols + ', 1fr)' + if (!items.length) { + st.grid.style.display = 'none'; st.empty.style.display = '' + } else { + st.grid.style.display = ''; st.empty.style.display = 'none' + for (let i = from; i < to; i++) st.grid.appendChild(cellOf(ctx, st, items[i], i, mode)) + if (to - from < cap.capacity) { + const add = el('button', { className: 'iwb-album-cell iwb-album-add', title: '添加图片' }, [el('b', null, '+'), el('span', null, '添加')]) + add.addEventListener('click', (e) => { e.stopPropagation(); pickFiles(ctx, st, st.root, false) }) + st.grid.appendChild(add) + } + } + } else { + st.grid.style.gridTemplateColumns = 'repeat(' + cap.cols + ', 1fr)' + } + + // 失联检测(每个节点一次;文件被移动/删除时给出明确提示) + if (!st.checkedMissing && items.some((it) => fileRefOf(it && it.src))) { + st.checkedMissing = true + checkMissing(ctx, st, items).then((changed) => { if (changed) { st.sig = ''; try { sync(ctx, st, st.node, st.props) } catch (e) { /* ignore */ } } }) + } + } + + // ── 单元格 ────────────────────────────────────────────── + function cellOf (ctx, st, it, index, mode) { + const src = it && it.src + const path = fileRefOf(src) + const key = path || str(it && it.name) || String(index) + const on = !(it && it.on === false) + const missing = path && st.missing.has(path) + const btn = el('button', { + className: 'iwb-album-cell' + (on ? ' sel' : ' off') + (missing ? ' missing' : ''), + title: (it && it.name ? it.name : ('图 ' + (index + 1))) + (missing ? '(文件已不在原位置:点一下重新定位)' : ''), + }) + const img = el('img', { alt: '', draggable: 'false' }) + const cached = st.thumbs.get(key) + if (cached) img.src = cached + else { + img.src = '' + loadThumb(ctx, st, it, key).then((url) => { if (url) img.src = url }) + } + btn.appendChild(img) + btn.appendChild(el('span', { className: 'iwb-album-idx' }, String(index + 1))) + if (mode === 'batch' && on) btn.appendChild(el('span', { className: 'iwb-album-batch' }, String(Math.floor(index / 12) + 1))) + const del = el('span', { className: 'iwb-album-del', title: '移除' }, '×') + del.addEventListener('pointerdown', (e) => e.stopPropagation()) + del.addEventListener('click', (e) => { + e.stopPropagation() + const items = itemsOf(st.node).slice() + items.splice(index, 1) + update(st.props, st.node, { items, page: 0 }, true) + }) + btn.appendChild(del) + btn.addEventListener('pointerdown', (e) => e.stopPropagation()) + btn.addEventListener('click', (e) => { + e.stopPropagation() + if (missing) { relocate(ctx, st, index); return } + const items = itemsOf(st.node).slice() + if (!items[index]) return + items[index] = Object.assign({}, items[index], { on: !on }) + update(st.props, st.node, { items }) + }) + // 拖拽排序 + btn.addEventListener('pointerdown', (e) => { + if (e.button !== 0) return + const startX = e.clientX, startY = e.clientY + let moved = false + const target = { index: index } + const onMove = (ev) => { + const dx = ev.clientX - startX, dy = ev.clientY - startY + if (!moved && Math.abs(dx) + Math.abs(dy) < 5) return + moved = true + btn.classList.add('dragging') + const cells = Array.from(st.grid.querySelectorAll('.iwb-album-cell')) + let hit = cells.length - 1 + for (let i = 0; i < cells.length; i++) { + const r = cells[i].getBoundingClientRect() + if (ev.clientX < r.left + r.width / 2 + (r.width * 0.1) && ev.clientY < r.bottom && ev.clientX > r.left - r.width) { hit = i; break } + } + cells.forEach((c, i) => c.classList.toggle('dropbefore', i === hit)) + target.index = hit + } + const onUp = () => { + document.removeEventListener('pointermove', onMove) + document.removeEventListener('pointerup', onUp) + btn.classList.remove('dragging') + Array.from(st.grid.querySelectorAll('.dropbefore')).forEach((c) => c.classList.remove('dropbefore')) + if (!moved) return + const items = itemsOf(st.node).slice() + const cellCount = st.grid.querySelectorAll('.iwb-album-cell').length + const pageStart = (Number((st.node.data || {}).page) || 0) * cellCount + const from = pageStart + const srcIndex = index + let dest = from + target.index + if (dest === srcIndex || dest < 0) return + const [movedItem] = items.splice(srcIndex, 1) + if (dest > srcIndex) dest -= 1 + items.splice(Math.max(0, Math.min(items.length, dest)), 0, movedItem) + update(st.props, st.node, { items }, true) + } + document.addEventListener('pointermove', onMove) + document.addEventListener('pointerup', onUp) + }) + return btn + } + + // ── 缩略图取用:内存 → 插件文件 → 现做 ─────────────────── + async function loadThumb (ctx, st, it, key) { + if (st.thumbs.has(key)) return st.thumbs.get(key) + const name = thumbNameOf(key) + try { + if (ctx.files) { + const got = await ctx.files.get(name) + if (got && got.ok && got.url) { st.thumbs.set(key, got.url); return got.url } + } + } catch (e) { /* 没缓存就现做 */ } + let dataUrl = '' + const src = it && it.src + try { + if (fileRefOf(src)) dataUrl = await ctx.images.dataUrl(src) + else if (typeof src === 'string') dataUrl = src + else dataUrl = await ctx.images.dataUrl(src) + } catch (e) { dataUrl = '' } + if (!dataUrl) return '' + const thumb = await makeThumb(dataUrl) + if (!thumb) return '' + st.thumbs.set(key, thumb) + try { if (ctx.files) await ctx.files.put(name, thumb) } catch (e) { /* 配额满就只留内存 */ } + return thumb + } + + // ── 导入:选择器 / 文件夹 / 拖入 / 固化 / 重新定位 ────────── + async function pickFiles (ctx, st, host, directory) { + if (st.busy) return + const items = itemsOf(st.node).slice() + // 桌面端:系统选择器给绝对路径 ⇒ 只引用(不复制字节) + if (ctx.images && ctx.images.canReference()) { + st.busy = '选择中…'; st.sig = ''; sync(ctx, st, st.node, st.props) + try { + const paths = await ctx.images.pick({ multiple: true, directory: !!directory }) + st.busy = '' + if (paths.length) await addPaths(ctx, st, paths) + else { st.sig = ''; sync(ctx, st, st.node, st.props) } + } catch (e) { st.busy = ''; st.sig = ''; sync(ctx, st, st.node, st.props) } + return + } + // 网页版:没有路径 ⇒ 退回文件选择 + 复制进画布存储 + const input = document.createElement('input') + input.type = 'file'; input.accept = 'image/*'; input.multiple = true + input.style.display = 'none' + document.body.appendChild(input) + input.addEventListener('change', () => { + const files = Array.from(input.files || []) + document.body.removeChild(input) + if (files.length) importDropped(ctx, st, files) + }) + input.click() + } + + async function addPaths (ctx, st, paths) { + const list = paths.filter(isImagePath) + const items = itemsOf(st.node).slice() + const keep = (st.node.data && st.node.data.keepOriginal !== false) + for (let i = 0; i < list.length; i++) { + st.busy = '导入 ' + (i + 1) + '/' + list.length; st.sig = ''; sync(ctx, st, st.node, st.props) + const ref = await ctx.images.reference(list[i]) + if (!ref || !ref.ok) continue + items.push({ src: { __file: ref.item.path }, name: ref.item.name, size: ref.item.size, mtime: ref.item.mtime, on: true }) + } + st.busy = '' + update(st.props, st.node, { items }, true) + st.sig = '' + sync(ctx, st, st.node, st.props) + // 顺序生成缩略图(避免一次读几十张原图造成内存尖峰) + for (const it of items) { + const key = fileRefOf(it.src) || it.name + if (key) await loadThumb(ctx, st, it, key) + } + st.sig = '' + sync(ctx, st, st.node, st.props) + } + + async function importDropped (ctx, st, files) { + const items = itemsOf(st.node).slice() + for (let i = 0; i < files.length; i++) { + const f = files[i] + if (!f || !/^image\//i.test(f.type || '')) continue + st.busy = '复制 ' + (i + 1) + '/' + files.length; st.sig = ''; sync(ctx, st, st.node, st.props) + const dataUrl = await new Promise((resolve) => { + try { const r = new FileReader(); r.onload = () => resolve(String(r.result || '')); r.onerror = () => resolve(''); r.readAsDataURL(f) } catch (e) { resolve('') } + }) + if (!dataUrl) continue + let res = null + try { res = await ctx.images.importDataUrl(dataUrl, { keepOriginal: (st.node.data && st.node.data.keepOriginal !== false) }) } catch (e) { res = null } + if (!res || !res.ok) continue + const src = res.ref || res.data + if (!src) continue + const name = f.name || ('图 ' + (items.length + 1)) + items.push({ src, name, size: f.size || 0, on: true }) + const thumb = await makeThumb(dataUrl) + if (thumb) { st.thumbs.set(name, thumb); try { if (ctx.files) await ctx.files.put(thumbNameOf(name), thumb) } catch (e) { /* ignore */ } } + } + st.busy = '' + update(st.props, st.node, { items }, true) + st.sig = '' + sync(ctx, st, st.node, st.props) + } + + // 固化:把 __file 引用换成宿主存储引用(删源文件/分享画布前用) + async function settleAll (ctx, st) { + const items = itemsOf(st.node).slice() + let done = 0 + for (let i = 0; i < items.length; i++) { + const it = items[i] + const path = fileRefOf(it && it.src) + if (!path) continue + st.busy = '固化 ' + (++done) + '…'; st.sig = ''; sync(ctx, st, st.node, st.props) + try { + const res = await ctx.images.importPath(path, { keepOriginal: (st.node.data && st.node.data.keepOriginal !== false) }) + if (res && res.ok && (res.ref || res.data)) items[i] = Object.assign({}, it, { src: res.ref || res.data }) + } catch (e) { /* 单张失败不打断整批 */ } + } + st.busy = '' + update(st.props, st.node, { items }, true) + st.sig = '' + sync(ctx, st, st.node, st.props) + } + + async function checkMissing (ctx, st, items) { + let changed = false + for (const it of items) { + const path = fileRefOf(it && it.src) + if (!path) continue + try { + const r = await ctx.images.stat(path) + const missing = !(r && r.ok && r.exists) + if (missing && !st.missing.has(path)) { st.missing.add(path); changed = true } + if (!missing && st.missing.has(path)) { st.missing.delete(path); changed = true } + } catch (e) { /* 检测失败按存在处理 */ } + } + return changed + } + + // 失联重定位:点失联格 → 选一张同名/任意图片替换 + async function relocate (ctx, st, index) { + if (!ctx.images || !ctx.images.canReference()) return + const items = itemsOf(st.node).slice() + const cur = items[index] + if (!cur) return + const paths = await ctx.images.pick({ multiple: false }) + if (!paths || !paths.length) return + const ref = await ctx.images.reference(paths[0]) + if (!ref || !ref.ok) return + const oldPath = fileRefOf(cur.src) + st.missing.delete(oldPath) + items[index] = Object.assign({}, cur, { src: { __file: ref.item.path }, name: ref.item.name, size: ref.item.size, mtime: ref.item.mtime }) + update(st.props, st.node, { items }, true) + st.sig = '' + sync(ctx, st, st.node, st.props) + loadThumb(ctx, st, items[index], fileRefOf(items[index].src)).then(() => { st.sig = ''; try { sync(ctx, st, st.node, st.props) } catch (e) { /* ignore */ } }) + } + + // ── 注册 ──────────────────────────────────────────────── + global.IWBPluginHost.register({ + id: 'album', + name: '相册', + version: '1.0.0', + apiVersion: 1, + capabilities: ['nodeTypes', 'images', 'files'], + settings: { + keepOriginal: { type: 'boolean', label: '默认保留原图(不压缩)', desc: '开启后导入不进 1600 长边压缩,分辨率不损失(占用更高)。节点内可单独改。', default: true }, + }, + }, function (ctx) { + ctx.nodes.register({ + id: 'album', + title: '相册', + width: 300, + height: 470, + color: '#8a8a8a', + ports: { in: true, out: true }, + defaults: { outKind: 'images', items: [], albumMode: 'per-image', density: 'S', page: 0, onlyPage: false, keepOriginal: ctx.settings.get('keepOriginal') !== false }, + render: function (node, props, host) { + let st = STATE.get(host) + if (!st || st.nodeId !== node.id) { st = buildShell(ctx, node, props, host); STATE.set(host, st) } + try { sync(ctx, st, node, props) } catch (e) { + // 渲染失败降级成一行可读文本(绝不让整块画布白屏) + try { host.textContent = ''; const tip = document.createElement('div'); tip.className = 'iwb-hint'; tip.textContent = '相册渲染失败:' + String((e && e.message) || e); host.appendChild(tip) } catch (e2) { /* ignore */ } + } + }, + }) + return {} + }) +})(typeof window !== 'undefined' ? window : globalThis) diff --git a/plugins/album/manifest.json b/plugins/album/manifest.json new file mode 100644 index 0000000..0c8d325 --- /dev/null +++ b/plugins/album/manifest.json @@ -0,0 +1,16 @@ +{ + "id": "album", + "name": "album", + "version": "1.0.0", + "apiVersion": 1, + "main": "main.js", + "style": "styles.css", + "description": "", + "author": "official", + "icon": "", + "tags": [], + "files": { + "main.js": "27b89ab975b6a2958b8815d868fda294ff8d603ca07a27e028ed5b18aa4fd071", + "styles.css": "cfa64a6ceda0ff59b6a11f451b43a9ef70a2c7977d3dc58a2c38ae8f3fa570d4" + } +} diff --git a/plugins/album/styles.css b/plugins/album/styles.css new file mode 100644 index 0000000..105d2a5 --- /dev/null +++ b/plugins/album/styles.css @@ -0,0 +1,48 @@ +/* 相册节点体(2026-11-26) + * 宿主只给一块空容器(.iwb-plugin-node-body),所有排版由这里决定。 + * 尺寸全部用像素而不是 rem:节点宽度是可拖拽的(264~600),rem 会跟着宿主字号漂移。 + */ +.iwb-album { display: flex; flex-direction: column; height: 100%; overflow: hidden; font-size: 11px; color: var(--iwb-node-text); } +.iwb-album-bar, .iwb-album-tools, .iwb-album-pager, .iwb-album-onepage { + display: flex; align-items: center; gap: 6px; padding: 4px 8px; flex: 0 0 auto; +} +.iwb-album-bar { border-bottom: 1px solid var(--iwb-line-weak); height: 26px; } +.iwb-album-tools { padding-top: 3px; padding-bottom: 3px; } +.iwb-album-toggle { display: inline-flex; align-items: center; gap: 5px; font-size: 10px; color: var(--iwb-node-text2); white-space: nowrap; cursor: pointer; } +.iwb-album-track { width: 22px; height: 12px; border-radius: 999px; background: var(--iwb-line); position: relative; flex: 0 0 auto; transition: background .15s; } +.iwb-album-track i { position: absolute; top: 1.5px; left: 1.5px; width: 9px; height: 9px; border-radius: 50%; background: var(--iwb-panel); transition: left .15s; } +.iwb-album-track.on { background: var(--iwb-brand); } +.iwb-album-track.on i { left: 11.5px; } +.iwb-album-count { margin-left: auto; font-size: 10px; color: var(--iwb-node-text2); white-space: nowrap; } +.iwb-album-count b { color: var(--iwb-node-text); font-weight: 600; } +.iwb-album-btn { height: 21px; padding: 0 7px; border: 1px solid var(--iwb-line); border-radius: var(--iwb-radius-chip); background: var(--iwb-panel); color: var(--iwb-node-text2); font-size: 10px; display: inline-flex; align-items: center; gap: 3px; cursor: pointer; white-space: nowrap; } +.iwb-album-btn:hover { border-color: var(--iwb-brand); color: var(--iwb-node-text); } +.iwb-album-btn.on { border-color: var(--iwb-brand); color: var(--iwb-node-text); } +.iwb-album-seg { margin-left: auto; display: inline-flex; border: 1px solid var(--iwb-line); border-radius: var(--iwb-radius-chip); overflow: hidden; } +.iwb-album-seg span { width: 21px; height: 21px; display: inline-flex; align-items: center; justify-content: center; font-size: 10px; color: var(--iwb-node-text2); background: var(--iwb-panel); cursor: pointer; } +.iwb-album-seg span.on { background: var(--iwb-brand); color: var(--iwb-on-brand); } +.iwb-album-grid { display: grid; gap: 5px; padding: 2px 8px 6px; overflow: hidden; align-content: start; flex: 1 1 auto; min-height: 0; } +.iwb-album-cell { position: relative; border-radius: var(--iwb-radius-chip); overflow: hidden; background: var(--iwb-line-weak); border: 1px solid var(--iwb-line); cursor: grab; } +.iwb-album-cell img { width: 100%; height: 100%; object-fit: cover; display: block; -webkit-user-drag: none; } +.iwb-album-cell.off img { opacity: .38; } +.iwb-album-cell.sel { outline: 2px solid var(--iwb-brand); outline-offset: -2px; } +.iwb-album-cell.missing { outline: 2px dashed #c0392b; outline-offset: -2px; } +.iwb-album-cell.missing::after { content: '失联'; position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; font-size: 10px; color: #c0392b; background: rgba(255,255,255,.72); } +.iwb-album-cell.dragging { opacity: .45; } +.iwb-album-cell.dropbefore { box-shadow: -3px 0 0 0 var(--iwb-brand); } +.iwb-album-idx { position: absolute; left: 3px; top: 3px; min-width: 14px; height: 14px; padding: 0 3px; border-radius: 999px; background: rgba(0,0,0,.55); color: #fff; font-size: 9px; display: flex; align-items: center; justify-content: center; } +.iwb-album-batch { position: absolute; right: 3px; top: 3px; padding: 0 4px; height: 14px; border-radius: 999px; background: rgba(107,114,128,.92); color: #fff; font-size: 9px; display: flex; align-items: center; } +.iwb-album-del { position: absolute; right: 3px; bottom: 3px; width: 15px; height: 15px; border-radius: 50%; background: rgba(255,255,255,.92); color: #666; font-size: 11px; line-height: 1; display: flex; align-items: center; justify-content: center; opacity: 0; cursor: pointer; } +.iwb-album-cell:hover .iwb-album-del { opacity: 1; } +.iwb-album-add { border: 1px dashed var(--iwb-line); background: transparent; color: var(--iwb-node-text2); display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 2px; font-size: 10px; border-radius: var(--iwb-radius-chip); cursor: pointer; } +.iwb-album-add b { font-size: 15px; line-height: 1; font-weight: 600; } +.iwb-album-pager { border-top: 1px solid var(--iwb-line-weak); height: 26px; } +.iwb-album-onepage { border-top: 1px solid var(--iwb-line-weak); height: 26px; color: var(--iwb-node-text2); font-size: 10px; } +.iwb-album-pg { display: inline-flex; align-items: center; border: 1px solid var(--iwb-line); border-radius: var(--iwb-radius-chip); background: var(--iwb-panel); } +.iwb-album-pg span { width: 17px; height: 17px; display: flex; align-items: center; justify-content: center; font-size: 10px; cursor: pointer; color: var(--iwb-node-text2); } +.iwb-album-pg b { font-weight: 600; color: var(--iwb-node-text); padding: 0 2px; font-size: 10px; } +.iwb-album-mini { display: inline-flex; align-items: center; gap: 4px; margin-left: auto; font-size: 10px; color: var(--iwb-node-text2); white-space: nowrap; } +.iwb-album-hint { margin: 0 8px 4px; padding: 4px 6px; border-radius: var(--iwb-radius-chip); background: rgba(107,114,128,.10); border: 1px solid rgba(107,114,128,.22); color: var(--iwb-node-text2); font-size: 10px; line-height: 1.45; } +.iwb-album-hint b { color: var(--iwb-node-text); } +.iwb-album-empty { flex: 1 1 auto; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px; color: var(--iwb-node-text2); font-size: 11px; text-align: center; padding: 0 14px; } +.iwb-album-empty .box { width: 66px; height: 50px; border: 1.5px dashed var(--iwb-line); border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 18px; color: var(--iwb-node-text2); } diff --git a/plugins/index.json b/plugins/index.json index 5d5caaa..385e4a5 100644 --- a/plugins/index.json +++ b/plugins/index.json @@ -1,4 +1,15 @@ [ + { + "id": "album", + "dir": "album", + "main": "main.js", + "style": "styles.css", + "version": "1.0.0", + "files": { + "main.js": "27b89ab975b6a2958b8815d868fda294ff8d603ca07a27e028ed5b18aa4fd071", + "styles.css": "cfa64a6ceda0ff59b6a11f451b43a9ef70a2c7977d3dc58a2c38ae8f3fa570d4" + } + }, { "id": "batch-export", "file": "plugin-batch-export.44c13ac8e6d9.js", diff --git a/scripts/build.js b/scripts/build.js index 276a539..b830f49 100644 --- a/scripts/build.js +++ b/scripts/build.js @@ -59,6 +59,7 @@ const sourceModules = [ 'runtime-execution-context.js', 'runtime-diagnostic-record.js', 'runtime-metrics.js', + 'image-file-ref.js', 'image-blob-store.js', 'runtime-crash-log.js', 'storage-health.js', @@ -133,6 +134,7 @@ const sourceModules = [ 'ui-connect-menu.js', 'ui-gen-config-panel.js', 'canvas-webview.js', + 'plugin-api-images.js', 'plugin-files-policy.js', 'image-prompt-cover.js', ] diff --git a/scripts/sync-plugins-from-repo.js b/scripts/sync-plugins-from-repo.js index c71d761..dc59680 100644 --- a/scripts/sync-plugins-from-repo.js +++ b/scripts/sync-plugins-from-repo.js @@ -10,7 +10,7 @@ const crypto = require('crypto') const root = path.resolve(__dirname, '..') const srcRoot = process.argv[2] ? path.resolve(process.argv[2]) : path.resolve(root, '..', 'iwb-plugins-desktop') const outDir = path.join(root, 'plugins', 'runtime') -const IDS = ['batch-export', 'blank-canvas', 'browser', 'gallery', 'grouplib', 'promptlib', 'image-annotate', 'image-vectorize', 'sticky', 'style-source', 'white-bg-800', 'xianyi-cutout'] +const IDS = ['album', 'batch-export', 'blank-canvas', 'browser', 'gallery', 'grouplib', 'promptlib', 'image-annotate', 'image-vectorize', 'sticky', 'style-source', 'white-bg-800', 'xianyi-cutout'] // v3.25.41(M1):目录化插件试点 —— 这些 id 产出 /{manifest.json,main.js},其余仍是单文件(双轨兼容) // ⚠️ 2026-11-20 修正:桌面包不随包发插件(scripts/strip-plugins.js),插件只能从市场装, // 而市场目前只支持单文件 ⇒ 目录形态暂不用于生产插件,等 M3(zip 安装)落地再启用。 diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 25d599a..d59240f 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -187,6 +187,29 @@ fn app_memory_mb() -> u64 { } } +// 把用户**显式选择**的路径加进本次运行的 fs scope(2026-11-26,相册「只引用本地文件」用)。 +// 为什么单独一条命令:dialog 选中的外部图片不在「资料目录」里,fs 插件默认拒绝读写; +// 这里只授权调用方传进来的具体路径,不扩大 $HOME 之类的面。 +#[tauri::command] +fn grant_paths(app: AppHandle, paths: Vec) -> Result, String> { + let mut ok: Vec = Vec::new(); + for raw in paths { + let p = std::path::PathBuf::from(&raw); + if !p.is_absolute() { + continue; + } + let granted = if p.is_dir() { + app.fs_scope().allow_directory(&p, true).is_ok() + } else { + app.fs_scope().allow_file(&p).is_ok() + }; + if granted { + ok.push(p.to_string_lossy().to_string()); + } + } + Ok(ok) +} + #[tauri::command] fn grant_dir(app: AppHandle, dir: String, record: Option) -> Result { let p = std::path::PathBuf::from(&dir); @@ -918,7 +941,7 @@ pub fn run() { .plugin(tauri_plugin_fs::init()) .plugin(tauri_plugin_dialog::init()) .plugin(tauri_plugin_updater::Builder::new().build()) - .invoke_handler(tauri::generate_handler![open_app_data_dir, open_data_subpath, grant_dir, copy_tree, check_update, install_update, clipboard_read_image, clipboard_write_image, clipboard_write_text, clipboard_read_text, open_external_url, open_browser_window, browser_control, browser_state, canvas_webview_ensure, canvas_webview_bounds, canvas_webview_navigate, canvas_webview_action, canvas_webview_state, canvas_webview_close_all, canvas_webview_metrics, notify_desktop, + .invoke_handler(tauri::generate_handler![open_app_data_dir, open_data_subpath, grant_paths, grant_dir, copy_tree, check_update, install_update, clipboard_read_image, clipboard_write_image, clipboard_write_text, clipboard_read_text, open_external_url, open_browser_window, browser_control, browser_state, canvas_webview_ensure, canvas_webview_bounds, canvas_webview_navigate, canvas_webview_action, canvas_webview_state, canvas_webview_close_all, canvas_webview_metrics, notify_desktop, app_memory_mb]) .setup(|app| { if cfg!(debug_assertions) { diff --git a/src/canvas-geometry.js b/src/canvas-geometry.js index 40761d8..f27c883 100644 --- a/src/canvas-geometry.js +++ b/src/canvas-geometry.js @@ -27,7 +27,11 @@ // 所以这里做一次归一化:声明了就按 prompt 节点参与下面的规则判定。 // 内置节点没有 outKind 字段 ⇒ 所有规则逐字不变(零回归,现有画布连不上的仍然连不上)。 const srcIsPromptOut = !!(src && src.data && src.data.outKind === 'prompt') - const st = srcIsPromptOut ? 'prompt' : src.type + // 相册(2026-11-26):声明 outKind:'images' ⇒ 下游当作「图片来源」参与规则(能进生图/组合/中继)。 + const srcIsImagesOut = !!(src && src.data && src.data.outKind === 'images') + const st = srcIsPromptOut ? 'prompt' : (srcIsImagesOut ? 'ref' : src.type) + // 相册自己只接受文本类输入(提示词/文本/组合/批量/中继):它自带图片,不吃别人的图。 + if (dst && dst.data && dst.data.outKind === 'images' && st !== 'prompt' && st !== 'textout' && st !== 'combine' && st !== 'batch' && st !== 'relay' && !srcIsPromptOut) return '相册节点只接受提示词/文本类输入' // batch 多输出:不同来源端口可连到同一目标;普通节点同对仅一条边 if (src.type !== 'batch' && hasEdge) return '这两个节点已经连接' // 提示词节点原来只收参考图 / 中继(避免提示词串联);样式节点要能进来做二次编辑,单独放行 diff --git a/src/generation-task-graph.js b/src/generation-task-graph.js index a4ac56f..482b943 100644 --- a/src/generation-task-graph.js +++ b/src/generation-task-graph.js @@ -71,12 +71,36 @@ // ② 下游 orderedUniqueRefNodes 还要按 id 去重、按画布坐标排序(图片按 X 轴先、Y 轴后), // 伪节点必须带上宿主节点自己的 x/y,才能排进用户预期的次序。 // id 取 `节点id + ':ref'`:不与任何真图片节点撞名,同一节点在多条链路被重复收集时又能正常去重。 + // 相册(2026-11-26,outKind:'images'):一个节点声明多张图。 + // data.items = [{ name, src, on? }],src 是 dataURL/URL 字符串或引用对象({__file}/{__blob}/{__cache})。 + // 为什么伪装成多个「ref 节点」:下游 refArgsOf / orderedUniqueRefNodes / 去重排序全都只认 ref 节点形状, + // 合成节点带宿主节点的 x/y,才能排进用户预期的次序(与 refOn 那条同一套理由)。 + const ALBUM_BATCH_MAX = 12 // 批量模式下每个请求最多带几张(相册模式 B:超过自动分批) + const albumItemsOf = (n) => { + const d = (n && n.data) || {} + if (d.outKind !== 'images' || !Array.isArray(d.items)) return [] + const out = [] + // 仅本页参与:相册按当前尺寸算出的可见区间写在 data.pageRange = [start, end)(插件维护,宿主只读) + const from = (d.onlyPage === true && Array.isArray(d.pageRange)) ? Math.max(0, Number(d.pageRange[0]) || 0) : 0 + const to = (d.onlyPage === true && Array.isArray(d.pageRange)) ? Math.max(from, Number(d.pageRange[1]) || 0) : d.items.length + for (let i = from; i < Math.min(d.items.length, to); i++) { + const it = d.items[i] + if (!it || it.on === false) continue + const src = it.src != null ? it.src : (it.ref != null ? it.ref : it.data) + if (!src) continue + const name = String(it.name || ('图 ' + (i + 1))) + const data = (typeof src === 'string') ? { data: src, name: name } : { url: src, name: name } + out.push({ id: String(n.id) + ':ref:' + i, type: 'ref', x: n.x, y: n.y, w: n.w, h: n.h, data: data }) + } + return out + } const selfRefNodesOf = (n) => { const d = (n && n.data) || {} + if (d.outKind === 'images') return albumItemsOf(n) if (d.refOn !== true) return [] const url = String(d.refUrl || '').trim() if (!url) return [] - return [{ id: String(n.id) + ':ref', type: 'ref', x: n.x, y: n.y, w: n.w, h: n.h, data: { url: url, name: String(d.refName || 'style-ref.png') } }] + return [{ id: String(n.id) + ':ref', type: 'ref', x: n.x, y: n.y, w: n.w, h: n.h, data: { url: url, name: String(d.refName || 'style-ref') } }] } function createTaskGraphIndex(nodesArr, edgesArr) { @@ -104,7 +128,27 @@ // 否则「样式节点直连生图」与「样式节点 → 提示词 → 生图」会被认成同一个来源而合并成一个任务。 return base.map((t) => ({ ...t, sourceNodeId: own ? n.id : (t.sourceNodeId || n.id), ownerNodeId: n.id, title: ownTitle || t.title || '', text: own || t.text, refNodes: dedupeTaskRefs((t.refNodes || []).concat(refs)) })) } - if (n.type === 'combine') { const orderedC = children.slice().sort((a, b) => { const na = graph.byId.get(a.sourceNodeId), nb = graph.byId.get(b.sourceNodeId); return na && nb ? compareCanvasTextOrder(na, nb) : 0 }); return [{ sourceNodeId: n.id, ownerNodeId: n.id, title: String((n.data && n.data.title) || '').trim(), text: own || orderedC.map((t) => t.text).filter(Boolean).join(String((n.data && n.data.sep) || (global.IWBRuntimeConstants && global.IWBRuntimeConstants.combineSep) || ', ')), refNodes: dedupeTaskRefs(orderedC.flatMap((t) => t.refNodes)), diagnostics: { cycles: orderedC.flatMap((t) => (t.diagnostics && t.diagnostics.cycles) || []), disabledSources: [] } }] } + if (n.type === 'combine') { + const orderedC = children.slice().sort((a, b) => { const na = graph.byId.get(a.sourceNodeId), nb = graph.byId.get(b.sourceNodeId); return na && nb ? compareCanvasTextOrder(na, nb) : 0 }) + /* 多值子源展开(2026-11-26):相册(一图一任务)接在组合前面时,组合必须**扇出 N 个任务**, + * 否则会被下面那句「永远返回 1 个值」压成「1 个任务 + N 张图」——那正是批量模式的行为,一图一任务会失效。 + * 安全边界:只有**恰好一个**来源提供多值时才展开(内置节点永远只返回 1 个值 ⇒ 现有画布零变化); + * 多个多值来源(未定义语义)不猜,退回原来的「压成 1 个」。 + */ + const keyOf = (t) => String(t.ownerNodeId || t.sourceNodeId || '') + const bySource = new Map() + for (const t of orderedC) { const k = keyOf(t); if (!bySource.has(k)) bySource.set(k, []); bySource.get(k).push(t) } + const multi = Array.from(bySource.keys()).filter((k) => bySource.get(k).length > 1) + if (multi.length === 1) { + const mk = multi[0] + const sepOf = String((n.data && n.data.sep) || (global.IWBRuntimeConstants && global.IWBRuntimeConstants.combineSep) || ', ') + const picks = bySource.get(mk) + return picks.map((pick, i) => { + const merged = orderedC.map((t) => (keyOf(t) === mk ? pick : t)) + return { sourceNodeId: n.id + '#' + i, ownerNodeId: n.id, title: String((n.data && n.data.title) || '').trim(), text: own || merged.map((t) => t.text).filter(Boolean).join(sepOf), refNodes: dedupeTaskRefs(merged.flatMap((t) => t.refNodes)), diagnostics: { cycles: merged.flatMap((t) => (t.diagnostics && t.diagnostics.cycles) || []), disabledSources: [] } } + }) + } + return [{ sourceNodeId: n.id, ownerNodeId: n.id, title: String((n.data && n.data.title) || '').trim(), text: own || orderedC.map((t) => t.text).filter(Boolean).join(String((n.data && n.data.sep) || (global.IWBRuntimeConstants && global.IWBRuntimeConstants.combineSep) || ', ')), refNodes: dedupeTaskRefs(orderedC.flatMap((t) => t.refNodes)), diagnostics: { cycles: orderedC.flatMap((t) => (t.diagnostics && t.diagnostics.cycles) || []), disabledSources: [] } }] } if (n.type === 'batch') { const candidates = incoming.map((e) => graph.byId.get(e.from)).filter((x) => x && isBatchSrc(x, graph.edges, graph.nodes) && !(x.data && x.data.enabled === false)); const selected = ctx.selectedBatchSourceId && candidates.find((x) => x.id === ctx.selectedBatchSourceId); const sources = selected ? [selected] : candidates; return sources.flatMap((src) => resolveNodeTaskValues(src.id, graph, { ...ctx, selectedBatchSourceId: null, stack: next }).map((t) => ({ ...t, text: batchJoinedText(n.data || {}, t.text) }))) } if (n.type === 'relay') { const sharedRefs = dedupeTaskRefs(children.filter((t) => !t.text).flatMap((t) => t.refNodes || [])) @@ -124,6 +168,21 @@ // 有上游时也要并(不再直接 return children):端口已关,但旧存档里可能有残留入边, // 那种情况下「用户勾的示例图」不该因为一条历史连线就消失。 const selfRefs = selfRefNodesOf(n) + // 相册(2026-11-26):多图源 = 多任务。 + // · 一图一任务(默认):每张图一个任务值,文本取自身或上游第一段(相机后面的组合/生图照旧) + // · 批量:按 ALBUM_BATCH_MAX 分批,每批一个任务值(一批内多张参考图) + // 只在 outKind:'images' 时生效 ⇒ 其它插件节点 / 内置类型行为逐字不变。 + if (n.data && n.data.outKind === 'images' && selfRefs.length) { + const albumText = own || (children.map((t) => t.text).filter(Boolean)[0] || '') + const diag = { cycles: children.flatMap((t) => (t.diagnostics && t.diagnostics.cycles) || []), disabledSources: [] } + const batch = n.data.albumMode === 'batch' + if (!batch) { + return selfRefs.map((r, i) => ({ sourceNodeId: n.id + '#' + i, ownerNodeId: n.id, title: String((n.data && n.data.title) || '').trim(), text: albumText, refNodes: [r], diagnostics: diag })) + } + const groups = [] + for (let i = 0; i < selfRefs.length; i += ALBUM_BATCH_MAX) groups.push(selfRefs.slice(i, i + ALBUM_BATCH_MAX)) + return groups.map((g, gi) => ({ sourceNodeId: n.id + '#b' + gi, ownerNodeId: n.id, title: String((n.data && n.data.title) || '').trim(), text: albumText, refNodes: g, diagnostics: diag })) + } if (children.length) { return selfRefs.length ? children.map((t) => ({ ...t, ownerNodeId: n.id, refNodes: dedupeTaskRefs((t.refNodes || []).concat(selfRefs)) })) diff --git a/src/image-file-ref.js b/src/image-file-ref.js new file mode 100644 index 0000000..ca06db2 --- /dev/null +++ b/src/image-file-ref.js @@ -0,0 +1,103 @@ +/* 本地文件图片引用(2026-11-26) + * + * 为什么单独成模块:相册要「只做引用、不复制字节」——节点里只存原文件绝对路径 + * ({__file: '/abs/a.png'}),生成/预览时才按需读盘。这样 22 张 4K 图 = 画布 JSON 2.6KB, + * 而不是往 images/canvas/ 复制 176MB。 + * + * 边界: + * · 只做「路径 ↔ 字节」这一层,不碰画布/存储/CSS;宿主 app.js 通过 wImgRefDataUrl 等入口调用 + * · 非桌面端(网页版)没有 __TAURI__ ⇒ available() false,调用方必须自己降级为复制 + * · fs 权限是运行时的:pick() 选完会把路径加进 fs scope(Rust grant_paths),重启后失效需重新选择 + */ +;(function (global) { + 'use strict' + const g = global || {} + const MIME = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', webp: 'image/webp', gif: 'image/gif', avif: 'image/avif', bmp: 'image/bmp', svg: 'image/svg+xml' } + const extOf = (p) => { const m = /\.([a-z0-9]{1,5})$/i.exec(String(p || '')); return m ? m[1].toLowerCase() : '' } + const mimeOf = (p) => MIME[extOf(p)] || 'application/octet-stream' + const nameOf = (p) => String(p || '').replace(/^.*[\\/]/, '') + const is = (v) => !!(v && typeof v === 'object' && !Array.isArray(v) && typeof v.__file === 'string' && v.__file) + const T = () => (typeof window !== 'undefined' ? window.__TAURI__ : null) + const fsApi = () => { const t = T(); return t && t.fs ? t.fs : null } + const available = () => { const f = fsApi(); return !!(f && typeof f.readFile === 'function') } + + async function readBytes (path) { + const f = fsApi() + if (!f || !path) return null + try { const u8 = await f.readFile(String(path)); return u8 || null } catch (e) { return null } + } + + // 手工 base64(不依赖 FileReader/btoa 的边界行为;Uint8Array → 分块拼,避免超长 apply 爆栈) + function toBase64 (u8) { + const bytes = (u8 && u8.length !== undefined) ? u8 : new Uint8Array(0) + const CHUNK = 0x8000 + let bin = '' + for (let i = 0; i < bytes.length; i += CHUNK) bin += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK)) + try { return btoa(bin) } catch (e) { return '' } + } + + async function readDataUrl (path) { + const u8 = await readBytes(path) + if (!u8 || !u8.length) return '' + const b64 = toBase64(u8) + return b64 ? ('data:' + mimeOf(path) + ';base64,' + b64) : '' + } + + async function readBlob (path) { + const u8 = await readBytes(path) + if (!u8 || !u8.length) return null + try { return new Blob([u8], { type: mimeOf(path) }) } catch (e) { return null } + } + + // 失联检测:相册打开画布时用它给「图片已不在原位置」的格子打标 + async function stat (path) { + const f = fsApi() + if (!f || !path) return { ok: false, exists: false, reason: 'no-fs' } + try { + const exists = (typeof f.exists === 'function') ? await f.exists(String(path)) : true + if (!exists) return { ok: true, exists: false } + const st = (typeof f.stat === 'function') ? await f.stat(String(path)) : null + return { ok: true, exists: true, size: st && Number(st.size) || 0, mtime: st && Number(st.mtime) || 0, name: nameOf(path) } + } catch (e) { return { ok: false, exists: false, reason: 'stat-failed' } } + } + + // 把用户选中的路径加进运行时 fs scope(Rust 侧 grant_paths) + async function grant (paths) { + const t = T(); const list = (Array.isArray(paths) ? paths : [paths]).filter((p) => typeof p === 'string' && p) + if (!t || !t.core || typeof t.core.invoke !== 'function' || !list.length) return [] + try { return await t.core.invoke('grant_paths', { paths: list }) || [] } catch (e) { return [] } + } + + // 系统选择器:返回绝对路径数组(桌面端才有路径;网页版返回空 ⇒ 调用方降级复制) + async function pick (opts) { + const t = T(); const dlg = t && t.dialog + if (!dlg || typeof dlg.open !== 'function') return [] + const o = opts || {} + let picked = null + try { + picked = await dlg.open({ + multiple: o.multiple !== false, + directory: o.directory === true, + title: String(o.title || (o.directory ? '选择图片文件夹' : '选择图片')), + filters: o.filters || [{ name: '图片', extensions: ['png', 'jpg', 'jpeg', 'webp', 'gif', 'avif', 'bmp', 'svg'] }], + }) + } catch (e) { return [] } + if (!picked) return [] + const list = Array.isArray(picked) ? picked : [picked] + await grant(list) + return list.filter((p) => typeof p === 'string' && p) + } + + // 单张引用:读 stat 拿元信息(不读字节)——相册导入时用 + async function reference (path) { + const p = String(path || '') + if (!p) return { ok: false, reason: 'empty-path' } + const st = await stat(p) + if (!st.ok) return { ok: false, reason: st.reason || 'stat-failed', path: p } + if (!st.exists) return { ok: false, reason: 'not-found', path: p } + return { ok: true, path: p, name: nameOf(p), size: st.size, mtime: st.mtime } + } + + const API = Object.freeze({ is, available, mimeOf, nameOf, readBytes, readDataUrl, readBlob, stat, grant, pick, reference }) + global.IWBImageFileRef = API +})(typeof window !== 'undefined' ? window : globalThis) diff --git a/src/plugin-api-images.js b/src/plugin-api-images.js new file mode 100644 index 0000000..37924ef --- /dev/null +++ b/src/plugin-api-images.js @@ -0,0 +1,68 @@ +/* 插件图片能力:ctx.images(2026-11-26,首个使用方 = 相册节点) + * + * 为什么需要:相册要「只引用本地文件、不复制字节」,同时也要能把拖入/固化时的字节写进宿主存储。 + * 插件自己做不到这两件事: + * · 引用:需要 fs scope 授权 + 绝对路径(只有宿主能调 grant_paths / dialog) + * · 落地:需要宿主的唯一收口 wImgRefWrite({__blob} 主通道 + 缩略图预生成) + * + * 本模块只做「参数校验 + 分派」,宿主能力全部经 create(deps) 注入: + * fileRef —— IWBImageFileRef(路径 ↔ 字节,含 pick/grant/stat) + * importDataUrl —— (dataUrl, opts) => Promise<{ok, ref|null, data|null, error?}>(走 wImportImage 唯一收口) + * readDataUrl —— (ref|path) => Promise(http/data/引用对象 → 真实字节) + * thumbUrlOf —— (ref|src) => string(768 显示缩略图,同步) + */ +;(function (global) { + 'use strict' + const g = global || {} + + const create = (deps) => { + const D = deps || {} + const need = (name) => { + const fn = D[name] + if (typeof fn !== 'function') throw new Error('IWBPluginApiImages 缺少注入依赖: ' + name) + return fn + } + const fileRef = need('fileRef') + const importDataUrl = need('importDataUrl') + const readDataUrl = need('readDataUrl') + const thumbUrlOf = need('thumbUrlOf') + + const str = (v) => (v == null ? '' : String(v)) + const IMAGE_EXT = ['png', 'jpg', 'jpeg', 'webp', 'gif', 'avif', 'bmp', 'svg'] + const extOf = (p) => { const m = /\.([a-z0-9]{1,5})$/i.exec(str(p)); return m ? m[1].toLowerCase() : '' } + const isImagePath = (p) => IMAGE_EXT.indexOf(extOf(p)) >= 0 + + return (ctx) => ({ + // 是否支持「本地文件引用」(网页版 false ⇒ 插件应退回 importPath/importDataUrl) + canReference: () => fileRef.available(), + // 系统选择器:返回绝对路径数组(桌面端);网页端返回 [] + pick: (opts) => fileRef.pick(opts), + // 单张引用:只读元信息,不复制字节 + reference: async (path) => { + if (!isImagePath(path)) return { ok: false, reason: 'not-image' } + const r = await fileRef.reference(path) + return r && r.ok ? { ok: true, item: { path: r.path, name: r.name, size: r.size, mtime: r.mtime } } : { ok: false, reason: (r && r.reason) || 'stat-failed' } + }, + // 失联检测(相册打开画布时批量调用) + stat: (path) => fileRef.stat(path), + // 读字节(base64 dataURL):只给「需要预览/上传」的显式场景 + dataUrl: (v) => readDataUrl(v), + // 缩略图地址(同步;宿主内部 768 缓存,不解析原图字节) + thumb: (v) => thumbUrlOf(v), + // 把本地文件字节写进宿主存储(拖拽=复制、以及「固化」按钮) + importPath: async (path, opts) => { + if (!isImagePath(path)) return { ok: false, error: 'not-image' } + const url = await fileRef.readDataUrl(path) + if (!url) return { ok: false, error: 'read-failed' } + return importDataUrl(url, opts) + }, + // 把任意 dataURL 写进宿主存储 + importDataUrl: (dataUrl, opts) => { + if (!/^data:image\//i.test(str(dataUrl))) return Promise.resolve({ ok: false, error: 'not-data-url' }) + return importDataUrl(str(dataUrl), opts) + }, + }) + } + + global.IWBPluginApiImages = Object.freeze({ create }) +})(typeof window !== 'undefined' ? window : globalThis) diff --git a/src/plugin-host.js b/src/plugin-host.js index 3d7d19e..90c93c7 100644 --- a/src/plugin-host.js +++ b/src/plugin-host.js @@ -4,7 +4,7 @@ const API_VERSION = 1 const ID_PATTERN = /^[a-z][a-z0-9-]{2,31}$/ const REQUIRED_FIELDS = ['id', 'name', 'version', 'apiVersion', 'capabilities'] - const CAPABILITIES = ['panels', 'commands', 'nodeTypes', 'generationHooks', 'providers', 'canvas', 'canvasWrite', 'nodeActions', 'gallery', 'grouplib', 'promptlib', 'files'] + const CAPABILITIES = ['panels', 'commands', 'nodeTypes', 'generationHooks', 'providers', 'canvas', 'canvasWrite', 'nodeActions', 'gallery', 'grouplib', 'promptlib', 'files', 'images'] const CAPABILITY_API_KEYS = { panels: 'ui', commands: 'commands', nodeTypes: 'nodes', generationHooks: 'generation', providers: 'providers', canvas: 'canvas', canvasWrite: 'canvas', nodeActions: 'nodeActions', gallery: 'gallery', grouplib: 'grouplib', promptlib: 'promptlib' , files: 'files'} function createPluginHost(options) { diff --git a/tests/album-task-graph-test.js b/tests/album-task-graph-test.js new file mode 100644 index 0000000..c631db5 --- /dev/null +++ b/tests/album-task-graph-test.js @@ -0,0 +1,113 @@ +'use strict' +/* 相册(outKind:'images')任务图行为(2026-11-26) + * + * 守的是什么: + * · 一图一任务:相册 N 张 → N 个任务,每个只带自己那张图 + * · 批量模式:按 ALBUM_BATCH_MAX(12) 分批 → ⌈N/12⌉ 个任务,每批多张参考图 + * · 组合扇出:相册接在组合前面时必须变成 N 个任务(否则会被压成 1 个任务 + N 张图) + * · 零回归:没有相册时,ref/组合/中继的任务数逐字不变 + * + * 用真实模块 + 最小注入实现(不切片 app.js):依赖全是纯函数,本文件里各写一份等价实现。 + */ +const assert = require('assert') +const fs = require('fs') +const path = require('path') +const vm = require('vm') + +const src = fs.readFileSync(path.join(__dirname, '..', 'src', 'generation-task-graph.js'), 'utf8') +const box = { console } +vm.runInNewContext(src, box) +const TG = box.IWBWTaskGraph +assert.ok(TG && typeof TG.create === 'function', '模块应导出 IWBWTaskGraph.create') + +// ── 最小注入依赖(语义与 app.js 一致,但实现从简)── +const byPos = (a, b) => (Number(a.x) - Number(b.x)) || (Number(a.y) - Number(b.y)) || String(a.id).localeCompare(String(b.id)) +const dedupeTaskRefs = (list) => { const seen = new Set(), out = []; for (const r of (list || [])) { if (!r || seen.has(r.id)) continue; seen.add(r.id); out.push(r) } return out } +const refArgsOf = (rn) => { const d = (rn && rn.data) || {}; if (d.localName) return [{ type: 'local', name: d.localName }]; if (d.data) return [{ type: 'data', value: d.data, name: d.name || 'ref.png' }]; if (typeof d.url === 'string') return d.url.trim() ? [{ type: 'url', value: d.url.trim() }] : []; if (d.url) return [{ type: 'data', value: d.url, name: d.name || 'ref.png' }]; return [] } +const isBatchSrc = (n) => !!n && (n.type === 'prompt' || n.type === 'textout' || n.type === 'combine' || n.type === 'batch' || (n.data && n.data.outKind === 'prompt')) +const batchJoinedText = (data, base) => String((data && data.combined) || base || '') +const batchSrcText = (n) => String((n && n.data && (n.data.combined || n.data.text)) || '') +const wDedupeTaskIds = (list) => { const seen = new Set(), out = []; for (const t of (list || [])) { if (!t || seen.has(t.id)) continue; seen.add(t.id); out.push(t) } return out } + +const tg = TG.create({ + sortByPosition: (arr) => arr.slice().sort(byPos), + compareCanvasImageOrder: byPos, + compareCanvasTextOrder: byPos, + dedupeTaskRefs, + isBatchSrc, + batchJoinedText, + wDedupeTaskIds, + refArgsOf, + batchSrcText, + standardSizeOf: () => '1024x1024', +}) + +const n = (id, type, data, extra) => Object.assign({ id, type, x: Number(id.replace(/\D/g, '')) || 0, y: 0, data: data || {} }, extra || {}) +const e = (from, to) => ({ id: from + '>' + to, from, to }) +const img = (i) => ({ name: 'img' + i + '.png', src: 'data:image/png;base64,AAA' + i }) +const album = (id, count, extra) => n(id, 'plugin:album:album', Object.assign({ outKind: 'images', items: Array.from({ length: count }, (_, i) => img(i + 1)) }, extra || {})) +const gen = n('g9', 'gen', {}) +const tasks = (nodes, edges) => tg.buildGenerationTasksV2(gen, nodes.concat([gen]), edges) + +let pass = 0, fail = 0 +const ok = (name, cond, extra) => { if (cond) { pass++; console.log(' PASS ' + name) } else { fail++; console.log(' FAIL ' + name + (extra ? ' → ' + extra : '')) } } + +// ① 一图一任务:相册(3) → 组合 ← 提示词 → 生图 = 3 个任务,各 1 张图 + 同一段文本 +{ + const nodes = [album('a1', 3), n('p2', 'prompt', { text: '一段提示词' }), n('c3', 'combine', {}), gen] + const out = tasks(nodes, [e('a1', 'c3'), e('p2', 'c3'), e('c3', 'g9')]) + ok('一图一任务 = 3 个任务', out.length === 3, '实际 ' + out.length) + ok('每个任务只带 1 张图', out.every((t) => t.refs.length === 1), JSON.stringify(out.map((t) => t.refs.length))) + ok('每个任务都带同一段提示词', out.every((t) => t.text === '一段提示词'), JSON.stringify(out.map((t) => t.text))) + ok('任务 id 互不相同', new Set(out.map((t) => t.id)).size === 3, JSON.stringify(out.map((t) => t.id))) +} + +// ② 批量模式:22 张 → 2 个任务(12 + 10) +{ + const nodes = [album('a1', 22, { albumMode: 'batch' }), n('c3', 'combine', {}), gen] + const out = tasks(nodes, [e('a1', 'c3'), e('c3', 'g9')]) + ok('批量 = 2 个任务', out.length === 2, '实际 ' + out.length) + ok('按 12 张分批:12 + 10', JSON.stringify(out.map((t) => t.refs.length)) === '[12,10]', JSON.stringify(out.map((t) => t.refs.length))) +} + +// ③ 组合前面再拼「其他参考图」:每个任务 = 该相册图 + 额外参考图 +{ + const nodes = [album('a1', 3), n('r4', 'ref', { url: 'https://example.test/extra.png' }), n('c3', 'combine', {}), gen] + const out = tasks(nodes, [e('a1', 'c3'), e('r4', 'c3'), e('c3', 'g9')]) + ok('组合扇出后仍是 3 个任务', out.length === 3, '实际 ' + out.length) + ok('每个任务 = 相册图 + 额外参考图(2 张)', out.every((t) => t.refs.length === 2), JSON.stringify(out.map((t) => t.refs.length))) +} + +// ④ 相册直连生图(不接组合):一图一任务 +{ + const nodes = [album('a1', 4), gen] + const out = tasks(nodes, [e('a1', 'g9')]) + ok('直连仍是 4 个任务', out.length === 4, '实际 ' + out.length) +} + +// ⑤ 零回归:普通 ref + 提示词 → 生图(1 个任务、1 张图) +{ + const nodes = [n('p2', 'prompt', { text: 'hello' }), n('r4', 'ref', { url: 'https://example.test/x.png' }), gen] + const out = tasks(nodes, [e('p2', 'g9'), e('r4', 'g9')]) + ok('普通画布仍是 1 个任务', out.length === 1, '实际 ' + out.length) + ok('普通画布 refs = 1', out[0].refs.length === 1, JSON.stringify(out[0].refs.length)) +} + +// ⑥ 零回归:组合(无多值来源)仍是 1 个任务、合并文本与图 +{ + const nodes = [n('p2', 'prompt', { text: 'a' }), n('t5', 'textout', { text: 'b' }), n('r4', 'ref', { url: 'https://example.test/x.png' }), n('c3', 'combine', {}), gen] + const out = tasks(nodes, [e('p2', 'c3'), e('t5', 'c3'), e('r4', 'c3'), e('c3', 'g9')]) + ok('普通组合仍是 1 个任务', out.length === 1, '实际 ' + out.length) + ok('普通组合文本已合并', /a/.test(out[0].text) && /b/.test(out[0].text), out[0].text) +} + +// ⑦ 停用(on:false)的相册项不参与 +{ + const items = [img(1), Object.assign(img(2), { on: false }), img(3)] + const nodes = [n('a1', 'plugin:album:album', { outKind: 'images', items }), gen] + const out = tasks(nodes, [e('a1', 'g9')]) + ok('停用的相册项被跳过', out.length === 2, '实际 ' + out.length) +} + +console.log('\n===== album 任务图:' + pass + ' 通过 / ' + fail + ' 失败 =====') +process.exit(fail ? 1 : 0) diff --git a/tests/fixtures/iwb-app-global-reads.json b/tests/fixtures/iwb-app-global-reads.json index 9570a6a..fc081b0 100644 --- a/tests/fixtures/iwb-app-global-reads.json +++ b/tests/fixtures/iwb-app-global-reads.json @@ -23,12 +23,14 @@ "IWBImageBlobStore", "IWBImageCompress", "IWBImageDisplayThumb", + "IWBImageFileRef", "IWBImageRemoteCache", "IWBImageThumbPick", "IWBMetricsSwallow", "IWBMiniMapFit", "IWBNativeClipboard", "IWBNodeBodies", + "IWBPluginApiImages", "IWBPluginData", "IWBPluginGallery", "IWBPluginGroupLib", diff --git a/tests/fixtures/iwb-source-modules-order.json b/tests/fixtures/iwb-source-modules-order.json index 9291c43..4399fa9 100644 --- a/tests/fixtures/iwb-source-modules-order.json +++ b/tests/fixtures/iwb-source-modules-order.json @@ -31,6 +31,7 @@ "runtime-execution-context.js", "runtime-diagnostic-record.js", "runtime-metrics.js", + "image-file-ref.js", "image-blob-store.js", "runtime-crash-log.js", "storage-health.js", @@ -105,6 +106,7 @@ "ui-connect-menu.js", "ui-gen-config-panel.js", "canvas-webview.js", + "plugin-api-images.js", "plugin-files-policy.js", "image-prompt-cover.js" ] diff --git a/tests/plugin-host-test.js b/tests/plugin-host-test.js index 6de3e4d..56b6c6f 100644 --- a/tests/plugin-host-test.js +++ b/tests/plugin-host-test.js @@ -13,7 +13,7 @@ vm.runInNewContext(source, sandbox) const host0 = sandbox.IWBPluginHost assert.ok(Number.isInteger(host0.apiVersion) && host0.apiVersion >= 1, 'apiVersion 必须是正整数') assert.ok(Array.isArray(host0.capabilities) && host0.capabilities.length >= 7, '能力清单应非空') -assert.strictEqual(host0.capabilities.slice().sort().join(','), 'canvas,canvasWrite,commands,files,gallery,generationHooks,grouplib,nodeActions,nodeTypes,panels,promptlib,providers') +assert.strictEqual(host0.capabilities.slice().sort().join(','), 'canvas,canvasWrite,commands,files,gallery,generationHooks,grouplib,images,nodeActions,nodeTypes,panels,promptlib,providers') const manifest = (over) => Object.assign({ id: 'demo-plugin', name: 'Demo', version: '1.0.0', apiVersion: 1, capabilities: [] }, over) const stateOf = (ids) => { diff --git a/tests/source-text-ratchet-test.js b/tests/source-text-ratchet-test.js index 508106d..a75e20b 100644 --- a/tests/source-text-ratchet-test.js +++ b/tests/source-text-ratchet-test.js @@ -157,13 +157,14 @@ const MAX_SRC_COMPONENT_LINES = 531 // ② 纠正过时的存储口径注释(用户要求:旧的不准确描述要改掉):图库/缩略图/原图档在桌面端是 // images/thumbs、images/gallery 文件,不是 IndexedDB;「1K 插入档降的是长边像素不是体积」。 // 共 6 行注释,属于事实纠错而非功能代码。 -// 2026-11-24 v3.26.65:9105 → **9133**(+28,生图 API 三处硬伤修复,逐条记账): -// · wResolveKey 返回多地址候选 addrs(含 fallbacks 去重) +6 -// · 生图/分层改用 wEndpointTools(genPath 生效 + auth 四态) +12(两处各约 6) -// · 地址回退调用(循环本体已下沉 src/generation-endpoint.js) +3 -// · 兼容兜底与注释 +7 -// 通用件(joinEndpoint / buildAuthHeaders / applyAuthQuery / runWithAddresses)全部在 src/,app.js 只做装配。 -const MAX_APP_JS_LINES = 9134 +// 2026-11-26 v3.26.66:9134 → **9159**(+25,相册节点宿主侧接线,逐条记账): +// · {__file} 本地文件引用四处分派(识别/key/字节解析/显示 URL) +4 +// · 导出时 items[].src 内联(跨设备可带走) +8 +// · ctx.images 能力装配(deps 注入 wImportImage/wImgRefDataUrl/thumb)+13 +// · 导入保留原图(keepOriginal 分支,2 行) +2 +// 通用件(pick/grant/stat/readDataUrl/readBlob/参数校验)全部在 src/image-file-ref.js +// 与 src/plugin-api-images.js,app.js 只做装配。 +const MAX_APP_JS_LINES = 9161 const MAX_APP_JS_SHARE = 0.40 // ── 历史记账(供回溯,逐条保留)────────────────────────────────────────────── diff --git a/types/iwb-globals.d.ts b/types/iwb-globals.d.ts index b7080eb..566a14c 100644 --- a/types/iwb-globals.d.ts +++ b/types/iwb-globals.d.ts @@ -34,6 +34,8 @@ interface Window { IWBRuntimePluginLoader?: any IWBRuntimePluginMarket?: any IWBRuntimePluginBackup?: any + IWBImageFileRef?: any + IWBPluginApiImages?: any IWBPluginData?: any IWBPluginRuntime?: any IWBDesktop?: any