diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2130368..99651cc 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -41,7 +41,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 136 个单测文件(jsdom 契约测试;2026-11-07 新增 sync-facts-guard(事实一致性)/ _helpers/source(统一源文本);2026-11-12 新增 provider-ping(测速 no-cors 兜底)) +test:unit 137 个单测文件(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) @@ -106,7 +106,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` | **8,665**(另守「占总源码 ≤ 40%」,见 `MAX_APP_JS_SHARE`) | -| `Workbench()` 行数 | 同上 `MAX_WORKBENCH_LINES` | **2,241** | +| `Workbench()` 行数 | 同上 `MAX_WORKBENCH_LINES` | **2,251** | | 单组件行数(不含 Workbench)| 同上 `MAX_APP_COMPONENT_LINES` | **423** | 三条都是**只减不增**。确需在 app.js 增长时,必须**同步上调上限并在 commit 里写理由**(等于显式记账,不会悄悄发生)。 diff --git a/app.js b/app.js index 7868e55..164ed53 100644 --- a/app.js +++ b/app.js @@ -98,6 +98,7 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct } // v3.26.143:默认不提升 world/grid 合成层(参考 infinite-canvas);诊断页可显式 opt-in。 try { document.documentElement.dataset.layers = lsGet('iwb_layers_on', false) ? 'on' : 'off' } catch (e) { /* ignore */ } + try { const V3 = (typeof window !== 'undefined' && window.IWBCanvasV3); if (V3 && typeof V3.init === 'function') V3.init() } catch (e) { /* ignore */ } try { if (lsGet('iwb_noblur_on', false)) document.documentElement.dataset.noblur = 'on' } catch (e) { /* ignore */ } // 桌面端保存二进制:有导出目录直接写 Uint8Array(不弹框),没目录才弹「另存为」;刻意不经 base64,省一次全量编解码。 const wSaveBlobNative = async (blob, name, title) => { @@ -3472,6 +3473,7 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct // 连线几何与合法性(纯函数收编到 src/canvas-geometry.js,P2-9):无依赖,直接用模块 const CanvasGeometry = (typeof window !== 'undefined' && window.IWBCanvasGeometry) || null const IWBCanvasEdges = (typeof window !== 'undefined' && window.IWBCanvasEdges) || { EdgeCanvas: () => null } + const IWCanvasV3NodeLayer = (typeof window !== 'undefined' && window.IWBCanvasV3NodeLayer) || { CanvasNodeLayer: () => null } // 撤销历史快照纯判定(收编到 src/canvas-history.js,P2-9):无依赖,直接用模块 const CanvasHistory = (typeof window !== 'undefined' && window.IWBCanvasHistory) || null // 工作台列表纯变换(收编到 src/workspace-list.js,状态模型 epic · Pilot 3 片 A):无依赖,直接用模块 @@ -6015,6 +6017,7 @@ const tbCenterSeed = (type, refs) => { const [groupNameDraft, setGroupNameDraft] = useState('') const [selEdge, setSelEdge] = useState(null) const [hoverEdgeId, setHoverEdgeId] = useState(null) + const canvasV3On = !!(typeof window !== 'undefined' && window.IWBCanvasV3 && window.IWBCanvasV3.isEnabled && window.IWBCanvasV3.isEnabled()) const [conn, setConn] = useState(null) const [connTarget, setConnTarget] = useState(null) const [ctxMenu, setCtxMenu] = useState(null) @@ -7345,8 +7348,9 @@ const tbCenterSeed = (type, refs) => { // 松手/停止滚轮后再提交一次 state,保证与 React 渲染值一致。 const applyViewportDom = (x, y, scale) => { CanvasGeometry.applyViewportDom(canvasEl.el, canvasSize, x, y, scale, refs.gridOpts) - // 边线视觉层是 canvas:手势期间命令式重画,避免等 React + // 边线/节点 canvas:手势期间命令式重画,避免等 React try { if (typeof refs.edgeCanvasDraw === 'function') refs.edgeCanvasDraw(x, y, scale) } catch (e) { /* ignore */ } + try { if (typeof refs.nodeCanvasDraw === 'function') refs.nodeCanvasDraw(x, y, scale) } catch (e) { /* ignore */ } } // LOD 滞回状态:plain 在 <15% 进入、>18% 退出(用 ref 保存,不触发额外渲染) @@ -7643,7 +7647,7 @@ const tbCenterSeed = (type, refs) => { )) } const nodeEls = IWBCanvasNodes.buildNodeEls({ - CanvasGeometry, CanvasStore, EMPTY_OBJ, NODE_W, NodeCardMemo, addRefFromUrl, batchPortTop, batchSourcesMap, canConnect, cancelRun, config, connTarget, + CanvasGeometry, CanvasStore, EMPTY_OBJ, NODE_W, NodeCardMemo, addRefFromUrl, batchPortTop, batchSourcesMap, canConnect, cancelRun, config, connTarget, canvasV3On, defaultNodeBoxWidth, deleteNodes, duplicateNodes, edges, el, generationConcurrency, hOf, inPortWorld, isBatchSrc, lodViewport, nodeDerived, nodeOnMeasure, nodeOnPreview, nodeOnSelect, nodeTypeH, nodeWidth, nodes, pushHistory, refs, runLLM, runLayerNode, runNode, runOutSources, saveNow, sel, selRef, setConn, setConnTarget, setNotice, setSel, taskCountOf, thumbRev, typesRev, uiZoom, uid, updateNode, visibleIds, wLodEnabled, zoomToNode, @@ -8077,6 +8081,13 @@ const tbCenterSeed = (type, refs) => { computeEdgePath, viewport, selEdge, focusNodeId, edgeHover, hoverEdgeId, tempD, connTarget, onReady: (fn) => { refs.edgeCanvasDraw = fn }, }), + // Canvas V3:未选中的 ref 节点卡片/图片画在 canvas;DOM 只保留 hit proxy。 + canvasV3On ? el(IWCanvasV3NodeLayer.CanvasNodeLayer, { + nodes: nodes.filter((n) => visibleIds.has(n.id)), viewport, sel, + widthOf: nodeWidth, heightOf: hOf, + imageFor: (node, raw) => { try { return wImgSrcForNode(raw, 320) || '' } catch (e) { return '' } }, + onReady: (fn) => { refs.nodeCanvasDraw = fn }, + }) : null, // 透明 hit path:选择/双击/悬停仍走 SVG(canvas pointer-events:none)。 el('svg', Object.assign({ className: 'iwb-edges' }, CanvasGeometry.edgeLayerProps(canvasSize)), el('g', { className: 'iwb-edge-world', transform: CanvasGeometry.edgeGroupTransform(viewport) }, edgeEls)), @@ -8145,7 +8156,7 @@ const tbCenterSeed = (type, refs) => { onSaveNow: saveNow, config, diagStats: () => wDiagStats(refs.nodes, refs.workspaces), - diagExtras: () => ({ persist: storagePersist, swallowed: (RuntimeMetrics && RuntimeMetrics.snapshot) ? RuntimeMetrics.snapshot() : null, procRssMB: wProcRssMB, layers: !!(document && document.documentElement && document.documentElement.dataset.layers === 'on'), noblur: (document && document.documentElement && document.documentElement.dataset.noblur === 'on'), dom: (function () { try { return { els: document.getElementsByTagName('*').length, dock: document.querySelectorAll('.iwb-dock *').length, cards: document.querySelectorAll('.iwb-history-item').length } } catch (e) { return null } })() }), // v3.26.121 RSS + v3.26.127 DOM 规模 // 持久化 + 被忽略错误(2026-11-07) + diagExtras: () => ({ persist: storagePersist, swallowed: (RuntimeMetrics && RuntimeMetrics.snapshot) ? RuntimeMetrics.snapshot() : null, procRssMB: wProcRssMB, layers: !!(document && document.documentElement && document.documentElement.dataset.layers === 'on'), canvasV3: !!(window && window.IWBCanvasV3 && window.IWBCanvasV3.isEnabled && window.IWBCanvasV3.isEnabled()), noblur: (document && document.documentElement && document.documentElement.dataset.noblur === 'on'), dom: (function () { try { return { els: document.getElementsByTagName('*').length, dock: document.querySelectorAll('.iwb-dock *').length, cards: document.querySelectorAll('.iwb-history-item').length } } catch (e) { return null } })() }), // v3.26.121 RSS + v3.26.127 DOM 规模 // 持久化 + 被忽略错误(2026-11-07) ...autoBackupKit, // autoBackup / autoBackupSave / autoBackupRestore / autoBackupRefresh diagText: () => buildRuntimeDiagnosticsText([], (typeof window !== 'undefined' && window.__IWB_BUILD_META__) || {}), onExportDiag: () => exportRuntimeDiagnostics(), @@ -8159,6 +8170,7 @@ const tbCenterSeed = (type, refs) => { onDiagDetail: () => wDiagDetail(), // v3.26.136:合成层常驻提升开关(立即生效,改完看「进程实测」对比) onToggleLayers: (on) => { try { document.documentElement.dataset.layers = on ? 'on' : 'off'; lsSet('iwb_layers_on', !!on) } catch (e) { /* ignore */ } }, + onToggleCanvasV3: (on) => { try { if (window.IWBCanvasV3) window.IWBCanvasV3.setEnabled(!!on) } catch (e) { /* ignore */ } }, onToggleNoBlur: (on) => { try { if (on) document.documentElement.dataset.noblur = 'on'; else delete document.documentElement.dataset.noblur; lsSet('iwb_noblur_on', !!on) } catch (e) { /* ignore */ } }, }), document.body) : null, helpOpen ? ReactDOM.createPortal(el('div', { className: 'iwb-modal-mask', onWheel: (e) => e.stopPropagation(), onPointerDown: (e) => { if (e.target === e.currentTarget) setHelpOpen(false) } }, diff --git a/docs/plans/canvas-v3-long-term.md b/docs/plans/canvas-v3-long-term.md new file mode 100644 index 0000000..1d78218 --- /dev/null +++ b/docs/plans/canvas-v3-long-term.md @@ -0,0 +1,98 @@ +# Canvas V3 长期迁移计划(静态 Canvas + DOM overlay) + +> 目标:把画布从“每节点完整 DOM”迁移到“静态内容 Canvas 绘制 + 只给选中/编辑节点挂 DOM”,降低 WKWebView 的布局/绘制/DOM 成本;保留旧 DOM 路径可回滚。 +> +> 基线:v3.26.144(Canvas 边线、平移全量渲染、world 默认不合成)。 +> 参考:Excalidraw(静态 canvas + overlay)、tldraw(DOM shape + 空间索引 + 手势冻结)。 + +## 状态 + +| 阶段 | 内容 | 状态 | 验收 | +|---|---|---|---| +| P0 | 特性开关、渲染接口、基线指标 | 已完成(2026-12-01) | 关闭开关时行为零变化 | +| P1 | 图片/ref 节点 Canvas 化 + 选中 DOM overlay | 进行中(垂直切片原型,默认关闭) | 100 图节点 DOM < 500;平移无空白 | +| P2 | 内置文本/gen/out/combine/batch/relay 节点 Canvas 化 | 待开始 | DOM < 500;编辑/生成不回归 | +| P3 | 插件节点 fallback + browser/webview | 待开始 | 旧插件可用;仅可见/选中挂 DOM | +| P4 | 稳定化、A/B、默认开启、旧路径退场 | 待开始 | 视觉/e2e/性能门禁通过 | + +## 目标架构 + +```text +SceneStore(纯数据,沿用现有 nodes/edges/groups) + ├─ CanvasRenderer(rAF、视口裁剪、分层) + │ ├─ grid(CSS,视口大小) + │ ├─ edges(已有 Canvas) + │ ├─ node frames / images / titles / group boxes + │ └─ selection / ports / progress + └─ DOM Overlay + ├─ 选中节点编辑 UI(输入框/下拉/按钮/插件正文) + ├─ 浮动工具条/菜单/面板 + └─ 原生 webview / 复杂插件 +``` + +## P0:基础设施(当前) + +- [ ] 新增 `src/canvas-v3.js`:`isEnabled()` / `setEnabled()` / `init()` / `stats()`; +- [ ] localStorage 键 `iwb_canvas_v3`,根节点 `data-canvas-v3="on|off"`; +- [ ] build sourceModules 登记模块; +- [ ] app 启动 init(关闭时零行为变化); +- [ ] 诊断页开关 + `diagExtras.canvasV3`; +- [ ] 单测:开关读写、默认关闭、根属性同步; +- [ ] 基线记录:100 节点 DOM/内存/长帧; +- [ ] 关闭开关回归:e2e/构建通过。 + +## P1:图片/ref 节点 Canvas 化 + +- [ ] 新增 `CanvasNodeLayer`(canvas 位于 world 之下); +- [ ] 绘制 ref 卡片框、标题、缩略图、选中环、端口(先只画不交互); +- [ ] 未选中 ref 节点用 `NodeHitProxy` 替身:保留 pointerdown/drag/select,不渲染完整 body; +- [ ] 选中 ref 节点恢复完整 NodeCard(DOM overlay); +- [ ] 命中测试:节点矩形、输出端口;双击预览/右键菜单入口; +- [ ] 图片缓存:复用现有 display thumb,不新增解码路径; +- [ ] e2e:图片节点选择/拖动/替换/标注不回归; +- [ ] 性能:100 图节点 DOM/内存/长帧对比。 + +## P2:内置节点 + +- 先 prompt/textout/combine/batch/relay,再 gen/layer/out; +- 文本画到 canvas,编辑时 DOM textarea overlay; +- 生成任务条/进度环 canvas 绘制; +- 选中节点才挂完整编辑 UI; +- 撤销/持久化沿用 CanvasStore。 + +## P3:插件与原生 webview + +- 插件 API(可选):`ctx.canvasRender.drawStatic/hitTest/openEditor`; +- 无能力插件:仅视口内实例 + 选中时完整 DOM; +- browser/原生 webview:始终 DOM/native,不参与 Canvas; +- 插件旧版本 fallback。 + +## P4:稳定化 + +- 视觉回归亮/暗色、选中态、组框; +- e2e:平移 1000px、缩放、拖拽、连线、文本编辑、生成; +- 性能门禁:100/500 节点;DOM、graphics、长帧; +- 默认开启,旧路径保留一个版本。 + +## 验收指标 + +- 100 节点 DOM 元素 < 500(当前 2487); +- WebContent graphics < 300MB; +- 平移/缩放无空白/节点迟到; +- 图片/文本/生成/插件主要链路不回归; +- 关闭开关即回旧版。 + +## 风险 + +- Canvas 文本度量与 DOM 不完全一致; +- 输入法/可访问性必须 DOM overlay; +- 插件 DOM 生态无法一次性迁移; +- 命中测试/端口优先级需重写; +- 双路径维护成本高。 + +## 执行原则 + +1. 默认关闭,按阶段 A/B,可回滚; +2. 不改数据格式; +3. 先图片节点垂直切片,验证收益后再扩大; +4. 每阶段在 `canvas-v3-progress.md` 记录数据与经验。 diff --git a/docs/plans/canvas-v3-progress.md b/docs/plans/canvas-v3-progress.md new file mode 100644 index 0000000..2c45ac1 --- /dev/null +++ b/docs/plans/canvas-v3-progress.md @@ -0,0 +1,74 @@ +# Canvas V3 进度与经验 + +> 计划:[canvas-v3-long-term.md](./canvas-v3-long-term.md) + +## 2026-12-01 · P0 完成 + +已完成: + +- `src/canvas-v3.js`:`isEnabled / setEnabled / init / stats`,localStorage 键 `iwb_canvas_v3`,根属性 `data-canvas-v3`; +- `scripts/build.js` 登记,app 启动 `init()`(默认 off,零行为变化); +- 诊断页新增「Canvas V3(实验,需刷新)」开关; +- 单测 `tests/canvas-v3-test.js` 接入 `test:unit`; +- 事实/边界/源码棘轮已同步。 + +基线(Web 测试环境,100 节点数据但视口内实际挂载 20 个): + +- DOM 元素 1170; +- `data-node-id` 20; +- `data-canvas-v3="off"`,`IWBCanvasV3.isEnabled() === false`。 + +经验: + +- 当前 DOM 基线比之前诊断的 2487 低,是因为视口裁剪只挂载可见节点;做 100 节点性能对比时必须固定视口/缩放,否则数据不可比。 +- Phase 0 不改变任何渲染路径,先保住旧路径可回滚。 + + +## 2026-12-01 · P1 垂直切片(实验,默认关闭) + +已实现: + +- `src/canvas-v3-node-layer.js`:viewport canvas 画未选中 ref 节点的卡片框、标题、图片区; +- `src/ui-canvas-nodes.js`:Canvas V3 开启时,未选中 ref 节点只渲染透明 `.iwb-node-hit-proxy`; +- 选中后立即恢复完整 `NodeCard`(DOM overlay); +- 拖动走现有 `refs.bodyDown` 全局指针逻辑;平移/拖节点命令式重画 canvas; +- 诊断页开关「Canvas V3(实验,需刷新)」。 + +实测(Web 测试环境,2 ref + 1 prompt): + +- `.iwb-node-hit-proxy` 2 个,完整 `.iwb-node` 1 个; +- DOM 元素 307; +- canvas 有绘制像素(31142); +- 点击 proxy 后:proxy 2→1、NodeCard 1→2、selected 1,说明选中恢复 DOM overlay 正常。 + +已知限制(P1 继续要补): + +- 未选中 ref 没有端口/右键菜单/双击预览入口(先选中后恢复 NodeCard 才有); +- 绘制样式是近似卡片,不是 NodeCard 像素级; +- 图片只走 `wImgSrcForNode(raw, 320)`,跨域图可能不画; +- 还没做 100 图节点的 DOM/内存/长帧对比(20 图节点已量,见下)。 + +经验: + +- “Canvas 画静态 + 选中恢复 NodeCard”路线可行;最小切片只需一个 hit proxy,不必先重写命中测试/全部交互。 +- 下一步优先补端口/右键/双击与 100 节点压测,而不是继续扩节点类型。 +### P1 20 图节点实测(Web,同一批 20 个 ref) + +| 模式 | DOM 元素 | 完整 NodeCard | hit proxy | +|---|---:|---:|---:| +| Canvas V3 off | 1687 | 20 | 0 | +| Canvas V3 on | 802 | 0(未选中) | 20 | + +- 降幅 **52%**(1687 → 802); +- canvas 正常绘制 20 张图片(pixels 2592605,截图见 `/Users/qiqi/.playwright-mcp/canvas-v3-20.png`); +- 选中一个 proxy 后:proxy 20→19、NodeCard 0→1、selected 1,说明 DOM overlay 正常。 + +结论:垂直切片方向成立,但 20 图节点还不能代表 WKWebView 的最终收益;下一步要在桌面端实机看 graphics/长帧,并补端口/右键/双击预览。 + +### 门禁 + +- `npm run verify:ci` 通过(33 e2e + 单测 + facts/boundary/ratchet); +- Canvas V3 默认关闭;关闭时旧路径零行为变化; +- 开启方式:诊断页「Canvas V3(实验,需刷新)」或 `IWBCanvasV3.setEnabled(true)` 后刷新。 + + diff --git a/docs/standards/architecture-current-state.md b/docs/standards/architecture-current-state.md index f0276b5..1529305 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 **8,640 行**(**双层预算**:绝对上限 8,665 / 占总源码 ≤ 40%,现 **25.9%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **2,241 行**(上限 **2,241**,余量 0;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **120** 个模块 / 24,764 行,`sourceModules` 120 项;v3.24.68 新增 `clipboard-graph.js`,v3.24.74 新增 `image-admit.js`,v3.24.75 新增 `image-dedupe.js`,v3.24.76 新增 `workspace-purge.js`,v3.24.79 新增 `generation-provider-ping.js`,v3.24.80 删除无调用的 `createWBFlushViewport` 17 行)。 +- `app.js` = 单 IIFE **8,652 行**(**双层预算**:绝对上限 8,665 / 占总源码 ≤ 40%,现 **25.7%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **2,251 行**(上限 **2,251**,余量 0;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **122** 个模块 / 25,000 行,`sourceModules` 122 项;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`。 ## 1.5 内存基线(2026-11-30,v3.26.115,Windows / WebView2 实测) @@ -192,7 +192,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` 不引用模块全局)。**120 个模块中 59 个导出**被 `app.js` 读取;其余为未接线 / 仅测试 / 零引用(见下)。 + - **判定法**:`global.X =` / `root.X =` 判「导出」;跨文件裸引用判「读」;排除自合并(`src/runtime-constants.js:9`)。`app.js` 是**唯一生产消费者**(无 HTML 入口;`sw.js` 不引用模块全局)。**122 个模块中 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` 自注册后读回(装载路径)。 @@ -208,7 +208,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 耦合面(**99** 项)与 `sourceModules` 顺序(**120** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。 + - **耦合面已冻结**:`tests/architecture-boundary-guard-test.js`(进 `npm run test:unit` 末环)冻结 app.js↔src 耦合面(**101** 项)与 `sourceModules` 顺序(**122** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。 ## 12. 易踩的坑 @@ -279,7 +279,7 @@ **信任模型(必须明示)**:形态 A 的插件是**可信代码**(与核心同权限、无沙箱);启停与设置是 UX 与可维护性手段,**不是安全边界**(同 §13.27 教训:前端开关一定可被绕过)。 -**守门与快照**:`tests/architecture-boundary-guard-test.js` 冻结「app.js ↔ src 耦合面」(**99** 项)与 `sourceModules` 顺序(**120** 项);新增模块、新增耦合、新增 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 耦合面」(**101** 项)与 `sourceModules` 顺序(**122** 项);新增模块、新增耦合、新增 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 0135e88..3707002 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/result-img-doubleclick-test.js && node tests/gallery-audit-test.js && 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/generation-default-model-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/clipboard-native-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 && node tests/image-file-ref-preview-test.js && node tests/icon-assets-test.js && node tests/strip-plugins-test.js && node tests/plugin-manifest-hashes-test.js && node tests/boot-progress-test.js && node tests/idb-gc-plugin-refs-test.js", + "test:unit": "node tests/result-img-doubleclick-test.js && node tests/gallery-audit-test.js && 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/generation-default-model-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/clipboard-native-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 && node tests/image-file-ref-preview-test.js && node tests/icon-assets-test.js && node tests/strip-plugins-test.js && node tests/plugin-manifest-hashes-test.js && node tests/boot-progress-test.js && node tests/idb-gc-plugin-refs-test.js && node tests/canvas-v3-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/scripts/build.js b/scripts/build.js index 5be0ff9..3b343b5 100644 --- a/scripts/build.js +++ b/scripts/build.js @@ -102,6 +102,8 @@ const sourceModules = [ 'ui-dock-panels.js', 'theme-tokens.js', 'canvas-grid.js', + 'canvas-v3.js', + 'canvas-v3-node-layer.js', 'image-display-thumb.js', 'image-cache-migrate.js', 'runtime-frame-probe.js', diff --git a/src/canvas-v3-node-layer.js b/src/canvas-v3-node-layer.js new file mode 100644 index 0000000..f35b3ec --- /dev/null +++ b/src/canvas-v3-node-layer.js @@ -0,0 +1,143 @@ +/* canvas-v3-node-layer.js —— Canvas V3 图片节点静态层(2026-12-01,P1 垂直切片) + * + * 仅当 data-canvas-v3="on" 时由 app 挂载;未选中的 ref 节点由 canvas 画卡片/标题/图片, + * DOM 只保留一个透明 hit proxy。选中后恢复完整 NodeCard。 + * 目标与限制见 docs/plans/canvas-v3-long-term.md。 + */ +;(function (global) { + 'use strict' + const React = global.React || {} + const el = (type, prop, ...children) => React.createElement(type, prop, ...children) + const useRef = React.useRef + const useEffect = React.useEffect + const useState = React.useState + const imgCache = new Map() + + function css (name, fallback) { + try { + const v = getComputedStyle(document.documentElement).getPropertyValue(name).trim() + return v || fallback + } catch (e) { return fallback } + } + + function roundRect (ctx, x, y, w, h, r) { + const rr = Math.max(0, Math.min(r, w / 2, h / 2)) + ctx.beginPath() + ctx.moveTo(x + rr, y) + ctx.arcTo(x + w, y, x + w, y + h, rr) + ctx.arcTo(x + w, y + h, x, y + h, rr) + ctx.arcTo(x, y + h, x, y, rr) + ctx.arcTo(x, y, x + w, y, rr) + ctx.closePath() + } + + function imageOf (url, onLoad) { + if (!url) return null + let entry = imgCache.get(url) + if (!entry) { + entry = { img: new Image(), loaded: false } + entry.img.decoding = 'async' + entry.img.onload = () => { entry.loaded = true; if (typeof onLoad === 'function') onLoad() } + entry.img.onerror = () => { entry.failed = true; if (typeof onLoad === 'function') onLoad() } + entry.img.src = url + imgCache.set(url, entry) + } + return entry + } + + function draw (canvas, o) { + if (!canvas || !o || typeof canvas.getContext !== 'function') return + const rect = canvas.getBoundingClientRect ? canvas.getBoundingClientRect() : null + const w = Math.max(1, Math.round((rect && rect.width) || canvas.clientWidth || 1)) + const h = Math.max(1, Math.round((rect && rect.height) || canvas.clientHeight || 1)) + const dpr = Math.min(2, (typeof devicePixelRatio === 'number' && devicePixelRatio > 0) ? devicePixelRatio : 1) + if (canvas.width !== Math.round(w * dpr) || canvas.height !== Math.round(h * dpr)) { + canvas.width = Math.round(w * dpr); canvas.height = Math.round(h * dpr) + } + const ctx = canvas.getContext('2d') + if (!ctx) return + ctx.setTransform(dpr, 0, 0, dpr, 0, 0) + ctx.clearRect(0, 0, w, h) + const vp = o.viewport || { x: 0, y: 0, scale: 1 } + const scale = Number(vp.scale) > 0 ? Number(vp.scale) : 1 + const nodes = Array.isArray(o.nodes) ? o.nodes : [] + const sel = Array.isArray(o.sel) ? o.sel : [] + const widthOf = typeof o.widthOf === 'function' ? o.widthOf : (n) => n.w || 240 + const heightOf = typeof o.heightOf === 'function' ? o.heightOf : (n) => n.h || 220 + const imageFor = typeof o.imageFor === 'function' ? o.imageFor : () => '' + const onImageLoad = o.onImageLoad + const bg = css('--iwb-panel', '#ffffff') + const border = css('--iwb-border2', '#d7dbe2') + const text = css('--iwb-text2', '#5f6673') + const accent = css('--iwb-brand', '#6b7280') + const radius = 14 + const headH = 34 + ctx.setTransform(dpr * scale, 0, 0, dpr * scale, dpr * (Number(vp.x) || 0), dpr * (Number(vp.y) || 0)) + ctx.lineJoin = 'round' + for (const n of nodes) { + if (!n || n.type !== 'ref' || sel.indexOf(n.id) >= 0) continue + const x = n.x, y = n.y, nw = widthOf(n), nh = heightOf(n) + // 卡片 + ctx.fillStyle = bg + roundRect(ctx, x, y, nw, nh, radius) + ctx.fill() + ctx.strokeStyle = border + ctx.lineWidth = 1 / scale + ctx.stroke() + // 标题 + ctx.fillStyle = text + ctx.font = '600 ' + Math.max(10, 12 / scale * 0.9) + 'px -apple-system, BlinkMacSystemFont, "PingFang SC", sans-serif' + const title = String((n.data && (n.data.title || n.data.name)) || '参考图') + ctx.save() + ctx.beginPath(); ctx.rect(x + 10, y, Math.max(0, nw - 20), headH); ctx.clip() + ctx.fillText(title, x + 12, y + 21) + ctx.restore() + // 图片区 + const pad = 10 + const ix = x + pad, iy = y + headH, iw = Math.max(1, nw - pad * 2), ih = Math.max(1, nh - headH - pad) + const raw = n.data && (n.data.data || n.data.url) + const url = raw ? imageFor(n, raw) : '' + const entry = url ? imageOf(url, onImageLoad) : null + if (entry && entry.loaded && !entry.failed) { + const iw0 = entry.img.naturalWidth || iw + const ih0 = entry.img.naturalHeight || ih + const k = Math.min(iw / iw0, ih / ih0) + const dw = iw0 * k, dh = ih0 * k + try { ctx.drawImage(entry.img, ix + (iw - dw) / 2, iy + (ih - dh) / 2, dw, dh) } catch (e) { /* cross-origin */ } + } else { + ctx.fillStyle = css('--iwb-layer2', '#f1f2f4') + roundRect(ctx, ix, iy, iw, ih, 10) + ctx.fill() + ctx.fillStyle = text + ctx.font = Math.max(10, 12 / scale * 0.9) + 'px -apple-system, BlinkMacSystemFont, "PingFang SC", sans-serif' + ctx.fillText(entry && entry.failed ? '图片源失效' : '图片加载中…', ix + 12, iy + 24) + } + // 选中/连线提示用边框色(当前未选中,保留扩展点) + void accent + } + } + + function CanvasNodeLayer (props) { + const ref = useRef(null) + const latest = useRef(props) + latest.current = props + const [rev, setRev] = useState(0) + void rev + useEffect(() => { + const canvas = ref.current + if (!canvas) return + const p = latest.current || {} + draw(canvas, Object.assign({}, p, { onImageLoad: () => setRev((v) => v + 1) })) + if (typeof p.onReady === 'function') { + p.onReady(function (x, y, scale) { + const q = latest.current || {} + draw(canvas, Object.assign({}, q, { viewport: { x: x, y: y, scale: scale }, onImageLoad: () => setRev((v) => v + 1) })) + }) + } + }) + useEffect(() => () => { if (typeof props.onReady === 'function') props.onReady(null) }, []) + return el('canvas', { className: 'iwb-node-canvas', 'aria-hidden': 'true', ref: ref }) + } + + global.IWBCanvasV3NodeLayer = { CanvasNodeLayer, draw } +})(typeof window !== 'undefined' ? window : globalThis) diff --git a/src/canvas-v3.js b/src/canvas-v3.js new file mode 100644 index 0000000..cf08266 --- /dev/null +++ b/src/canvas-v3.js @@ -0,0 +1,64 @@ +/* canvas-v3.js —— Canvas 静态渲染迁移的特性开关(2026-12-01,Phase 0) + * + * 默认关闭;开启后只改变 data-canvas-v3 与后续渲染器选择,不影响数据格式。 + * 目标架构见 docs/plans/canvas-v3-long-term.md。 + */ +;(function (global) { + 'use strict' + const KEY = 'iwb_canvas_v3' + const ATTR = 'canvasV3' + + // src 内不直调 localStorage:统一走 IWBStorageLocal 门面(桌面端会落到资料目录底座)。 + function store () { + try { + const S = global.IWBStorageLocal + return (S && typeof S.getStore === 'function') ? S.getStore() : null + } catch (e) { return null } + } + + function isEnabled () { + try { + const s = store() + if (s && typeof s.rawGet === 'function') return s.rawGet(KEY, '0') === '1' + } catch (e) { /* ignore */ } + return false + } + + function syncRoot (on) { + try { + if (typeof document !== 'undefined' && document.documentElement) { + document.documentElement.dataset[ATTR] = on ? 'on' : 'off' + } + } catch (e) { /* ignore */ } + } + + function setEnabled (on) { + const next = !!on + try { + const s = store() + if (s && typeof s.rawSet === 'function') s.rawSet(KEY, next ? '1' : '0') + } catch (e) { /* ignore */ } + syncRoot(next) + try { + if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof CustomEvent === 'function') { + window.dispatchEvent(new CustomEvent('iwb:canvas-v3', { detail: { enabled: next } })) + } + } catch (e) { /* ignore */ } + return next + } + + function init () { + const on = isEnabled() + syncRoot(on) + return on + } + + function stats () { + const on = isEnabled() + let dom = -1 + try { dom = document.getElementsByTagName('*').length } catch (e) { /* ignore */ } + return { enabled: on, dom } + } + + global.IWBCanvasV3 = { KEY, isEnabled, setEnabled, init, stats } +})(typeof window !== 'undefined' ? window : globalThis) diff --git a/src/ui-canvas-nodes.js b/src/ui-canvas-nodes.js index b934762..3e57e4b 100644 --- a/src/ui-canvas-nodes.js +++ b/src/ui-canvas-nodes.js @@ -9,11 +9,34 @@ 'use strict' function buildNodeEls(ctx) { - const { CanvasGeometry, CanvasStore, EMPTY_OBJ, NODE_W, NodeCardMemo, addRefFromUrl, batchPortTop, batchSourcesMap, canConnect, cancelRun, config, connTarget, defaultNodeBoxWidth, deleteNodes, duplicateNodes, edges, el, generationConcurrency, hOf, inPortWorld, isBatchSrc, lodViewport, nodeDerived, nodeOnMeasure, nodeOnPreview, nodeOnSelect, nodeTypeH, nodeWidth, nodes, pushHistory, refs, runLLM, runLayerNode, runNode, runOutSources, saveNow, sel, selRef, setConn, setConnTarget, setNotice, setSel, taskCountOf, thumbRev, typesRev, uiZoom, uid, updateNode, visibleIds, wLodEnabled, zoomToNode } = ctx + const { CanvasGeometry, CanvasStore, EMPTY_OBJ, NODE_W, NodeCardMemo, addRefFromUrl, batchPortTop, batchSourcesMap, canConnect, cancelRun, config, connTarget, canvasV3On, defaultNodeBoxWidth, deleteNodes, duplicateNodes, edges, el, generationConcurrency, hOf, inPortWorld, isBatchSrc, lodViewport, nodeDerived, nodeOnMeasure, nodeOnPreview, nodeOnSelect, nodeTypeH, nodeWidth, nodes, pushHistory, refs, runLLM, runLayerNode, runNode, runOutSources, saveNow, sel, selRef, setConn, setConnTarget, setNotice, setSel, taskCountOf, thumbRev, typesRev, uiZoom, uid, updateNode, visibleIds, wLodEnabled, zoomToNode } = ctx const nodeEls = [] const batchSourcesById = batchSourcesMap for (const n of nodes) { if (!visibleIds.has(n.id)) continue + // Canvas V3 P1:未选中的 ref 节点只保留透明 hit proxy,视觉由 canvas 画;选中后恢复完整 NodeCard。 + if (canvasV3On && n.type === 'ref' && !sel.includes(n.id)) { + nodeEls.push(el('div', { + key: n.id, + className: 'iwb-node-hit-proxy', + 'data-node-id': n.id, + style: { transform: 'translate(' + n.x + 'px, ' + n.y + 'px)', width: nodeWidth(n) + 'px', height: hOf(n) + 'px' }, + onPointerDown: (e) => { + if (e.button !== 0) return + e.stopPropagation() + const curSel = selRef.current + const ids = (e.shiftKey || e.metaKey || e.ctrlKey) + ? (curSel.includes(n.id) ? curSel.filter((x) => x !== n.id) : curSel.concat([n.id])) + : (curSel.includes(n.id) ? curSel.slice() : [n.id]) + const start = {} + for (const x of refs.nodes) if (ids.includes(x.id)) start[x.id] = { x: x.x, y: x.y } + refs.bodyDown = { id: n.id, ids, start, sx: e.clientX / uiZoom(), sy: e.clientY / uiZoom(), active: false } + setSel(ids) + }, + onDoubleClick: (e) => { e.stopPropagation() }, + }, null)) + continue + } // 细粒度:只传该节点相关的 busy/progress/connTarget(其他节点引用稳定,memo 跳过) let busySelf = nodeDerived.busyById.get(n.id) || EMPTY_OBJ let progSelf = nodeDerived.progById.get(n.id) || EMPTY_OBJ diff --git a/src/ui-canvas-pointer.js b/src/ui-canvas-pointer.js index 1b44a58..d00c613 100644 --- a/src/ui-canvas-pointer.js +++ b/src/ui-canvas-pointer.js @@ -61,8 +61,9 @@ const gEl = el0.querySelector('[data-edge-id="' + ed.id + '"]') if (gEl && d) { const ps = gEl.querySelectorAll('path'); for (let i = 0; i < ps.length; i++) ps[i].setAttribute('d', d) } } - // 边线视觉层是 canvas:拖动中坐标已就地更新,命令式重画一次(不触发 React)。 + // 边线/节点 canvas:拖动中坐标已就地更新,命令式重画一次(不触发 React)。 try { if (typeof refs.edgeCanvasDraw === 'function') refs.edgeCanvasDraw(refs.viewport.x, refs.viewport.y, refs.viewport.scale) } catch (e) { /* ignore */ } + try { if (typeof refs.nodeCanvasDraw === 'function') refs.nodeCanvasDraw(refs.viewport.x, refs.viewport.y, refs.viewport.scale) } catch (e) { /* ignore */ } // 节点组外框实时跟随:外框由成员包围盒派生,拖动中不重渲染 → 必须就地改 DOM(否则松手才跳)。 // 用 refs.nodeGroupMap 反查受影响的组,避免每帧 O(groups×members) 扫描。 if (refs.nodeGroupMap && refs.nodeGroupMap.size) { diff --git a/src/ui-settings-tab-diag.js b/src/ui-settings-tab-diag.js index 1845b75..3bdb4b3 100644 --- a/src/ui-settings-tab-diag.js +++ b/src/ui-settings-tab-diag.js @@ -110,6 +110,9 @@ el('label', { className: 'iwb-diag-kv', title: '打开后整个画布世界会被提升成一个常驻合成层:拖拽/缩放更顺,但内存会明显上涨(实测 +700MB 级)。改完等 10 秒看「进程实测」对比。' }, el('input', { type: 'checkbox', checked: !!(extras && extras.layers), onChange: (e) => { if (typeof props.onToggleLayers === 'function') props.onToggleLayers(e.target.checked) } }), ' 合成层常驻提升'), + el('label', { className: 'iwb-diag-kv', title: 'Canvas V3 实验:静态节点内容改 Canvas 绘制,只给选中/编辑节点挂 DOM。默认关闭,开启后需刷新;见 docs/plans/canvas-v3-long-term.md' }, + el('input', { type: 'checkbox', checked: !!(extras && extras.canvasV3), onChange: (e) => { if (typeof props.onToggleCanvasV3 === 'function') props.onToggleCanvasV3(e.target.checked) } }), + ' Canvas V3(实验,需刷新)'), el('label', { className: 'iwb-diag-kv', title: '关掉所有 backdrop-filter(顶栏/停靠栏的毛玻璃),用于二分 graphics 占用' }, el('input', { type: 'checkbox', checked: !!(extras && extras.noblur), onChange: (e) => { if (typeof props.onToggleNoBlur === 'function') props.onToggleNoBlur(e.target.checked) } }), ' 禁用毛玻璃'), diff --git a/style.css b/style.css index 2547ae1..1689130 100644 --- a/style.css +++ b/style.css @@ -33,6 +33,9 @@ button { font-family: inherit; } .iwb-world { position: absolute; left: 0; top: 0; transform-origin: 0 0; } .iwb-edges { position: absolute; left: 0; top: 0; pointer-events: none; } .iwb-edge-canvas { position: absolute; inset: 0; width: 100%; height: 100%; pointer-events: none; } +.iwb-node-canvas { position: absolute; inset: 0; width: 100%; height: 100%; pointer-events: none; } +.iwb-node-hit-proxy { position: absolute; left: 0; top: 0; background: transparent; border: 0; pointer-events: auto; cursor: grab; } +.iwb-node-hit-proxy:active { cursor: grabbing; } .iwb-edge-hit { fill: none; stroke: transparent; stroke-width: 14; pointer-events: stroke; cursor: pointer; } .iwb-edge-hit:hover { stroke: color-mix(in srgb, var(--iwb-brand) 16%, transparent); } .iwb-edge-hit:hover + .iwb-edge { stroke-width: calc(var(--iwb-edge-w) + 0.6px); stroke: var(--iwb-edge-hot); } diff --git a/tests/canvas-v3-test.js b/tests/canvas-v3-test.js new file mode 100644 index 0000000..c773858 --- /dev/null +++ b/tests/canvas-v3-test.js @@ -0,0 +1,50 @@ +'use strict' +const assert = require('assert') +const fs = require('fs') +const path = require('path') +const vm = require('vm') +const source = fs.readFileSync(path.join(__dirname, '..', 'src', 'canvas-v3.js'), 'utf8') + +function makeSandbox (initial) { + const store = new Map(Object.entries(initial || {})) + const events = [] + const root = { dataset: {} } + const localStorage = { + getItem: (k) => (store.has(k) ? store.get(k) : null), + setItem: (k, v) => { store.set(k, String(v)) }, + } + const document = { documentElement: root, getElementsByTagName: () => ({ length: 42 }) } + const window = { dispatchEvent: (e) => { events.push(e) } } + window.IWBStorageLocal = { getStore: () => ({ rawGet: (k, f) => (store.has(k) ? store.get(k) : f), rawSet: (k, v) => { store.set(k, String(v)); return true } }) } + class CustomEvent { constructor (type, init) { this.type = type; this.detail = init && init.detail } } + const storage = { rawGet: (k, f) => (store.has(k) ? store.get(k) : f), rawSet: (k, v) => { store.set(k, String(v)); return true } } + const sandbox = { window, document, localStorage, IWBStorageLocal: { getStore: () => storage }, CustomEvent, console } + vm.createContext(sandbox) + vm.runInContext(source, sandbox) + return { api: sandbox.window.IWBCanvasV3, root, store, events } +} + +{ + const s = makeSandbox({}) + assert.strictEqual(s.api.isEnabled(), false, '默认关闭') + assert.strictEqual(s.api.init(), false) + assert.strictEqual(s.root.dataset.canvasV3, 'off', '关闭时根属性为 off') +} +{ + const s = makeSandbox({ iwb_canvas_v3: '1' }) + assert.strictEqual(s.api.isEnabled(), true, 'localStorage=1 时开启') + assert.strictEqual(s.api.init(), true) + assert.strictEqual(s.root.dataset.canvasV3, 'on', '开启时根属性为 on') +} +{ + const s = makeSandbox({}) + assert.strictEqual(s.api.setEnabled(true), true) + assert.strictEqual(s.store.get('iwb_canvas_v3'), '1') + assert.strictEqual(s.root.dataset.canvasV3, 'on') + assert.strictEqual(s.events.length, 1) + assert.strictEqual(s.events[0].type, 'iwb:canvas-v3') + assert.strictEqual(s.events[0].detail.enabled, true) + assert.strictEqual(s.api.setEnabled(false), false) + assert.strictEqual(s.root.dataset.canvasV3, 'off') +} +console.log('canvas-v3 checks passed') diff --git a/tests/fixtures/iwb-app-global-reads.json b/tests/fixtures/iwb-app-global-reads.json index c7e8f42..44c7116 100644 --- a/tests/fixtures/iwb-app-global-reads.json +++ b/tests/fixtures/iwb-app-global-reads.json @@ -12,6 +12,8 @@ "IWBCanvasPointer", "IWBCanvasStore", "IWBCanvasText", + "IWBCanvasV3", + "IWBCanvasV3NodeLayer", "IWBCrashLog", "IWBDefaultGenModel", "IWBDesktop", diff --git a/tests/fixtures/iwb-source-modules-order.json b/tests/fixtures/iwb-source-modules-order.json index be1e12a..fadd224 100644 --- a/tests/fixtures/iwb-source-modules-order.json +++ b/tests/fixtures/iwb-source-modules-order.json @@ -74,6 +74,8 @@ "ui-dock-panels.js", "theme-tokens.js", "canvas-grid.js", + "canvas-v3.js", + "canvas-v3-node-layer.js", "image-display-thumb.js", "image-cache-migrate.js", "runtime-frame-probe.js", diff --git a/tests/source-text-ratchet-test.js b/tests/source-text-ratchet-test.js index 75aaa43..a31c328 100644 --- a/tests/source-text-ratchet-test.js +++ b/tests/source-text-ratchet-test.js @@ -213,7 +213,7 @@ const MAX_APP_JS_SHARE = 0.40 // 需要实时读 .iwb-world 变换 + 按同类型实测高度校正视觉中心;属装配层的 DOM 读取, // 放 src 会引入新的全局读取与边界快照改动,权衡后留在 app.js // +10(2026-11-01):背景色「悬停预览」的 DOM 补丁助手(纯 DOM,不写数据/不进撤销栈); // 属装配层最小的 DOM 操作,放 src 会引入新的全局读取与边界快照改动,权衡后留在 app.js -const MAX_WORKBENCH_LINES = 2241 // +10(2026-11-30 Canvas 边线装配:EdgeCanvas 组件、hoverEdgeId、手势命令式重画钩子;绘制逻辑在 src/ui-canvas-edges.js) // +52(2026-11-30:图片策略 v2 装配 + 诊断明细 + 浏览器窗口空闲休眠读数;预热的实现已抽到 src/ui-workbench-hooks.js 的 useGalleryPrewarm,下一步继续把 ctx 装配下沉以回落上限) // +11(2026-11-27:同上,Workbench 2169→2180) // 2026-11-26 复制/粘贴通道重写(+14:refs 新增粘贴时间戳/系统剪贴板可信标记、pasteCtx 增补 ids/clipboardOf/stageClip/readNativeText、bindCopy 装配) +const MAX_WORKBENCH_LINES = 2251 // +10(2026-11-30 Canvas 边线装配:EdgeCanvas 组件、hoverEdgeId、手势命令式重画钩子;绘制逻辑在 src/ui-canvas-edges.js) // +52(2026-11-30:图片策略 v2 装配 + 诊断明细 + 浏览器窗口空闲休眠读数;预热的实现已抽到 src/ui-workbench-hooks.js 的 useGalleryPrewarm,下一步继续把 ctx 装配下沉以回落上限) // +11(2026-11-27:同上,Workbench 2169→2180) // 2026-11-26 复制/粘贴通道重写(+14:refs 新增粘贴时间戳/系统剪贴板可信标记、pasteCtx 增补 ids/clipboardOf/stageClip/readNativeText、bindCopy 装配) // 2026-11-18 v3.25.21:模态层指针守卫(2 行) // 实测 3090 → 2998(省 92):① 生成取消族 cancelRunsFor/cancelRun/cancelTaskJobs // → src/runtime-workbench-logic.js 的 createCancelActions(−53);② 工作区列表写回族