feat(plugin): 节点组库插件化(grouplib capability + 删宿主侧栏),同步 grouplib 1.0.0

This commit is contained in:
qiqi committed 2026-11-20 13:12:14 +08:00
1 parent 23f82dc728
commit d8153f24d2
18 files changed
+646 -464

No files matched your search

+31 -10
View File
@@ -5466,10 +5466,6 @@ const tbCenterSeed = (type, refs) => {
const CanvasTopBar = (props) => window.IWBUICanvasTopBar(Object.assign({ I }, props))
const ProductNav = (props) => window.IWBUIProductNav(Object.assign({ I }, props))
// ---------- 节点组面板(v3:独立面板;收藏的组拖入画布实例化 / 重命名 / 删除) ----------
// 组件已收编到 src/ui-groups-sidebar.js(P2-9 组件抽取);宿主注入 I / api
const GroupsSidebar = (props) => window.IWBUIGroupsSidebar(Object.assign({ I, api }, props))
// 依赖注入点:放在 Workbench 之前 —— 此处 ICONS / computeEdgePath / downloadUrl / IDB 等全部已定义。
_mod.inject({
ICONS, IDB, computeEdgePath, copyImageToClipboard, downloadUrl,
@@ -7376,6 +7372,8 @@ const tbCenterSeed = (type, refs) => {
// drag & drop import(逻辑已外移到 src/runtime-workbench-logic.js.startCanvasDrop,2026-11-06)
useEffect(() => IWWorkbenchLogic.startCanvasDrop({ canvasEl, refs, uiZoom, importCanvasFile, instantiateGroup, wResolveOutputSrc, wImgRefWrite, wImportImage, uid, pushHistory, commitCanvas, setSel, setNotice, outputs }), [])
// 节点组数据变化(收藏/删除/其它标签页同步)→ 通知 grouplib 插件重拉,避免插件显示旧列表
useEffect(() => { if (window.IWBPluginGroupLib) window.IWBPluginGroupLib.emit('host') }, [savedGroups, nodeGroupGroups])
// v2 §7:LLM 润色(自动写回下游文案输出节点;脏链在生图/全部运行时自动先润色)
@@ -8010,11 +8008,6 @@ const tbCenterSeed = (type, refs) => {
setViewport((v) => ({ ...v, x: vw / 2 - wx * v.scale, y: vh / 2 - wy * v.scale }))
}, [canvasSize])
// ---- 左右停靠面板(v3.25.35)----
const dockGroupsEl = el(GroupsSidebar, { embedded: true, savedGroups, nodeGroupGroups,
onSavedGroupsChange: (list, onErr) => { setSavedGroups(list); api('groups', { groups: list, groupGroups: nodeGroupGroups }).then((r) => { if (r && r.ok === false && onErr) onErr() }).catch(() => { if (onErr) onErr() }) },
onNodeGroupGroupsChange: setNodeGroupGroups,
onFlash: (t, ty) => { setNotice({ type: ty === 'err' ? 'err' : 'ok', text: t }); showToast(t, ty) },
onRefresh: loadSavedGroups, onClose: () => {} })
const dockPromptsEl = el(LibSidebar, { embedded: true, prompts, groups: promptGroups,
canvasPrompts: nodes.filter((n) => n.type === 'prompt').map((n) => ({ id: n.id, text: n.data.text || '' })),
onPromptsChange: (list) => setPrompts(list), onGroupsChange: setPromptGroups,
@@ -8041,8 +8034,35 @@ const tbCenterSeed = (type, refs) => {
insert: async (names, o) => ({ ok: true, inserted: await insertOutputsToCanvas((outputs || []).filter((f) => names.indexOf(f.name) >= 0), (o && o.insertK) || '1k') }),
remove: async (names) => { const n = await deleteOutputs(names); return { ok: n > 0, removed: n } },
})
// 节点组库插件(grouplib):数据仍由宿主持有,插件只拿读写/实例化能力
if (window.IWBPluginGroupLib) {
window.IWBPluginGroupLib.setImpl({
list: () => ({ groups: refs.savedGroups || [], groupGroups: refs.nodeGroupGroups || [] }),
save: (payload) => {
const groups = (payload && Array.isArray(payload.groups)) ? payload.groups : []
const groupGroups = (payload && Array.isArray(payload.groupGroups)) ? payload.groupGroups : []
setSavedGroups(groups)
setNodeGroupGroups(groupGroups)
return Promise.resolve(wSaveGroups(groups, groupGroups)).then((r) => { window.IWBPluginGroupLib.emit('save'); return r || { ok: true } })
},
remove: (id) => {
const groups = (refs.savedGroups || []).filter((g) => g.id !== id)
setSavedGroups(groups)
return Promise.resolve(wSaveGroups(groups, refs.nodeGroupGroups || [])).then((r) => { window.IWBPluginGroupLib.emit('remove'); return r || { ok: true } })
},
instantiate: (id) => {
const snap = (refs.savedGroups || []).find((g) => g.id === id)
if (!snap) return { ok: false, error: '节点组不存在' }
const vw = canvasSize.w || 800, vh = canvasSize.h || 600
const wx = ((vw / 2) - viewport.x) / (viewport.scale || 1)
const wy = ((vh / 2) - viewport.y) / (viewport.scale || 1)
return Promise.resolve(instantiateGroup(snap, wx, wy)).then(() => ({ ok: true }))
},
notify: (text, type) => { setNotice({ type: type === 'err' ? 'err' : 'ok', text: String(text || '') }); showToast(String(text || ''), type) },
})
}
const dockPanels = {
groups: { title: '节点组', icon: 'group', node: dockGroupsEl },
groups: { title: '节点组', icon: 'group', pluginId: 'grouplib', hint: '节点组插件未安装 · 设置 → 插件 → 市场安装' },
browser: { title: '浏览器', icon: 'globe', pluginId: 'browser' },
styles: { title: '风格库', icon: 'palette', pluginId: 'style-source' },
prompts: { title: '提示词库', icon: 'book', node: dockPromptsEl },
@@ -8696,6 +8716,7 @@ items.push(el('button', { key: 'bgc', className: 'iwb-ctx-item', onClick: (e) =>
log: () => { try { wLog.apply(null, arguments) } catch (e) { /* ignore */ } },
capabilities: {
gallery: () => ((typeof window !== 'undefined' && window.IWBPluginGallery) ? window.IWBPluginGallery.api() : {}),
grouplib: () => ((typeof window !== 'undefined' && window.IWBPluginGroupLib) ? window.IWBPluginGroupLib.api() : {}),
commands: (ctx) => {
const owned = []
return {
+2 -2
View File
@@ -30,8 +30,8 @@
| 项 | 现值 | 依据 |
|---|---|---|
| 单测基线 | **658 通过 / 0 新增失败 / 2 已知环境差异**(2026-11-12 v3.24.76 实测;660 −2 = 94-5~7 三条钉点换成一条消费方契约) | (A) `npm test` 实测(`tests/iwb-v32-web-test.js`) |
| e2e | spec 文件 **59** 个(**55** 个进门禁 + 4 个 dev 探针 `_perf-baseline` / `_plugin-host-probe` / `_probe-drag` / `_probe-tab-switch`) | (A) `tests/` 计数 + `scripts/list-e2e-specs.js` |
| e2e 用例数 | **200 条**(2026-11-16 实测:55 个进门禁 spec 内 `test()` 总数;v3.25.15 删除网页版部署面后为 **53** 个进门禁 —— `iwb-csp-gate` / `iwb-functions-headers` 随 `_headers`、`functions/` 一起移除)(历史:115 → v3.24.18 **143** → v3.24.19 **147** → v3.24.21 **151** → F2 改名 1 条 **152** → 抓手工具 2 条 **154** → v3.24.44 输出顺序 2 条 **166** → v3.24.47 同步去重 `iwb-sync-dedupe` 1 条 **167** → v3.24.67 **179** → v3.24.68 **183** → v3.24.69 **184** → v3.24.70 **186** → v3.24.74 **187**(新增「拖入 PDF 给提示 + MIME 空 PNG 仍能导入」)→ v3.24.75 **188**(新增「同一张图连粘两次只建一个节点」)→ v3.24.76 **191**(新增 `iwb-tabs-release` 3 条:回首页不降级 / 关标签先保存再关 / 彻底删除连带关标签)→ v3.24.77 **194**(新增 `iwb-lod` 3 条:fit 大画布必须全 LOD / 放大后必须恢复 / 常规画布不 LOD)→ v3.24.78 **196**(`iwb-lod` 3 → 5 条:新增「lite 档必须画出代表图/首行文字」与「缩到 15% 以下才退成 plain」)→ v3.24.82 **197**(新增 `iwb-inherit-text` 1 条:提示词/文本节点显示上游继承文本、改字接管、恢复跟随)→ v3.24.83 **198**(新增 `iwb-plugin-node-coldstart` 1 条:插件脚本晚到 1.2s,存档里的插件节点必须自动切回插件节点体,且类型不被降级成 `plugin`)→ v3.24.79 **196 不变**(测速修复的守门落在 jsdom 单测 `provider-ping-test.js`,e2e 无新增)→ v3.24.85 **200**(新增 `iwb-multi-tab` 2 条:A 页 flush 落盘后 B 页必须靠 rev 轮询看到改动;B 页持锁期间 A 页图库归档必须挂起);早期 99 → 115 的逐版链条见 `docs/history/coverage-baseline-2026-10-27.md`) | (A) `tests/*.spec.js` 计数 + `scripts/list-e2e-specs.js` |
| e2e | spec 文件 **58** 个(**52** 个进门禁 + 4 个 dev 探针 `_perf-baseline` / `_plugin-host-probe` / `_probe-drag` / `_probe-tab-switch`) | (A) `tests/` 计数 + `scripts/list-e2e-specs.js` |
| e2e 用例数 | **200 条**(2026-11-16 实测:55 个进门禁 spec 内 `test()` 总数;v3.25.15 删除网页版部署面后为 **53** 个进门禁;v3.25.56 节点组库改插件 `grouplib`(宿主侧栏组件删除)后为 **52** 个进门禁 —— `iwb-csp-gate` / `iwb-functions-headers` 随 `_headers`、`functions/` 一起移除)(历史:115 → v3.24.18 **143** → v3.24.19 **147** → v3.24.21 **151** → F2 改名 1 条 **152** → 抓手工具 2 条 **154** → v3.24.44 输出顺序 2 条 **166** → v3.24.47 同步去重 `iwb-sync-dedupe` 1 条 **167** → v3.24.67 **179** → v3.24.68 **183** → v3.24.69 **184** → v3.24.70 **186** → v3.24.74 **187**(新增「拖入 PDF 给提示 + MIME 空 PNG 仍能导入」)→ v3.24.75 **188**(新增「同一张图连粘两次只建一个节点」)→ v3.24.76 **191**(新增 `iwb-tabs-release` 3 条:回首页不降级 / 关标签先保存再关 / 彻底删除连带关标签)→ v3.24.77 **194**(新增 `iwb-lod` 3 条:fit 大画布必须全 LOD / 放大后必须恢复 / 常规画布不 LOD)→ v3.24.78 **196**(`iwb-lod` 3 → 5 条:新增「lite 档必须画出代表图/首行文字」与「缩到 15% 以下才退成 plain」)→ v3.24.82 **197**(新增 `iwb-inherit-text` 1 条:提示词/文本节点显示上游继承文本、改字接管、恢复跟随)→ v3.24.83 **198**(新增 `iwb-plugin-node-coldstart` 1 条:插件脚本晚到 1.2s,存档里的插件节点必须自动切回插件节点体,且类型不被降级成 `plugin`)→ v3.24.79 **196 不变**(测速修复的守门落在 jsdom 单测 `provider-ping-test.js`,e2e 无新增)→ v3.24.85 **200**(新增 `iwb-multi-tab` 2 条:A 页 flush 落盘后 B 页必须靠 rev 轮询看到改动;B 页持锁期间 A 页图库归档必须挂起);早期 99 → 115 的逐版链条见 `docs/history/coverage-baseline-2026-10-27.md`) | (A) `tests/*.spec.js` 计数 + `scripts/list-e2e-specs.js` |
| CI | `.github/workflows/verify.yml`:**push(main) + PR(→main) + 手动** 触发,两个 job(`gate` = `verify:ci`;`e2e` = `test:e2e`),只验证不部署 | (A) |
| 部署 | `npm run deploy` = `verify` + `wrangler pages deploy dist --branch main`;**内含全量 verify,不得绕过** | (A) `package.json:16` |
| 部署环境 | 本机 wrangler 为 OAuth 登录 → **不能设 `CI=true`**(用 `unset CI` + `WRANGLER_SEND_METRICS=false`) | (A) 本轮发布实测 |
+1 -1
View File
@@ -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/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/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/image-blob-store-test.js && node tests/image-preview-derive-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/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/ui-groups-sidebar-test.js && node tests/ui-lib-sidebar-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/prompt-md-roundtrip-test.js && node tests/generation-results-store-test.js && node tests/out-groups-order-test.js && node tests/ui-workbench-hooks-test.js",
"test:unit": "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/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/image-blob-store-test.js && node tests/image-preview-derive-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-grouplib-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/ui-lib-sidebar-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/prompt-md-roundtrip-test.js && node tests/generation-results-store-test.js && node tests/out-groups-order-test.js && node tests/ui-workbench-hooks-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",
+6
View File
@@ -28,6 +28,12 @@
"styles.css": "94c57b2d18deef3f672242efe1812ba1dc88dad90f03648d68feaa64bc70f572"
}
},
{
"id": "grouplib",
"file": "plugin-grouplib.d14dbb4b85bd.js",
"version": "1.0.0",
"integrity": "sha256-0U27S4W9dGN4lhsKIIpPfWOy1OMLL4V3UVWoZq9FizQ="
},
{
"id": "image-annotate",
"file": "plugin-image-annotate.7a865c7c353c.js",
+10
View File
@@ -97,5 +97,15 @@
"资源",
"图库"
]
},
"grouplib": {
"name": "节点组",
"desc": "左栏收藏的节点组:分组/改名/删除,拖到画布实例化(数据由客户端提供)",
"author": "official",
"icon": "📦",
"tags": [
"资源",
"节点组"
]
}
}
@@ -0,0 +1,427 @@
// iwb-plugin: 节点组库 —— 左侧「节点组」面板(宿主只提供 ctx.grouplib 数据能力,界面全部在插件里)
//
// 依赖客户端能力:grouplib(list/save/remove/instantiate/notify/onChanged)+ panels。
// 数据仍在宿主持有(收藏的节点组快照 + 分组),插件不存副本,避免两份真相。
// 视觉:复用宿主 .iwb-lib-* / .iwb-pcard / .iwb-chip / .iwb-gmgr-* 类名(style.css 已有)。
;(function (global) {
'use strict'
if (!global.IWBPluginHost) return
var PANEL_ID = 'grouplib-panel'
function el (tag, attrs) {
var node = document.createElement(tag)
if (attrs) {
for (var k in attrs) {
if (!Object.prototype.hasOwnProperty.call(attrs, k)) continue
var v = attrs[k]
if (v === null || v === undefined) continue
if (k === 'class') node.className = v
else if (k === 'text') node.textContent = v
else if (k === 'style') node.setAttribute('style', v)
else node.setAttribute(k, v)
}
}
for (var i = 2; i < arguments.length; i++) append(node, arguments[i])
return node
}
function append (node, v) {
if (v === null || v === undefined || v === false) return
if (Array.isArray(v)) { for (var i = 0; i < v.length; i++) append(node, v[i]); return }
node.appendChild(typeof v === 'string' ? document.createTextNode(v) : v)
}
function clear (node) { while (node.firstChild) node.removeChild(node.firstChild) }
function ask (text, opts) {
var C = global.IWBUIConfirm
if (C && typeof C.askOrNative === 'function') return C.askOrNative(text, opts)
return Promise.resolve(global.confirm(String(text)))
}
function mount (host, ctx) {
clear(host)
host.classList.add('iwb-plugin-node-body')
host.style.minHeight = '0'
var list = [] // [{id, name, group, ...snapshot}]
var ggroups = [] // [{id, name}]
var filter = 'all'
var manage = false
var picked = {} // id -> 1(管理模式多选)
var editing = '' // 正在改名的 id
var newOpen = false
var managerOpen = false
var api = ctx.grouplib || {}
function notify (text, type) { try { api.notify && api.notify(text, type || 'ok') } catch (e) { /* ignore */ } }
function groupsOf () {
if (ggroups && ggroups.length) return ggroups
var seen = []
for (var i = 0; i < list.length; i++) {
var g = String((list[i] && list[i].group) || '').trim()
if (g && !seen.some(function (x) { return x.name === g })) seen.push({ id: g, name: g })
}
return seen
}
function save (next, nextGroups) {
var groups = next || list
var gs = nextGroups || groupsOf()
list = groups
ggroups = gs
render()
return Promise.resolve(api.save({ groups: groups, groupGroups: gs })).then(function (r) {
if (r && r.ok === false) { notify(r.error || '节点组保存失败,请重试', 'err'); return r }
return r || { ok: true }
}).catch(function () { notify('节点组保存失败,请重试', 'err') })
}
var body = el('div', { class: 'iwb-lib-body' })
var fixed = el('div', { class: 'iwb-lib-fixed' })
var scrollBox = el('div', { class: 'iwb-lib-scroll' })
var wrap = el('div', { class: 'iwb-groups-embedded' }, body)
body.appendChild(fixed)
body.appendChild(scrollBox)
host.appendChild(wrap)
function load () {
return Promise.resolve(api.list()).then(function (r) {
list = (r && r.groups) || []
ggroups = (r && r.groupGroups) || []
render()
}).catch(function () {
list = []
ggroups = []
render()
})
}
function countOf (name) {
if (name === 'all') return list.length
if (name === '__none__') return list.filter(function (g) { return !String((g && g.group) || '').trim() }).length
return list.filter(function (g) { return (g && g.group) === name }).length
}
function visible () {
if (filter === '__none__') return list.filter(function (g) { return !String((g && g.group) || '').trim() })
if (filter !== 'all') return list.filter(function (g) { return (g && g.group) === filter })
return list.slice()
}
function assignGroup (ids, group) {
return save(list.map(function (x) { return ids.indexOf(x.id) >= 0 ? Object.assign({}, x, { group: group || '' }) : x }))
.then(function () { notify('已移动到' + (group || '未分组')) })
}
function openMenu (e, g) {
e.preventDefault(); e.stopPropagation()
closeMenu()
var menu = el('div', { class: 'iwb-ctxmenu iwb-lib-group-menu', style: 'left:' + e.clientX + 'px;top:' + e.clientY + 'px' })
menu.appendChild(el('div', { class: 'iwb-ctx-title', text: '移动到分组' }))
var mk = function (label, value) {
var b = el('button', { class: 'iwb-ctx-item', text: label })
b.addEventListener('click', function () { closeMenu(); assignGroup([g.id], value) })
menu.appendChild(b)
}
mk('未分组', '')
groupsOf().forEach(function (gr) { mk(gr.name, gr.name) })
document.body.appendChild(menu)
menu._iwbOwner = wrap
setTimeout(function () { document.addEventListener('pointerdown', onDocDown, true) }, 0)
}
var openMenuEl = null
function closeMenu () {
if (openMenuEl && openMenuEl.parentNode) openMenuEl.parentNode.removeChild(openMenuEl)
openMenuEl = null
document.removeEventListener('pointerdown', onDocDown, true)
var old = document.querySelector('.iwb-lib-group-menu')
if (old && old.parentNode) old.parentNode.removeChild(old)
}
function onDocDown (e) {
var m = document.querySelector('.iwb-lib-group-menu')
if (m && m.contains(e.target)) return
closeMenu()
}
// ---- 分组管理弹窗 ----
var modalHost = null
function openManager () {
closeManager()
managerOpen = true
var mask = el('div', { class: 'iwb-modal-mask' })
var modal = el('div', { class: 'iwb-modal iwb-modal-sm' })
var head = el('div', { class: 'iwb-modal-head' })
var title = el('span', { class: 'iwb-toolbar-title' })
var closeBtn = el('button', { class: 'iwb-btn iwb-btn-sm', title: '关闭', text: '✕' })
closeBtn.addEventListener('click', closeManager)
head.appendChild(title); head.appendChild(closeBtn)
var bodyEl = el('div', { class: 'iwb-modal-body' })
modal.appendChild(head); modal.appendChild(bodyEl)
mask.appendChild(modal)
mask.addEventListener('wheel', function (e) { e.stopPropagation() })
mask.addEventListener('pointerdown', function (e) { if (e.target === mask) closeManager() })
document.body.appendChild(mask)
modalHost = mask
renderManager(title, bodyEl)
}
function closeManager () {
managerOpen = false
if (modalHost && modalHost.parentNode) modalHost.parentNode.removeChild(modalHost)
modalHost = null
render()
}
function renderManager (title, bodyEl) {
var gs = groupsOf()
title.textContent = '管理节点组分组(' + gs.length + ')'
clear(bodyEl)
if (!gs.length) bodyEl.appendChild(el('div', { class: 'iwb-hint', text: '暂无分组。可在下方新建。' }))
gs.forEach(function (g, i) {
var row = el('div', { class: 'iwb-gmgr-row' })
var nameEl = el('span', { class: 'iwb-gmgr-name', text: g.name })
row.appendChild(nameEl)
row.appendChild(el('span', { class: 'iwb-gmgr-count', text: countOf(g.name) + ' 组' }))
var rn = el('button', { class: 'iwb-btn iwb-btn-sm', title: '重命名', text: '重命名' })
rn.addEventListener('click', function () {
var input = el('input', { class: 'iwb-input iwb-grow', value: g.name })
row.replaceChild(input, nameEl)
input.focus(); input.select()
var commit = function () {
var n = String(input.value || '').trim()
if (!n || n === g.name) { renderManager(title, bodyEl); return }
if (groupsOf().some(function (x) { return x.name === n })) { renderManager(title, bodyEl); return }
var ng = groupsOf().map(function (x) { return x.name === g.name ? { id: n, name: n } : x })
var nl = list.map(function (x) { return x.group === g.name ? Object.assign({}, x, { group: n }) : x })
if (filter === g.name) filter = n
save(nl, ng).then(function () { if (managerOpen) openManager() })
}
input.addEventListener('keydown', function (e) {
if (e.key === 'Enter') { e.preventDefault(); commit() }
if (e.key === 'Escape') renderManager(title, bodyEl)
})
input.addEventListener('blur', commit)
})
row.appendChild(rn)
var up = el('button', { class: 'iwb-btn iwb-btn-sm', title: '上移', text: '↑' })
up.disabled = i === 0
up.addEventListener('click', function () { swap(i, -1) })
row.appendChild(up)
var down = el('button', { class: 'iwb-btn iwb-btn-sm', title: '下移', text: '↓' })
down.disabled = i === gs.length - 1
down.addEventListener('click', function () { swap(i, 1) })
row.appendChild(down)
var del = el('button', { class: 'iwb-btn iwb-btn-sm iwb-btn-danger', title: '删除分组(组内节点组移至未分组)', text: '删除' })
del.addEventListener('click', function () {
ask('删除节点组分组「' + g.name + '」?组内节点组将移至「未分组」(不删除节点组)。', { title: '删除分组', okText: '删除' }).then(function (ok) {
if (!ok) return
var ng = groupsOf().filter(function (x) { return x.name !== g.name })
var nl = list.map(function (x) { return x.group === g.name ? Object.assign({}, x, { group: '' }) : x })
if (filter === g.name) filter = 'all'
save(nl, ng).then(function () { if (managerOpen) openManager() })
})
})
row.appendChild(del)
bodyEl.appendChild(row)
})
var addRow = el('div', { class: 'iwb-row' })
var input = el('input', { class: 'iwb-input iwb-grow', placeholder: '新分组名称' })
var addBtn = el('button', { class: 'iwb-btn', text: '+ 添加' })
var doAdd = function () {
var n = String(input.value || '').trim()
if (!n) return
if (groupsOf().some(function (x) { return x.name === n })) { input.value = ''; return }
input.value = ''
save(list, groupsOf().concat([{ id: n, name: n }])).then(function () { if (managerOpen) openManager() })
}
input.addEventListener('keydown', function (e) { if (e.key === 'Enter') doAdd() })
addBtn.addEventListener('click', doAdd)
addRow.appendChild(input); addRow.appendChild(addBtn)
bodyEl.appendChild(addRow)
}
function swap (i, dir) {
var gs = groupsOf().slice()
var ni = i + dir
if (ni < 0 || ni >= gs.length) return
var t = gs[i]; gs[i] = gs[ni]; gs[ni] = t
save(list, gs).then(function () { if (managerOpen) openManager() })
}
// ---- 渲染 ----
function render () {
clear(fixed); clear(scrollBox)
var gs = groupsOf()
var topRow = el('div', { class: 'iwb-row' })
var mgBtn = el('button', { class: 'iwb-btn iwb-btn-sm' + (manage ? ' iwb-btn-primary' : ''), text: manage ? '退出管理' : '管理' })
mgBtn.addEventListener('click', function () { manage = !manage; picked = {}; render() })
topRow.appendChild(mgBtn)
if (manage && Object.keys(picked).length) {
var mv = el('select', { class: 'iwb-input' })
mv.appendChild(el('option', { value: '__move__', text: '移动到分组…' }))
mv.appendChild(el('option', { value: '', text: '未分组' }))
gs.forEach(function (g) { mv.appendChild(el('option', { value: g.name, text: g.name })) })
mv.addEventListener('change', function () {
if (mv.value === '__move__') return
var ids = Object.keys(picked)
picked = {}
assignGroup(ids, mv.value)
})
topRow.appendChild(mv)
}
fixed.appendChild(topRow)
// 分类胶囊
var chips = el('div', { class: 'iwb-lib-chips' })
function chip (label, value, count, extra) {
var b = el('button', { class: 'iwb-chip' + (filter === value ? ' iwb-chip-active' : '') + (extra || ''), title: value === '__none__' ? '未分组;拖拽节点组卡片到此 = 移出分组' : (value === 'all' ? '' : '拖拽节点组卡片到此 = 移动到该分组') })
b.appendChild(document.createTextNode(label))
b.appendChild(el('span', { class: 'iwb-chip-count', text: String(count) }))
b.addEventListener('click', function () { newOpen = false; filter = value; render() })
b.addEventListener('dragover', function (e) { e.preventDefault(); e.stopPropagation() })
b.addEventListener('drop', function (e) {
e.preventDefault(); e.stopPropagation()
var gid = e.dataTransfer && e.dataTransfer.getData('application/x-iwb-groupid')
if (!gid) return
assignGroup([gid], value === 'all' || value === '__none__' ? '' : value)
})
return b
}
chips.appendChild(chip('全部', 'all', list.length))
chips.appendChild(chip('未分组', '__none__', countOf('__none__'), ' iwb-chip-drop'))
gs.forEach(function (g) { chips.appendChild(chip(g.name, g.name, countOf(g.name), ' iwb-chip-drop')) })
var addChip = el('button', { class: 'iwb-chip iwb-chip-add', title: '新建分组', text: '+' })
addChip.addEventListener('click', function () { newOpen = !newOpen; render() })
chips.appendChild(addChip)
var mgChip = el('button', { class: 'iwb-chip iwb-chip-add', title: '管理分组(重命名 / 排序 / 删除)', text: '⚙' })
mgChip.addEventListener('click', openManager)
chips.appendChild(mgChip)
fixed.appendChild(chips)
if (newOpen) {
var row = el('div', { class: 'iwb-row' })
var inp = el('input', { class: 'iwb-input iwb-grow', placeholder: '新分组名称' })
var ok = el('button', { class: 'iwb-btn iwb-btn-primary', text: '确定' })
var no = el('button', { class: 'iwb-btn', text: '取消' })
ok.addEventListener('click', function () {
var n = String(inp.value || '').trim()
if (n && !groupsOf().some(function (x) { return x.name === n })) save(list, groupsOf().concat([{ id: n, name: n }]))
filter = n || filter
newOpen = false
render()
})
no.addEventListener('click', function () { newOpen = false; render() })
inp.addEventListener('keydown', function (e) { if (e.key === 'Enter') ok.click() })
row.appendChild(inp); row.appendChild(ok); row.appendChild(no)
fixed.appendChild(row)
setTimeout(function () { try { inp.focus() } catch (e) { /* ignore */ } }, 0)
}
// 卡片
var cards = el('div', { class: 'iwb-lib-cards' })
var items = visible()
items.forEach(function (g) {
var isEditing = editing === g.id
var card = el('div', {
class: 'iwb-pcard' + (isEditing ? ' iwb-pcard-editing' : '') + (manage && picked[g.id] ? ' iwb-pcard-selected' : ''),
draggable: isEditing ? 'false' : 'true',
title: manage ? '单击选中 · 右上「移动到分组」' : '双击改名 · 拖到画布实例化 · 右键移动到分组',
})
card.addEventListener('dragstart', function (e) {
if (isEditing) return
try {
e.stopPropagation()
e.dataTransfer.setData('application/x-iwb-group', JSON.stringify(g.id))
e.dataTransfer.setData('application/x-iwb-groupid', g.id)
e.dataTransfer.effectAllowed = 'copy'
} catch (err) { /* ignore */ }
})
card.addEventListener('contextmenu', function (e) {
if (manage) { e.preventDefault(); picked[g.id] = picked[g.id] ? 0 : 1; render(); return }
openMenu(e, g)
})
card.addEventListener('dblclick', function (e) {
e.stopPropagation()
if (manage) return
editing = g.id
render()
})
var rowEl = el('div', { class: 'iwb-row' })
if (isEditing) {
var input = el('input', { class: 'iwb-input iwb-grow iwb-pname-input', value: g.name || '', placeholder: '组名' })
var cancel = false
var commit = function () {
if (cancel) return
editing = ''
var n = String(input.value || '').trim() || g.name
if (n !== g.name) save(list.map(function (x) { return x.id === g.id ? Object.assign({}, x, { name: n }) : x }))
else render()
}
input.addEventListener('keydown', function (e) {
if (e.key === 'Enter') { e.stopPropagation(); commit() }
if (e.key === 'Escape') { e.stopPropagation(); cancel = true; editing = ''; render() }
})
input.addEventListener('blur', commit)
rowEl.appendChild(input)
setTimeout(function () { try { input.focus(); input.select() } catch (e) { /* ignore */ } }, 0)
} else {
var nameEl = el('span', { class: 'iwb-pname', title: '双击改名', text: g.name || '分组' })
rowEl.appendChild(nameEl)
var btns = el('span', { class: 'iwb-pbtns' })
var del = el('button', { class: 'iwb-btn iwb-btn-sm iwb-btn-danger', title: '删除节点组', text: '✕' })
del.addEventListener('click', function (e) {
e.stopPropagation()
ask('删除节点组「' + (g.name || '') + '」?', { title: '删除节点组', okText: '删除' }).then(function (ok) {
if (!ok) return
list = list.filter(function (x) { return x.id !== g.id })
render()
Promise.resolve(api.remove(g.id)).catch(function () {})
})
})
btns.appendChild(del)
rowEl.appendChild(btns)
}
card.appendChild(rowEl)
if (manage) {
card.addEventListener('click', function () {
picked[g.id] = picked[g.id] ? 0 : 1
if (!picked[g.id]) delete picked[g.id]
render()
})
} else {
card.addEventListener('click', function (e) { e.stopPropagation() })
}
cards.appendChild(card)
})
scrollBox.appendChild(cards)
if (!items.length) scrollBox.appendChild(el('div', { class: 'iwb-hint', text: '暂无收藏节点组。画布编组后点组右上角收藏,拖卡片到画布实例化。' }))
}
// 宿主侧变化(画布收藏节点组 / 其它标签页同步)→ 重拉
var off = null
try { off = api.onChanged && api.onChanged(function () { load() }) } catch (e) { /* ignore */ }
load()
return function dispose () {
try { if (typeof off === 'function') off() } catch (e) { /* ignore */ }
closeMenu()
if (modalHost && modalHost.parentNode) modalHost.parentNode.removeChild(modalHost)
modalHost = null
}
}
global.IWBPluginHost.register({
id: 'grouplib',
name: '节点组',
version: '1.0.0',
apiVersion: 1,
capabilities: ['panels', 'grouplib'],
data: { schemaVersion: 1, maxBytes: 65536 },
}, function (ctx) {
ctx.ui.registerPanel({
id: PANEL_ID,
title: '节点组',
icon: 'group',
mount: mount,
})
})
})(typeof window !== 'undefined' ? window : globalThis)
+1 -1
View File
@@ -79,6 +79,7 @@ const sourceModules = [
'ui-components.js',
'plugin-data.js',
'plugin-api-gallery.js',
'plugin-api-grouplib.js',
'plugin-host.js',
'image-compress.js',
'storage-fallback-indexeddb.js',
@@ -89,7 +90,6 @@ const sourceModules = [
'canvas-text.js',
'generation-task-graph.js',
'generation-results-store.js',
'ui-groups-sidebar.js',
'ui-lib-sidebar.js',
'ui-dock.js',
'ui-desktop-shell.js',
+1 -1
View File
@@ -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', 'image-annotate', 'image-vectorize', 'style-source', 'white-bg-800', 'xianyi-cutout']
const IDS = ['batch-export', 'blank-canvas', 'browser', 'gallery', 'grouplib', 'image-annotate', 'image-vectorize', 'style-source', 'white-bg-800', 'xianyi-cutout']
// v3.25.41(M1):目录化插件试点 —— 这些 id 产出 <id>/{manifest.json,main.js},其余仍是单文件(双轨兼容)
// ⚠️ 2026-11-20 修正:桌面包不随包发插件(scripts/strip-plugins.js),插件只能从市场装,
// 而市场目前只支持单文件 ⇒ 目录形态暂不用于生产插件,等 M3(zip 安装)落地再启用。
+53
View File
@@ -0,0 +1,53 @@
/* plugin-api-grouplib.js —— 宿主 grouplib capability(M7:节点组库插件化)
*
* 给插件「收藏的节点组 + 节点的分组」的读写面:
* list() → { groups, groupGroups }
* save({groups, groupGroups}) → { ok }
* remove(id) → { ok }
* instantiate(id) → 在画布视口中心实例化(插件不碰画布状态)
* notify(text, type) → 走宿主 toast/提示条
*
* 与 gallery 同一套「impl 桥」:capability 在 PluginHost.init 时创建(早于 Workbench 渲染),
* 因此这里只持有稳定代理,真实实现由 Workbench 每次渲染时 setImpl 注入。
* 同一份数据仍由宿主持有(iwb_web_groups / iwb_web_groupgroups),插件删了数据不丢。
*/
;(function (global) {
'use strict'
let impl = null
const listeners = []
function setImpl (next) {
impl = (next && typeof next === 'object') ? next : null
}
function call (name) {
return function () {
const fn = impl && impl[name]
if (typeof fn !== 'function') return Promise.reject(new Error('节点组能力未就绪'))
try { return Promise.resolve(fn.apply(null, arguments)) } catch (e) { return Promise.reject(e) }
}
}
// 数据变了下发一次(收藏节点组、其它标签页同步、插件自己 save 都会走到)
function emit (reason) {
for (const fn of listeners.slice()) {
try { fn(reason || 'changed') } catch (e) { /* 插件回调异常不影响宿主 */ }
}
}
const API = {
list: call('list'),
save: call('save'),
remove: call('remove'),
instantiate: call('instantiate'),
notify: call('notify'),
onChanged: function (fn) {
if (typeof fn !== 'function') return function () {}
listeners.push(fn)
return function () { const i = listeners.indexOf(fn); if (i >= 0) listeners.splice(i, 1) }
},
}
global.IWBPluginGroupLib = { setImpl: setImpl, api: function () { return API }, emit: emit }
})(typeof window !== 'undefined' ? window : globalThis)
+2 -2
View File
@@ -4,8 +4,8 @@
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']
const CAPABILITY_API_KEYS = { panels: 'ui', commands: 'commands', nodeTypes: 'nodes', generationHooks: 'generation', providers: 'providers', canvas: 'canvas', canvasWrite: 'canvas', nodeActions: 'nodeActions', gallery: 'gallery' }
const CAPABILITIES = ['panels', 'commands', 'nodeTypes', 'generationHooks', 'providers', 'canvas', 'canvasWrite', 'nodeActions', 'gallery', 'grouplib']
const CAPABILITY_API_KEYS = { panels: 'ui', commands: 'commands', nodeTypes: 'nodes', generationHooks: 'generation', providers: 'providers', canvas: 'canvas', canvasWrite: 'canvas', nodeActions: 'nodeActions', gallery: 'gallery', grouplib: 'grouplib' }
function createPluginHost(options) {
const opt = options || {}
-203
View File
@@ -1,203 +0,0 @@
/* 资源中心「节点组」侧栏(自 app.js 收编,P2-9 组件抽取)
*
* 无状态 UI 组件:数据与回调经 props 传入;React / el 从 global 解析。
* 宿主(app.js)注入两个应用层助手:props.api(数据层)、props.I(图标)。
*/
// 确认统一走页内确认(桌面端),网页端保持原生 confirm
function askConfirm (text, opts) {
const C = (typeof window !== 'undefined') ? window.IWBUIConfirm : null
if (C && typeof C.askOrNative === 'function') return C.askOrNative(text, opts)
return Promise.resolve(window.confirm(String(text)))
}
;(function (global) {
'use strict'
const R = global.React || {}
const ReactDOM = global.ReactDOM || {}
const el = (type, prop, ...children) => R.createElement(type, prop, ...children)
const useState = R.useState, useEffect = R.useEffect, useRef = R.useRef
function IWBUIGroupsSidebar (props) {
const api = props.api
const I = props.I
const [w, setW] = useState(300)
const [drag] = useState(() => ({ active: false, sx: 0, sw: 300 }))
const [gEdit, setGEdit] = useState(null)
const [gEditName, setGEditName] = useState('')
const [groupFilter, setGroupFilter] = useState('all')
const [newGroup, setNewGroup] = useState(false)
const [newGroupName, setNewGroupName] = useState('')
const [gMgrOpen, setGMgrOpen] = useState(false)
const [manage, setManage] = useState(false)
const [selSet, setSelSet] = useState(() => new Set())
const [groupMenu, setGroupMenu] = useState(null)
useEffect(() => {
if (!groupMenu) return
const closeOutside = (e) => { if (!e.target || !e.target.closest || !e.target.closest('.iwb-lib-group-menu')) setGroupMenu(null) }
document.addEventListener('pointerdown', closeOutside, true)
return () => document.removeEventListener('pointerdown', closeOutside, true)
}, [groupMenu])
const [gmEdit, setGmEdit] = useState(null)
const [gmNew, setGmNew] = useState('')
const gEditCancel = useRef(false) // Esc 取消后 blur 不误提交
const handleDrag = (e) => {
if (!drag.active) return
e.preventDefault()
setW(Math.max(240, Math.min(560, drag.sw + (drag.sx - e.clientX))))
}
const stopDrag = () => { drag.active = false }
const list = props.savedGroups || []
const groups = (props.nodeGroupGroups && props.nodeGroupGroups.length)
? props.nodeGroupGroups
: (() => { const seen = []; for (const g of list) { const gr = String((g && g.group) || '').trim(); if (gr && !seen.some((x) => x.name === gr)) seen.push({ id: gr, name: gr }) } return seen })()
const saveList = (newList) => {
// 失败提示走红色(2026-11-12):这里原来只传一句文案,onFlash 固定按「成功」绿色渲染 ⇒ 失败看着像成功。
props.onSavedGroupsChange((newList || []).map((g) => ({ ...g, group: String((g && g.group) || '').trim() })), () => props.onFlash && props.onFlash('节点组保存失败,请重试', 'err'))
}
const saveGroups = (gs) => {
props.onNodeGroupGroupsChange(gs)
// 同 ui-lib-sidebar:api() 失败是 resolve({ok:false}),不是 reject ⇒ .catch 抓不到,必须看返回值。
api('groups', { groups: list, groupGroups: gs })
.then((r) => { if (r && r.ok === false && props.onFlash) props.onFlash(r.error || '节点分组保存失败,请重试', 'err') })
.catch(() => { if (props.onFlash) props.onFlash('节点分组保存失败,请重试', 'err') })
}
const assignNodeGroup = (ids, group) => { saveList(list.map((x) => ids.includes(x.id) ? { ...x, group: group || '' } : x)); setGroupMenu(null); props.onFlash && props.onFlash('已移动到' + (group || '未分组')) }
const openNodeGroupMenu = (e, g) => { e.preventDefault(); e.stopPropagation(); setGroupMenu({ x: e.clientX, y: e.clientY, ids: [g.id] }) }
const moveSelected = (group) => { if (!selSet.size) return; assignNodeGroup(Array.from(selSet), group); setSelSet(new Set()) }
const groupCount = (gname) => {
if (gname === 'all') return list.length
if (gname === '__none__') return list.filter((g) => !String((g && g.group) || '').trim()).length
return list.filter((g) => (g && g.group) === gname).length
}
const filtered = list.filter((g) => {
if (groupFilter === '__none__') return !String((g && g.group) || '').trim()
if (groupFilter !== 'all') return (g && g.group) === groupFilter
return true
})
// 分组管理操作(与提示词库一致:重命名/删除/排序/新建,空分组保留)
const confirmNewGroup = () => {
const name = newGroupName.trim()
if (!name) { setNewGroup(false); return }
if (!groups.some((g) => g.name === name)) saveGroups(groups.concat([{ id: name, name }]))
setGroupFilter(name)
setNewGroup(false)
setNewGroupName('')
}
const renameGroup = (oldName, newName) => {
const n = String(newName || '').trim()
if (!n || n === oldName) return
if (groups.some((g) => g.name === n && g.name !== oldName)) return
saveGroups(groups.map((g) => (g.name === oldName ? { id: n, name: n } : g)))
saveList(list.map((g) => (g.group === oldName ? { ...g, group: n } : g)))
if (groupFilter === oldName) setGroupFilter(n)
}
const removeGroup = async (name) => {
if (!(await askConfirm('删除节点组分组「' + name + '」?组内节点组将移至「未分组」(不删除节点组)。', { title: '删除分组', okText: '删除' }))) return
saveGroups(groups.filter((g) => g.name !== name))
saveList(list.map((g) => (g.group === name ? { ...g, group: '' } : g)))
if (groupFilter === name) setGroupFilter('all')
}
const moveGroup = (i, dir) => {
const ni = i + dir
if (ni < 0 || ni >= groups.length) return
const gs = groups.slice()
const t = gs[i]; gs[i] = gs[ni]; gs[ni] = t
saveGroups(gs)
}
const mgrModal = gMgrOpen ? el('div', { className: 'iwb-modal-mask', onWheel: (e) => e.stopPropagation(), onPointerDown: (e) => { if (e.target === e.currentTarget) setGMgrOpen(false) } },
el('div', { className: 'iwb-modal iwb-modal-sm' },
el('div', { className: 'iwb-modal-head' },
el('span', { className: 'iwb-toolbar-title' }, '管理节点组分组(' + groups.length + ')'),
el('button', { className: 'iwb-btn iwb-btn-sm', title: '关闭', onClick: () => setGMgrOpen(false) }, I('x')),
),
el('div', { className: 'iwb-modal-body' },
!groups.length ? el('div', { className: 'iwb-hint' }, '暂无分组。可在下方新建。') : null,
groups.map((g, i) => {
const editingThis = gmEdit && gmEdit.name === g.name
return el('div', { key: g.id || g.name, className: 'iwb-gmgr-row' },
editingThis
? el('input', { className: 'iwb-input iwb-grow', value: gmEdit.value, autoFocus: true, onChange: (e) => setGmEdit({ name: g.name, value: e.target.value }), onKeyDown: (e) => { if (e.key === 'Enter') { renameGroup(g.name, gmEdit.value); setGmEdit(null) } if (e.key === 'Escape') setGmEdit(null) } })
: el('span', { className: 'iwb-gmgr-name' }, g.name),
el('span', { className: 'iwb-gmgr-count' }, groupCount(g.name) + ' 组'),
editingThis
? el('button', { className: 'iwb-btn iwb-btn-sm iwb-btn-primary', onClick: () => { renameGroup(g.name, gmEdit.value); setGmEdit(null) } }, '✓')
: el('button', { className: 'iwb-btn iwb-btn-sm', title: '重命名', onClick: () => setGmEdit({ name: g.name, value: g.name }) }, '重命名'),
el('button', { className: 'iwb-btn iwb-btn-sm', title: '上移', disabled: i === 0, onClick: () => moveGroup(i, -1) }, '↑'),
el('button', { className: 'iwb-btn iwb-btn-sm', title: '下移', disabled: i === groups.length - 1, onClick: () => moveGroup(i, 1) }, '↓'),
el('button', { className: 'iwb-btn iwb-btn-sm iwb-btn-danger', title: '删除分组(组内节点组移至未分组)', onClick: () => removeGroup(g.name) }, '删除'),
)
}),
el('div', { className: 'iwb-row' },
el('input', { className: 'iwb-input iwb-grow', placeholder: '新分组名称', value: gmNew, onChange: (e) => setGmNew(e.target.value), onKeyDown: (e) => { if (e.key === 'Enter') { const n = gmNew.trim(); if (n) { if (!groups.some((x) => x.name === n)) saveGroups(groups.concat([{ id: n, name: n }])); setGmNew('') } } } }),
el('button', { className: 'iwb-btn', onClick: () => { const n = gmNew.trim(); if (n) { if (!groups.some((x) => x.name === n)) saveGroups(groups.concat([{ id: n, name: n }])); setGmNew('') } } }, '+ 添加'),
),
),
),
) : null
// 分类胶囊行(同提示词库;拖拽卡片到分组 = 移动分组)
const chipsRow = el('div', { className: 'iwb-lib-chips' },
el('button', { className: 'iwb-chip' + (groupFilter === 'all' ? ' iwb-chip-active' : ''), onClick: () => { setNewGroup(false); setGroupFilter('all') } }, '全部', el('span', { className: 'iwb-chip-count' }, list.length)),
el('button', { className: 'iwb-chip' + (groupFilter === '__none__' ? ' iwb-chip-active' : '') + ' iwb-chip-drop', title: '未分组;拖拽节点组卡片到此 = 移出分组', onClick: () => { setNewGroup(false); setGroupFilter('__none__') }, onDragOver: (e) => { e.preventDefault(); e.stopPropagation(); e.dataTransfer.dropEffect = 'move' }, onDrop: (e) => { e.preventDefault(); e.stopPropagation(); const gid = e.dataTransfer && e.dataTransfer.getData('application/x-iwb-groupid'); if (gid) { saveList(list.map((x) => (x.id === gid ? { ...x, group: '' } : x))); props.onFlash && props.onFlash('已移到未分组') } } }, '未分组', el('span', { className: 'iwb-chip-count' }, groupCount('__none__'))),
groups.map((g) => el('button', { key: g.id || g.name, className: 'iwb-chip' + (groupFilter === g.name ? ' iwb-chip-active' : '') + ' iwb-chip-drop', title: '拖拽节点组卡片到此 = 移动到该分组', onClick: () => { setNewGroup(false); setGroupFilter(g.name) }, onDragOver: (e) => { e.preventDefault(); e.stopPropagation(); e.dataTransfer.dropEffect = 'copy' }, onDropCapture: (e) => { e.stopPropagation() }, onDrop: (e) => { e.preventDefault(); e.stopPropagation(); const gid = e.dataTransfer && e.dataTransfer.getData('application/x-iwb-groupid'); if (gid) { saveList(list.map((x) => (x.id === gid ? { ...x, group: g.name } : x))); props.onFlash && props.onFlash('已移动到分组「' + g.name + '」') } } }, g.name, el('span', { className: 'iwb-chip-count' }, groupCount(g.name)))),
el('button', { key: 'add', className: 'iwb-chip iwb-chip-add', title: '新建分组', onClick: () => { setNewGroup(!newGroup); if (!newGroup) setNewGroupName('') } }, '+'),
el('button', { key: 'mgmt', className: 'iwb-chip iwb-chip-add', title: '管理分组(重命名 / 排序 / 删除)', onClick: () => setGMgrOpen(true) }, '⚙'),
)
const newGroupRow = newGroup ? el('div', { className: 'iwb-row' },
el('input', { className: 'iwb-input iwb-grow', placeholder: '新分组名称', value: newGroupName, onChange: (e) => setNewGroupName(e.target.value) }),
el('button', { className: 'iwb-btn iwb-btn-primary', onClick: confirmNewGroup }, '确定'),
el('button', { className: 'iwb-btn', onClick: () => setNewGroup(false) }, '取消'),
) : null
// 卡片:只展示标题;双击标题原位置改名(Enter/blur 提交、Esc 取消);管理按钮删除(确认提示)
const cards = filtered.map((g) => {
const editing = gEdit === g.id
const commitRename = () => {
if (gEditCancel.current) { gEditCancel.current = false; return }
saveList(list.map((x) => (x.id === g.id ? { ...x, name: gEditName.trim() || x.name } : x)))
setGEdit(null)
}
const cancelEdit = () => { gEditCancel.current = true; setGEdit(null) }
return el('div', { key: g.id, className: 'iwb-pcard' + (editing ? ' iwb-pcard-editing' : '') + (manage && selSet.has(g.id) ? ' iwb-pcard-selected' : ''), draggable: !editing, onContextMenu: (e) => openNodeGroupMenu(e, g),
onDragStart: (e) => { try { e.stopPropagation(); e.dataTransfer.setData('application/x-iwb-group', JSON.stringify(g.id)); e.dataTransfer.setData('application/x-iwb-groupid', g.id); e.dataTransfer.effectAllowed = 'copy' } catch (err) { /* ignore */ } },
onDragEnd: (e) => { try { e.stopPropagation() } catch (err) { /* ignore */ } },
onDoubleClick: (e) => { e.stopPropagation(); gEditCancel.current = false; setGEdit(g.id); setGEditName(g.name || '') },
},
el('div', { className: 'iwb-row' },
editing
? el('input', { className: 'iwb-input iwb-grow iwb-pname-input', value: gEditName, autoFocus: true, placeholder: '组名', spellCheck: false, onChange: (e) => setGEditName(e.target.value), onKeyDown: (e) => { if (e.key === 'Enter') { e.stopPropagation(); commitRename() } if (e.key === 'Escape') { e.stopPropagation(); cancelEdit() } }, onBlur: commitRename, onPointerDown: (e) => e.stopPropagation() })
: el('span', { className: 'iwb-pname', title: '双击改名' }, g.name || '分组'),
el('span', { className: 'iwb-pbtns' },
el('button', { className: 'iwb-btn iwb-btn-sm iwb-btn-danger', title: '删除节点组', onClick: async (e) => { e.stopPropagation(); if (await askConfirm('删除节点组「' + (g.name || '') + '」?', { title: '删除节点组', okText: '删除' })) saveList(list.filter((x) => x.id !== g.id)) } }, I('x')),
),
),
)
})
const nodeGroupMenuEl = groupMenu ? ReactDOM.createPortal(el('div', { className: 'iwb-ctxmenu iwb-lib-group-menu', style: { left: groupMenu.x, top: groupMenu.y }, onPointerDown: (e) => e.stopPropagation(), onContextMenu: (e) => e.preventDefault() }, el('div', { className: 'iwb-ctx-title' }, '移动到分组'), el('button', { className: 'iwb-ctx-item', onClick: () => assignNodeGroup(groupMenu.ids, '') }, '未分组'), groups.map((g) => el('button', { key: g.id || g.name, className: 'iwb-ctx-item', onClick: () => assignNodeGroup(groupMenu.ids, g.name) }, g.name))), document.body) : null
const bodyEl = el('div', { className: 'iwb-lib-body' },
el('div', { className: 'iwb-lib-fixed' },
el('div', { className: 'iwb-row' }, el('button', { className: 'iwb-btn iwb-btn-sm' + (manage ? ' iwb-btn-primary' : ''), onClick: () => { setManage(!manage); setSelSet(new Set()) } }, manage ? '退出管理' : '管理'), manage && selSet.size ? el('select', { className: 'iwb-input', value: '__move__', onChange: (e) => { if (e.target.value !== '__move__') moveSelected(e.target.value) } }, el('option', { value: '__move__' }, '移动到分组…'), el('option', { value: '' }, '未分组'), groups.map((g) => el('option', { key: g.id || g.name, value: g.name }, g.name))) : null),
chipsRow,
newGroupRow,
),
el('div', { className: 'iwb-lib-scroll' },
el('div', { className: 'iwb-lib-cards' }, cards),
!filtered.length ? el('div', { className: 'iwb-hint' }, '暂无收藏节点组。画布编组后点组右上角收藏,拖卡片到画布实例化。') : null,
),
)
if (props.embedded) {
return el('div', { className: 'iwb-groups-embedded' }, bodyEl, mgrModal, nodeGroupMenuEl)
}
return el('div', { className: 'iwb-lib', style: { width: w }, onPointerDown: (e) => e.stopPropagation(), onPointerMove: (e) => { e.stopPropagation(); handleDrag(e) }, onPointerUp: (e) => { e.stopPropagation(); stopDrag() }, onPointerLeave: (e) => { e.stopPropagation(); stopDrag() }, onClick: (e) => e.stopPropagation(), onDoubleClick: (e) => e.stopPropagation(), onWheel: (e) => e.stopPropagation() },
el('div', { className: 'iwb-lib-handle', onPointerDown: (e) => { e.stopPropagation(); drag.active = true; drag.sx = e.clientX; drag.sw = w } }, null),
el('div', { className: 'iwb-lib-head' },
el('span', { className: 'iwb-toolbar-title' }, '节点组'),
el('span', { className: 'iwb-pbtns' },
el('button', { className: 'iwb-btn iwb-btn-sm', title: '刷新', onClick: props.onRefresh }, I('refresh')),
el('button', { className: 'iwb-btn iwb-btn-sm', onClick: props.onClose }, '✕'),
),
),
bodyEl,
mgrModal,
)
}
global.IWBUIGroupsSidebar = IWBUIGroupsSidebar
})(typeof window !== 'undefined' ? window : globalThis)
+1 -1
View File
@@ -24,6 +24,7 @@
"IWBNodeBodies",
"IWBPluginData",
"IWBPluginGallery",
"IWBPluginGroupLib",
"IWBPluginHost",
"IWBProviderPing",
"IWBResultImg",
@@ -64,7 +65,6 @@
"IWBUIConfirm",
"IWBUIConnectMenu",
"IWBUIGenConfigPanel",
"IWBUIGroupsSidebar",
"IWBUILibSidebar",
"IWBUINodeCard",
"IWBUIProductNav",
+1 -1
View File
@@ -51,6 +51,7 @@
"ui-components.js",
"plugin-data.js",
"plugin-api-gallery.js",
"plugin-api-grouplib.js",
"plugin-host.js",
"image-compress.js",
"storage-fallback-indexeddb.js",
@@ -61,7 +62,6 @@
"canvas-text.js",
"generation-task-graph.js",
"generation-results-store.js",
"ui-groups-sidebar.js",
"ui-lib-sidebar.js",
"ui-dock.js",
"ui-desktop-shell.js",
-80
View File
@@ -1,80 +0,0 @@
// 节点组侧栏验收(2026-10-28,P1)
//
// 守 src/ui-groups-sidebar.js(此前 e2e 覆盖仅 2%)。
// 它是资源中心「节点组」tab 的内容:分组管理(新建/重命名/删除)+ 收藏节点组卡片。
//
// 本轮只覆盖**渲染路径**(低风险、稳定):
// ① 打开资源中心 → 节点组 tab → 侧栏正常渲染(空态文案 + 新建分组入口),无 pageerror
// ② 预置一个已收藏的节点组 → 卡片渲染出组名与节点数
//
// ⚠️ 未覆盖:拖拽卡片到画布实例化、分组重命名/删除/排序 ——
// 这些是复合交互(拖拽 + 二次确认),硬写会得到脆弱用例,留作独立任务。
const { test, expect } = require('./_pw-coverage')
const baseURL = process.env.IWB_BASE_URL || 'http://127.0.0.1:8787'
test.use({ baseURL, viewport: { width: 1440, height: 1000 } })
const WS = {
workspaces: [{ id: 'ws_grp', name: '节点组', nodes: [], edges: [], groups: [] }],
activeId: 'ws_grp', rev: 1, schemaVersion: 1,
}
// 已收藏的节点组(savedGroups 的存储键 = iwb_web_groups)
const SAVED = [{
id: 'sg1', name: '封面三件套', group: '营销',
nodes: [
{ id: 'n1', type: 'prompt', x: 0, y: 0, data: { text: '标题文案' } },
{ id: 'n2', type: 'gen', x: 240, y: 0, data: { enabled: true, provider: 'tuzi', keyGroup: 'daily', model: 'gpt-image-2', ratio: '1:1', variants: 1 } },
],
edges: [{ id: 'se1', from: 'n1', to: 'n2' }],
}]
async function openGroupsTab(page, saved) {
await page.addInitScript(([ws, sv]) => {
if (localStorage.getItem('__iwb_grp_seeded__') !== '1') {
localStorage.setItem('iwb_web_workspaces', JSON.stringify(ws))
localStorage.setItem('iwb_web_groups', JSON.stringify(sv))
localStorage.setItem('__iwb_grp_seeded__', '1')
}
}, [WS, saved])
await page.goto('/', { waitUntil: 'domcontentloaded' })
await page.waitForSelector('.iwb-home-card:not(.iwb-home-new)', { timeout: 20000 })
await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick()
await page.waitForSelector('.iwb-canvas-topbar', { timeout: 20000 })
await page.locator('.iwb-top-nav-icon[title*="资源中心"]').click()
await page.waitForSelector('.iwb-res-tabs', { timeout: 15000 })
await page.waitForTimeout(400)
const tab = page.locator('.iwb-res-tab', { hasText: '节点组' }).first()
await expect(tab, '资源中心应有「节点组」tab').toBeVisible()
await tab.click()
await page.waitForTimeout(700)
}
test('① 空态:节点组侧栏渲染出空态文案与「新建分组」入口,无 pageerror', async ({ page }) => {
const errors = []
page.on('pageerror', (e) => errors.push(String(e && e.message || e)))
await openGroupsTab(page, [])
// tab 应已切到「节点组」
const activeTab = await page.evaluate(() => {
const t = Array.from(document.querySelectorAll('.iwb-res-tab')).find((e) => e.className.indexOf('active') >= 0)
return t ? t.innerText : ''
})
expect(activeTab, '「节点组」tab 应处于选中态').toContain('节点组')
const text = await page.locator('.iwb-fullmask, .iwb-fullpanel').first().innerText()
// 空态文案(实测空态下不渲染「新建分组」按钮 —— 那是有分组时才出现的管理入口)
expect(text, '空态应提示暂无收藏节点组').toContain('暂无收藏节点组')
expect(errors, '不应有 pageerror').toEqual([])
})
test('② 有数据:已收藏的节点组渲染出组名与节点数', async ({ page }) => {
const errors = []
page.on('pageerror', (e) => errors.push(String(e && e.message || e)))
await openGroupsTab(page, SAVED)
const panel = await page.locator('.iwb-fullmask, .iwb-fullpanel').first().innerText()
expect(panel, '应显示收藏的节点组名称').toContain('封面三件套')
expect(panel, '应显示该组的分组名').toContain('营销')
expect(errors, '不应有 pageerror').toEqual([])
})
+2 -1
View File
@@ -31,7 +31,8 @@ assert.deepStrictEqual(specsBase, expectedSpecs, '门禁 spec 必须等于全部
// —— 这两条 spec 随 v3.24.81/82 一起进仓库时没同步更新本数字,门禁从那时起是红的(2026-11-14 补记)
// 55 = 54 + iwb-multi-tab(v3.24.85:跨标签页契约 —— A 页 flush 落盘后 B 页靠 rev 轮询可见 / 图库归档受跨进程锁保护)
// 53 = 55 − iwb-csp-gate − iwb-functions-headers(v3.25.15:网页版部署面删除,两条只测 _headers/Functions 的 spec 一并删除)
assert.strictEqual(result.specs.length, 53, '当前门禁应自动发现 53 个 spec')
// 52 = 53 − iwb-groups-sidebar(v3.25.56 节点组库改为插件 grouplib,宿主侧栏组件删除,其 e2e 一并移除)
assert.strictEqual(result.specs.length, 52, '当前门禁应自动发现 52 个 spec')
// 排除集合 = 全部人工 dev 探针,且都必须已声明标记
// 4 = 3 + _probe-tab-switch(切画布标签耗时归因:四轮对照实验,只读诊断)
assert.deepStrictEqual(excludedBase, ['_perf-baseline.spec.js', '_plugin-host-probe.spec.js', '_probe-drag.spec.js', '_probe-tab-switch.spec.js'], '被排除的应是全部带 iwb-dev-probe 标记的 dev 探针')
+107
View File
@@ -0,0 +1,107 @@
'use strict'
// 节点组库插件渲染回归(grouplib 1.0.0)
//
// 守三件事:① 列表/分组胶囊/卡片渲染;② 改名·删除·移动分组都经 ctx.grouplib 落盘(插件不留副本);
// ③ 卡片拖拽必须带 application/x-iwb-group(画布 drop 靠它实例化)。
const assert = require('assert')
const fs = require('fs')
const path = require('path')
const vm = require('vm')
const { JSDOM } = require('jsdom')
const src = fs.readFileSync(path.resolve(__dirname, '..', '..', 'iwb-plugins-desktop', 'grouplib', 'src', 'index.js'), 'utf8')
const wait = (ms) => new Promise((r) => setTimeout(r, ms))
;(async () => {
const dom = new JSDOM('<!doctype html><html><body><div id="host"></div></body></html>', { pretendToBeVisual: true })
const { window } = dom
window.confirm = () => true
let registered = null
window.IWBPluginHost = { register (manifest, factory) { registered = { manifest, factory } } }
const sandbox = { window, document: window.document, console, setTimeout, clearTimeout, Promise, Object, Array, JSON, Math, Date, String, Number }
vm.runInNewContext(src, sandbox)
assert.ok(registered, '插件应注册')
assert.strictEqual(registered.manifest.id, 'grouplib')
assert.ok(registered.manifest.capabilities.indexOf('grouplib') >= 0, '应声明 grouplib 能力')
let groups = [
{ id: 'g1', name: '海报组', group: '电商', nodes: [] },
{ id: 'g2', name: '白底组', group: '', nodes: [] },
]
let groupGroups = [{ id: '电商', name: '电商' }]
const calls = { save: 0, remove: [], instantiate: [], notify: [] }
let mounted = null
const ctx = {
ui: { registerPanel (p) { mounted = p.mount } },
grouplib: {
list: async () => ({ groups: groups.slice(), groupGroups: groupGroups.slice() }),
save: async (payload) => { calls.save++; groups = payload.groups.slice(); groupGroups = payload.groupGroups.slice(); return { ok: true } },
remove: async (id) => { calls.remove.push(id); groups = groups.filter((g) => g.id !== id); return { ok: true } },
instantiate: async (id) => { calls.instantiate.push(id); return { ok: true } },
notify: (t, ty) => { calls.notify.push([t, ty]) },
onChanged: () => () => {},
},
}
registered.factory(ctx)
assert.ok(mounted, '应注册面板 mount')
const host = window.document.getElementById('host')
mounted(host, ctx)
await wait(50)
const cards = () => Array.from(host.querySelectorAll('.iwb-pcard'))
assert.strictEqual(cards().length, 2, '应渲染两个节点组卡片,实际 ' + cards().length)
const chips = Array.from(host.querySelectorAll('.iwb-chip')).map((c) => c.textContent)
assert.ok(chips.some((t) => t.indexOf('全部') === 0 && /2$/.test(t)), '应有「全部 2」胶囊:' + chips.join('|'))
assert.ok(chips.some((t) => t.indexOf('未分组') === 0 && /1$/.test(t)), '应有「未分组 1」胶囊:' + chips.join('|'))
// 分组筛选:点「未分组」只剩白底组
const noneChip = Array.from(host.querySelectorAll('.iwb-chip')).find((c) => c.textContent.indexOf('未分组') === 0)
noneChip.dispatchEvent(new window.MouseEvent('click', { bubbles: true }))
await wait(20)
assert.strictEqual(cards().length, 1, '筛选未分组后应只剩 1 张')
assert.ok(cards()[0].textContent.indexOf('白底组') >= 0, '剩下的应是白底组')
// 拖拽 payload:画布 drop 依赖 application/x-iwb-group(JSON 字符串)
const card = cards()[0]
const store = {}
const dragEvt = new window.Event('dragstart', { bubbles: true })
dragEvt.dataTransfer = { setData: (k, v) => { store[k] = v }, effectAllowed: '' }
card.dispatchEvent(dragEvt)
assert.strictEqual(store['application/x-iwb-groupid'], 'g2', '拖拽应带组 id')
assert.strictEqual(JSON.parse(store['application/x-iwb-group']), 'g2', '拖拽应带实例化 payload')
// 双击改名 → ctx.grouplib.save 落盘
card.dispatchEvent(new window.MouseEvent('dblclick', { bubbles: true }))
await wait(20)
const input = cards()[0] && cards()[0].querySelector('.iwb-pname-input')
assert.ok(input, '双击后应出现改名输入框')
input.value = '白底组-新'
input.dispatchEvent(new window.KeyboardEvent('keydown', { key: 'Enter', bubbles: true }))
await wait(50)
assert.ok(calls.save >= 1, '改名应经 save 落盘')
assert.strictEqual(groups.find((g) => g.id === 'g2').name, '白底组-新', '宿主侧名字应更新')
// 删除 → 走 remove(id)(不是本地删完就算)
const del = Array.from(host.querySelectorAll('.iwb-pbtns .iwb-btn-danger'))[0]
assert.ok(del, '卡片应有删除按钮')
del.dispatchEvent(new window.MouseEvent('click', { bubbles: true }))
await wait(60)
assert.deepStrictEqual(calls.remove, ['g2'], '删除应调用宿主 remove,实际 ' + JSON.stringify(calls.remove))
// 删掉最后一张 → 空态
Array.from(host.querySelectorAll('.iwb-chip')).forEach((c) => { if (c.textContent.indexOf('全部') === 0) c.dispatchEvent(new window.MouseEvent('click', { bubbles: true })) })
await wait(20)
const last = cards()[0]
assert.ok(last, '应还剩一张卡片')
last.querySelector('.iwb-pbtns .iwb-btn-danger').dispatchEvent(new window.MouseEvent('click', { bubbles: true }))
await wait(60)
assert.deepStrictEqual(calls.remove, ['g2', 'g1'], '两次删除都应走宿主 remove')
assert.ok(host.querySelector('.iwb-hint'), '无节点组时应给空态提示')
console.log('grouplib render checks passed(列表/筛选/拖拽 payload/改名落盘/删除走宿主)')
})().catch((e) => { console.error(e); process.exit(1) })
+1 -1
View File
@@ -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,gallery,generationHooks,nodeActions,nodeTypes,panels,providers')
assert.strictEqual(host0.capabilities.slice().sort().join(','), 'canvas,canvasWrite,commands,gallery,generationHooks,grouplib,nodeActions,nodeTypes,panels,providers')
const manifest = (over) => Object.assign({ id: 'demo-plugin', name: 'Demo', version: '1.0.0', apiVersion: 1, capabilities: [] }, over)
const stateOf = (ids) => {
-160
View File
@@ -1,160 +0,0 @@
'use strict'
// src/ui-groups-sidebar.js 的行为测试(此前该组件完全无测试)。
//
// 用 vm + 极简 React/ReactDOM 假体驱动组件:右键卡片 → groupMenu 置位 → 重渲染 → ReactDOM.createPortal
// 渲染「移动到分组」菜单 → 点「未分组」→ onSavedGroupsChange/onFlash 被调用。
// 注:真实环境里 ReactDOM 由 vendor 脚本提供为浏览器全局;本测试以假体注入,只验证组件自身接线。
const assert = require('assert')
const fs = require('fs')
const path = require('path')
const vm = require('vm')
const root = path.resolve(__dirname, '..')
const loadComp = () => {
const states = []
const refs = []
let cursor = 0
let rerender = null
const fakeReact = {
createElement: (type, props, ...children) => ({ __el: true, type, props: props || {}, children: children.flat() }),
useState: (init) => {
const i = cursor++
if (!(i in states)) states[i] = (typeof init === 'function') ? init() : init
return [states[i], (v) => { states[i] = (typeof v === 'function') ? v(states[i]) : v; if (rerender) rerender() }]
},
useEffect: () => {}, // 不执行副作用(本测试不需要 document 监听)
useRef: (init) => { const i = cursor++; if (!(i in refs)) refs[i] = { current: init === undefined ? null : init }; return refs[i] },
}
const portals = []
const fakeReactDOM = { createPortal: (child, container) => { portals.push({ child, container }); return { __el: true, type: '__portal__', props: {}, children: [child] } } }
const sandbox = {
React: fakeReact,
ReactDOM: fakeReactDOM,
document: { body: { __body: true }, addEventListener: () => {}, removeEventListener: () => {} },
console,
confirm: () => true,
}
// 组件里用的是 bare `window.confirm`(删除分组前确认)⇒ 沙箱必须提供 window 自引用,
// 否则一走到 removeGroup 就 ReferenceError(此前没有用例触发过「删除分组」)。
sandbox.window = sandbox
vm.runInNewContext(fs.readFileSync(path.join(root, 'src', 'ui-groups-sidebar.js'), 'utf8'), sandbox)
const Comp = sandbox.IWBUIGroupsSidebar
let tree = null
const render = (props) => { cursor = 0; tree = Comp(props) }
rerender = () => render(render.props)
return { render: (props) => { render.props = props; render(props) }, portals, getTree: () => tree }
}
const walk = (node, fn) => {
if (!node || typeof node !== 'object') return
if (Array.isArray(node)) { node.forEach((n) => walk(n, fn)); return }
if (node.__el) { fn(node); (node.children || []).forEach((c) => walk(c, fn)) }
}
assert.strictEqual(typeof vm.runInNewContext, 'function')
const created = []
const flashed = []
const app = loadComp()
const props = {
embedded: true,
savedGroups: [{ id: 'g1', name: '收藏组1', group: '' }],
nodeGroupGroups: [{ id: 'x', name: '分组X' }],
api: () => Promise.resolve(),
I: () => null,
onSavedGroupsChange: (list) => created.push(list),
onFlash: (m) => flashed.push(m),
}
// 初次渲染:groupMenu 为 null ⇒ 不应有 portal
app.render(props)
assert.strictEqual(app.portals.length, 0, '未右键时不应渲染「移动到分组」菜单')
assert.ok(app.getTree(), '组件应返回元素树')
// 右键卡片 → 打开分组菜单(此路径此前因 ReactDOM 未绑定而抛 ReferenceError)
let card = null
walk(app.getTree(), (n) => {
if (!card && typeof n.props.className === 'string' && n.props.className.indexOf('iwb-pcard') === 0) card = n
})
assert.ok(card, '应能定位到节点组卡片')
card.props.onContextMenu({ preventDefault() {}, stopPropagation() {}, clientX: 30, clientY: 40 })
assert.strictEqual(app.portals.length, 1, '右键后应经 ReactDOM.createPortal 渲染菜单')
assert.ok(app.portals[0].container && app.portals[0].container.__body === true, 'portal 容器应为 document.body')
// 菜单里应含「移动到分组」标题与「未分组」按钮(只在 portal 子树里找,避免撞上分类芯片)
let menuBtn = null
walk(app.portals[0].child, (n) => { if (!menuBtn && n.type === 'button' && n.children[0] === '未分组') menuBtn = n })
assert.ok(menuBtn, '菜单应含「未分组」按钮')
// 点「未分组」→ 与分组解绑并回调
menuBtn.props.onClick()
assert.strictEqual(created.length, 1, 'assignNodeGroup 应触发 onSavedGroupsChange')
assert.strictEqual(created[0][0].group, '', '应把该组移到未分组')
assert.strictEqual(flashed.join(','), '已移动到未分组')
// ── 失败必须可见(2026-11-12)──
// 两条保存路径都要在失败时给出 **err 级** 提示:
// ① saveList:组件把失败回调交给 app.js(那边判 r.ok===false 后调用),文案必须是 err;
// ② saveGroups:本组件自己发 api('groups'),失败是 resolve({ok:false}) 而不是 reject。
const tick = () => new Promise((r) => setTimeout(r, 0))
;(async () => {
// ① saveList 的失败回调 → onFlash(..., 'err')
{
const flashes = []
let onErr = null
const a = loadComp()
a.render({
embedded: true,
savedGroups: [{ id: 'g1', name: '收藏组1', group: '分组X' }],
nodeGroupGroups: [{ id: 'x', name: '分组X' }],
api: () => Promise.resolve(),
I: () => null,
onSavedGroupsChange: (list, cb) => { onErr = cb },
onFlash: (m, ty) => flashes.push([m, ty]),
})
let card = null
walk(a.getTree(), (n) => { if (!card && typeof n.props.className === 'string' && n.props.className.indexOf('iwb-pcard') === 0) card = n })
card.props.onContextMenu({ preventDefault() {}, stopPropagation() {}, clientX: 10, clientY: 10 })
let btn = null
for (const p of a.portals) walk(p.child, (n) => { if (!btn && n.type === 'button' && n.children[0] === '未分组') btn = n })
btn.props.onClick()
assert.ok(typeof onErr === 'function', 'saveList 应把失败回调交给 app.js(否则失败永远显示不出来)')
onErr()
assert.ok(flashes.some((f) => f[1] === 'err' && /保存失败/.test(f[0])),
'节点组保存失败必须是 err 级提示(实际:' + JSON.stringify(flashes) + ')')
}
// ② saveGroups:api 返回 {ok:false} → onFlash(..., 'err')
{
const flashes = []
const a = loadComp()
a.render({
embedded: true,
savedGroups: [{ id: 'g1', name: '收藏组1', group: '' }],
nodeGroupGroups: [{ id: 'x', name: '分组X' }],
api: () => Promise.resolve({ ok: false, error: '节点分组保存失败:浏览器本地存储空间不足。' }),
I: () => null,
onSavedGroupsChange: () => {},
onNodeGroupGroupsChange: () => {},
onFlash: (m, ty) => flashes.push([m, ty]),
})
let mgr = null
// 注意:同排还有「+ 新建分组」也是 iwb-chip-add ⇒ 必须按 title 精确区分
walk(a.getTree(), (n) => { if (!mgr && typeof n.props.title === 'string' && n.props.title.indexOf('管理分组') === 0) mgr = n })
assert.ok(mgr, '应能找到「管理分组」入口')
mgr.props.onClick()
let del = null
// 管理分组弹窗是**内联**渲染(不经 portal),所以要在整棵树里找
walk(a.getTree(), (n) => { if (!del && n.type === 'button' && typeof n.props.title === 'string' && n.props.title.indexOf('删除分组') === 0) del = n })
assert.ok(del, '管理分组弹窗应含「删除分组」按钮')
del.props.onClick()
await tick()
assert.ok(flashes.some((f) => f[1] === 'err' && /保存失败/.test(f[0])),
'删除分组后保存失败必须给 err 提示(实际:' + JSON.stringify(flashes) + ')')
}
console.log('ui-groups-sidebar checks passed')
})().catch((e) => { console.error('❌ ' + ((e && e.stack) || e)); process.exit(1) })